1f99ccf65SEugene Zhulenev //===- PolynomialApproximation.cpp - Approximate math operations ----------===//
2f99ccf65SEugene Zhulenev //
3f99ccf65SEugene Zhulenev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f99ccf65SEugene Zhulenev // See https://llvm.org/LICENSE.txt for license information.
5f99ccf65SEugene Zhulenev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f99ccf65SEugene Zhulenev //
7f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===//
8f99ccf65SEugene Zhulenev //
9f99ccf65SEugene Zhulenev // This file implements expansion of math operations to fast approximations
10f99ccf65SEugene Zhulenev // that do not rely on any of the library functions.
11f99ccf65SEugene Zhulenev //
12f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===//
13ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMTypes.h"
15f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/IR/Math.h"
16f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/Transforms/Passes.h"
17f99ccf65SEugene Zhulenev #include "mlir/Dialect/Vector/VectorOps.h"
18f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h"
19ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
20f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h"
21f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
22ea7f211bSAhmed Taei #include <limits.h>
23f99ccf65SEugene Zhulenev 
24f99ccf65SEugene Zhulenev using namespace mlir;
25f99ccf65SEugene Zhulenev using namespace mlir::vector;
26f99ccf65SEugene Zhulenev 
27ce976d2dSEugene Zhulenev using TypePredicate = llvm::function_ref<bool(Type)>;
28ce976d2dSEugene Zhulenev 
29ce976d2dSEugene Zhulenev // Returns vector width if the element type is matching the predicate (scalars
30ce976d2dSEugene Zhulenev // that do match the predicate have width equal to `1`).
31ce976d2dSEugene Zhulenev static Optional<int> vectorWidth(Type type, TypePredicate pred) {
32ce976d2dSEugene Zhulenev   // If the type matches the predicate then its width is `1`.
33ce976d2dSEugene Zhulenev   if (pred(type))
34ce976d2dSEugene Zhulenev     return 1;
35ce976d2dSEugene Zhulenev 
36ce976d2dSEugene Zhulenev   // Otherwise check if the type is a vector type.
37ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
38ce976d2dSEugene Zhulenev   if (vectorType && pred(vectorType.getElementType())) {
39ce976d2dSEugene Zhulenev     assert(vectorType.getRank() == 1 && "only 1d vectors are supported");
40ce976d2dSEugene Zhulenev     return vectorType.getDimSize(0);
41ce976d2dSEugene Zhulenev   }
42ce976d2dSEugene Zhulenev 
43ce976d2dSEugene Zhulenev   return llvm::None;
44ce976d2dSEugene Zhulenev }
45ce976d2dSEugene Zhulenev 
46ce976d2dSEugene Zhulenev // Returns vector width of the type. If the type is a scalar returns `1`.
47ce976d2dSEugene Zhulenev static int vectorWidth(Type type) {
48ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
49ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getDimSize(0) : 1;
50ce976d2dSEugene Zhulenev }
51ce976d2dSEugene Zhulenev 
52ce976d2dSEugene Zhulenev // Returns vector element type. If the type is a scalar returns the argument.
53*39b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static Type elementType(Type type) {
54ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
55ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getElementType() : type;
56f99ccf65SEugene Zhulenev }
57f99ccf65SEugene Zhulenev 
58*39b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isF32(Type type) { return type.isF32(); }
59*39b2cd40SEugene Zhulenev 
60*39b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isI32(Type type) {
61*39b2cd40SEugene Zhulenev   return type.isInteger(32);
62*39b2cd40SEugene Zhulenev }
63*39b2cd40SEugene Zhulenev 
64f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
65ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values.
66f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
67f99ccf65SEugene Zhulenev 
68ce976d2dSEugene Zhulenev // Broadcasts scalar type into vector type (iff width is greater then 1).
69ce976d2dSEugene Zhulenev static Type broadcast(Type type, int width) {
70ce976d2dSEugene Zhulenev   assert(!type.isa<VectorType>() && "must be scalar type");
71ce976d2dSEugene Zhulenev   return width > 1 ? VectorType::get({width}, type) : type;
72ce976d2dSEugene Zhulenev }
73f99ccf65SEugene Zhulenev 
74ce976d2dSEugene Zhulenev // Broadcasts scalar value into vector (iff width is greater then 1).
75ce976d2dSEugene Zhulenev static Value broadcast(ImplicitLocOpBuilder &builder, Value value, int width) {
76ce976d2dSEugene Zhulenev   assert(!value.getType().isa<VectorType>() && "must be scalar value");
77ce976d2dSEugene Zhulenev   auto type = broadcast(value.getType(), width);
78ce976d2dSEugene Zhulenev   return width > 1 ? builder.create<BroadcastOp>(type, value) : value;
79ce976d2dSEugene Zhulenev }
80f99ccf65SEugene Zhulenev 
81ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
82ce976d2dSEugene Zhulenev // Helper functions to create constants.
83ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
84f99ccf65SEugene Zhulenev 
85ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
86ce976d2dSEugene Zhulenev   return builder.create<ConstantOp>(builder.getF32Type(),
87ce976d2dSEugene Zhulenev                                     builder.getF32FloatAttr(value));
88ce976d2dSEugene Zhulenev }
89f99ccf65SEugene Zhulenev 
90ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
91ce976d2dSEugene Zhulenev   return builder.create<ConstantOp>(builder.getI32Type(),
92ce976d2dSEugene Zhulenev                                     builder.getI32IntegerAttr(value));
93ce976d2dSEugene Zhulenev }
94f99ccf65SEugene Zhulenev 
95ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
96ce976d2dSEugene Zhulenev   Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
97ce976d2dSEugene Zhulenev   return builder.create<LLVM::BitcastOp>(builder.getF32Type(), i32Value);
98ce976d2dSEugene Zhulenev }
99f99ccf65SEugene Zhulenev 
100ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
101ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations.
102ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
103ce976d2dSEugene Zhulenev 
104ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) {
105ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
106ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OLT, a, b), a, b);
107ce976d2dSEugene Zhulenev }
108ce976d2dSEugene Zhulenev 
109ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) {
110ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
111ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OGT, a, b), a, b);
112ce976d2dSEugene Zhulenev }
113ce976d2dSEugene Zhulenev 
114ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
115ce976d2dSEugene Zhulenev                    Value upperBound) {
116ce976d2dSEugene Zhulenev   return max(builder, min(builder, value, upperBound), lowerBound);
117ce976d2dSEugene Zhulenev }
118ce976d2dSEugene Zhulenev 
119ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and
120ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type.
121ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
122ce976d2dSEugene Zhulenev                                      bool is_positive = false) {
123ce976d2dSEugene Zhulenev   assert(isF32(elementType(arg.getType())) && "argument must be f32 type");
124ce976d2dSEugene Zhulenev 
125ce976d2dSEugene Zhulenev   int width = vectorWidth(arg.getType());
126ce976d2dSEugene Zhulenev 
127ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
128ce976d2dSEugene Zhulenev     return broadcast(builder, value, width);
129f99ccf65SEugene Zhulenev   };
130f99ccf65SEugene Zhulenev 
131ce976d2dSEugene Zhulenev   auto i32 = builder.getIntegerType(32);
132ce976d2dSEugene Zhulenev   auto i32Vec = broadcast(i32, width);
133ce976d2dSEugene Zhulenev   auto f32Vec = broadcast(builder.getF32Type(), width);
134f99ccf65SEugene Zhulenev 
135ce976d2dSEugene Zhulenev   Value cst126f = f32Cst(builder, 126.0f);
136ce976d2dSEugene Zhulenev   Value cstHalf = f32Cst(builder, 0.5f);
137ce976d2dSEugene Zhulenev   Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
138f99ccf65SEugene Zhulenev 
139ce976d2dSEugene Zhulenev   // Bitcast to i32 for bitwise operations.
140ce976d2dSEugene Zhulenev   Value i32Half = builder.create<LLVM::BitcastOp>(i32, cstHalf);
141ce976d2dSEugene Zhulenev   Value i32InvMantMask = builder.create<LLVM::BitcastOp>(i32, cstInvMantMask);
142ce976d2dSEugene Zhulenev   Value i32Arg = builder.create<LLVM::BitcastOp>(i32Vec, arg);
143f99ccf65SEugene Zhulenev 
144ce976d2dSEugene Zhulenev   // Compute normalized fraction.
145ce976d2dSEugene Zhulenev   Value tmp0 = builder.create<LLVM::AndOp>(i32Arg, bcast(i32InvMantMask));
146ce976d2dSEugene Zhulenev   Value tmp1 = builder.create<LLVM::OrOp>(tmp0, bcast(i32Half));
147ce976d2dSEugene Zhulenev   Value normalizedFraction = builder.create<LLVM::BitcastOp>(f32Vec, tmp1);
148f99ccf65SEugene Zhulenev 
149ce976d2dSEugene Zhulenev   // Compute exponent.
150ce976d2dSEugene Zhulenev   Value arg0 = is_positive ? arg : builder.create<AbsFOp>(arg);
151ce976d2dSEugene Zhulenev   Value biasedExponentBits = builder.create<UnsignedShiftRightOp>(
152ce976d2dSEugene Zhulenev       builder.create<LLVM::BitcastOp>(i32Vec, arg0),
153ce976d2dSEugene Zhulenev       bcast(i32Cst(builder, 23)));
154ce976d2dSEugene Zhulenev   Value biasedExponent = builder.create<SIToFPOp>(f32Vec, biasedExponentBits);
155ce976d2dSEugene Zhulenev   Value exponent = builder.create<SubFOp>(biasedExponent, bcast(cst126f));
156f99ccf65SEugene Zhulenev 
157ce976d2dSEugene Zhulenev   return {normalizedFraction, exponent};
158f99ccf65SEugene Zhulenev }
159f99ccf65SEugene Zhulenev 
160ea7f211bSAhmed Taei // Computes exp2 for an i32 argument.
161ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
162ea7f211bSAhmed Taei   assert(isI32(elementType(arg.getType())) && "argument must be i32 type");
163ea7f211bSAhmed Taei 
164ea7f211bSAhmed Taei   int width = vectorWidth(arg.getType());
165ea7f211bSAhmed Taei 
166ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
167ea7f211bSAhmed Taei     return broadcast(builder, value, width);
168ea7f211bSAhmed Taei   };
169ea7f211bSAhmed Taei 
170ea7f211bSAhmed Taei   auto f32Vec = broadcast(builder.getF32Type(), width);
171ea7f211bSAhmed Taei   // The exponent of f32 located at 23-bit.
172ea7f211bSAhmed Taei   auto exponetBitLocation = bcast(i32Cst(builder, 23));
173ea7f211bSAhmed Taei   // Set the exponent bias to zero.
174ea7f211bSAhmed Taei   auto bias = bcast(i32Cst(builder, 127));
175ea7f211bSAhmed Taei 
176ea7f211bSAhmed Taei   Value biasedArg = builder.create<AddIOp>(arg, bias);
177ea7f211bSAhmed Taei   Value exp2ValueInt =
178ea7f211bSAhmed Taei       builder.create<ShiftLeftOp>(biasedArg, exponetBitLocation);
179ea7f211bSAhmed Taei   Value exp2ValueF32 = builder.create<LLVM::BitcastOp>(f32Vec, exp2ValueInt);
180ea7f211bSAhmed Taei 
181ea7f211bSAhmed Taei   return exp2ValueF32;
182ea7f211bSAhmed Taei }
183ea7f211bSAhmed Taei 
184f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
185f99ccf65SEugene Zhulenev // TanhOp approximation.
186f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
187f99ccf65SEugene Zhulenev 
188f99ccf65SEugene Zhulenev namespace {
189f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
190f99ccf65SEugene Zhulenev public:
191f99ccf65SEugene Zhulenev   using OpRewritePattern::OpRewritePattern;
192f99ccf65SEugene Zhulenev 
193f99ccf65SEugene Zhulenev   LogicalResult matchAndRewrite(math::TanhOp op,
194f99ccf65SEugene Zhulenev                                 PatternRewriter &rewriter) const final;
195f99ccf65SEugene Zhulenev };
196f99ccf65SEugene Zhulenev } // namespace
197f99ccf65SEugene Zhulenev 
198f99ccf65SEugene Zhulenev LogicalResult
199f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op,
200f99ccf65SEugene Zhulenev                                    PatternRewriter &rewriter) const {
201ce976d2dSEugene Zhulenev   auto width = vectorWidth(op.operand().getType(), isF32);
202ce976d2dSEugene Zhulenev   if (!width.hasValue())
203f99ccf65SEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
204f99ccf65SEugene Zhulenev 
205ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
206ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
207ce976d2dSEugene Zhulenev     return broadcast(builder, value, *width);
208ce976d2dSEugene Zhulenev   };
209f99ccf65SEugene Zhulenev 
210f99ccf65SEugene Zhulenev   // Clamp operand into [plusClamp, minusClamp] range.
211ce976d2dSEugene Zhulenev   Value minusClamp = bcast(f32Cst(builder, -7.9053111076354980f));
212ce976d2dSEugene Zhulenev   Value plusClamp = bcast(f32Cst(builder, 7.90531110763549805f));
213ce976d2dSEugene Zhulenev   Value x = clamp(builder, op.operand(), minusClamp, plusClamp);
214f99ccf65SEugene Zhulenev 
215f99ccf65SEugene Zhulenev   // Mask for tiny values that are approximated with `operand`.
216ce976d2dSEugene Zhulenev   Value tiny = bcast(f32Cst(builder, 0.0004f));
217ce976d2dSEugene Zhulenev   Value tinyMask = builder.create<CmpFOp>(
218ce976d2dSEugene Zhulenev       CmpFPredicate::OLT, builder.create<AbsFOp>(op.operand()), tiny);
219f99ccf65SEugene Zhulenev 
220f99ccf65SEugene Zhulenev   // The monomial coefficients of the numerator polynomial (odd).
221ce976d2dSEugene Zhulenev   Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
222ce976d2dSEugene Zhulenev   Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
223ce976d2dSEugene Zhulenev   Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
224ce976d2dSEugene Zhulenev   Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
225ce976d2dSEugene Zhulenev   Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
226ce976d2dSEugene Zhulenev   Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
227ce976d2dSEugene Zhulenev   Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
228f99ccf65SEugene Zhulenev 
229f99ccf65SEugene Zhulenev   // The monomial coefficients of the denominator polynomial (even).
230ce976d2dSEugene Zhulenev   Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
231ce976d2dSEugene Zhulenev   Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
232ce976d2dSEugene Zhulenev   Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
233ce976d2dSEugene Zhulenev   Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
234f99ccf65SEugene Zhulenev 
235f99ccf65SEugene Zhulenev   // Since the polynomials are odd/even, we need x^2.
236ce976d2dSEugene Zhulenev   Value x2 = builder.create<MulFOp>(x, x);
237f99ccf65SEugene Zhulenev 
238f99ccf65SEugene Zhulenev   // Evaluate the numerator polynomial p.
239ce976d2dSEugene Zhulenev   Value p = builder.create<FmaFOp>(x2, alpha13, alpha11);
240ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha9);
241ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha7);
242ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha5);
243ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha3);
244ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha1);
245ce976d2dSEugene Zhulenev   p = builder.create<MulFOp>(x, p);
246f99ccf65SEugene Zhulenev 
247f99ccf65SEugene Zhulenev   // Evaluate the denominator polynomial q.
248ce976d2dSEugene Zhulenev   Value q = builder.create<FmaFOp>(x2, beta6, beta4);
249ce976d2dSEugene Zhulenev   q = builder.create<FmaFOp>(x2, q, beta2);
250ce976d2dSEugene Zhulenev   q = builder.create<FmaFOp>(x2, q, beta0);
251f99ccf65SEugene Zhulenev 
252f99ccf65SEugene Zhulenev   // Divide the numerator by the denominator.
253ce976d2dSEugene Zhulenev   Value res =
254ce976d2dSEugene Zhulenev       builder.create<SelectOp>(tinyMask, x, builder.create<DivFOp>(p, q));
255f99ccf65SEugene Zhulenev 
256f99ccf65SEugene Zhulenev   rewriter.replaceOp(op, res);
257f99ccf65SEugene Zhulenev 
258f99ccf65SEugene Zhulenev   return success();
259f99ccf65SEugene Zhulenev }
260f99ccf65SEugene Zhulenev 
261ea7f211bSAhmed Taei #define LN2_VALUE                                                              \
262ea7f211bSAhmed Taei   0.693147180559945309417232121458176568075500134360255254120680009493393621L
263c0891706SEmilio Cota #define LOG2E_VALUE                                                            \
264ea7f211bSAhmed Taei   1.442695040888963407359924681001892137426645954152985934135449406931109219L
265ea7f211bSAhmed Taei 
266f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
267c0891706SEmilio Cota // LogOp and Log2Op approximation.
268ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
269ce976d2dSEugene Zhulenev 
270ce976d2dSEugene Zhulenev namespace {
271c0891706SEmilio Cota template <typename Op>
272c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> {
273c0891706SEmilio Cota   using OpRewritePattern<Op>::OpRewritePattern;
274ce976d2dSEugene Zhulenev 
275c0891706SEmilio Cota   /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise.
276c0891706SEmilio Cota   LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter,
277c0891706SEmilio Cota                                    bool base2) const;
278ce976d2dSEugene Zhulenev };
279ce976d2dSEugene Zhulenev } // namespace
280ce976d2dSEugene Zhulenev 
281c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library.
282c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath
283c0891706SEmilio Cota template <typename Op>
284ce976d2dSEugene Zhulenev LogicalResult
285c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter,
286c0891706SEmilio Cota                                              bool base2) const {
287ce976d2dSEugene Zhulenev   auto width = vectorWidth(op.operand().getType(), isF32);
288ce976d2dSEugene Zhulenev   if (!width.hasValue())
289ce976d2dSEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
290ce976d2dSEugene Zhulenev 
291ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
292ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
293ce976d2dSEugene Zhulenev     return broadcast(builder, value, *width);
294ce976d2dSEugene Zhulenev   };
295ce976d2dSEugene Zhulenev 
296ce976d2dSEugene Zhulenev   Value cstZero = bcast(f32Cst(builder, 0.0f));
297ce976d2dSEugene Zhulenev   Value cstOne = bcast(f32Cst(builder, 1.0f));
298ce976d2dSEugene Zhulenev   Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
299ce976d2dSEugene Zhulenev 
300ce976d2dSEugene Zhulenev   // The smallest non denormalized float number.
301ce976d2dSEugene Zhulenev   Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
302ce976d2dSEugene Zhulenev   Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
303ce976d2dSEugene Zhulenev   Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
304ce976d2dSEugene Zhulenev   Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
305ce976d2dSEugene Zhulenev 
306ce976d2dSEugene Zhulenev   // Polynomial coefficients.
307ce976d2dSEugene Zhulenev   Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
308ce976d2dSEugene Zhulenev   Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
309ce976d2dSEugene Zhulenev   Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
310ce976d2dSEugene Zhulenev   Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
311ce976d2dSEugene Zhulenev   Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
312ce976d2dSEugene Zhulenev   Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
313ce976d2dSEugene Zhulenev   Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
314ce976d2dSEugene Zhulenev   Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
315ce976d2dSEugene Zhulenev   Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
316ce976d2dSEugene Zhulenev   Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
317ce976d2dSEugene Zhulenev 
318ce976d2dSEugene Zhulenev   Value x = op.operand();
319ce976d2dSEugene Zhulenev 
320ce976d2dSEugene Zhulenev   // Truncate input values to the minimum positive normal.
321ce976d2dSEugene Zhulenev   x = max(builder, x, cstMinNormPos);
322ce976d2dSEugene Zhulenev 
323ce976d2dSEugene Zhulenev   // Extract significant in the range [0.5,1) and exponent.
324ce976d2dSEugene Zhulenev   std::pair<Value, Value> pair = frexp(builder, x, /*is_positive=*/true);
325ce976d2dSEugene Zhulenev   x = pair.first;
326ce976d2dSEugene Zhulenev   Value e = pair.second;
327ce976d2dSEugene Zhulenev 
328ce976d2dSEugene Zhulenev   // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
329ce976d2dSEugene Zhulenev   // by -1.0. The values are then centered around 0, which improves the
330ce976d2dSEugene Zhulenev   // stability of the polynomial evaluation:
331ce976d2dSEugene Zhulenev   //
332ce976d2dSEugene Zhulenev   //   if( x < SQRTHF ) {
333ce976d2dSEugene Zhulenev   //     e -= 1;
334ce976d2dSEugene Zhulenev   //     x = x + x - 1.0;
335ce976d2dSEugene Zhulenev   //   } else { x = x - 1.0; }
336ce976d2dSEugene Zhulenev   Value mask = builder.create<CmpFOp>(CmpFPredicate::OLT, x, cstCephesSQRTHF);
337ce976d2dSEugene Zhulenev   Value tmp = builder.create<SelectOp>(mask, x, cstZero);
338ce976d2dSEugene Zhulenev 
339ce976d2dSEugene Zhulenev   x = builder.create<SubFOp>(x, cstOne);
340ce976d2dSEugene Zhulenev   e = builder.create<SubFOp>(e,
341ce976d2dSEugene Zhulenev                              builder.create<SelectOp>(mask, cstOne, cstZero));
342ce976d2dSEugene Zhulenev   x = builder.create<AddFOp>(x, tmp);
343ce976d2dSEugene Zhulenev 
344ce976d2dSEugene Zhulenev   Value x2 = builder.create<MulFOp>(x, x);
345ce976d2dSEugene Zhulenev   Value x3 = builder.create<MulFOp>(x2, x);
346ce976d2dSEugene Zhulenev 
347ce976d2dSEugene Zhulenev   // Evaluate the polynomial approximant of degree 8 in three parts.
348ce976d2dSEugene Zhulenev   Value y0, y1, y2;
349ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(cstCephesLogP0, x, cstCephesLogP1);
350ce976d2dSEugene Zhulenev   y1 = builder.create<FmaFOp>(cstCephesLogP3, x, cstCephesLogP4);
351ce976d2dSEugene Zhulenev   y2 = builder.create<FmaFOp>(cstCephesLogP6, x, cstCephesLogP7);
352ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x, cstCephesLogP2);
353ce976d2dSEugene Zhulenev   y1 = builder.create<FmaFOp>(y1, x, cstCephesLogP5);
354ce976d2dSEugene Zhulenev   y2 = builder.create<FmaFOp>(y2, x, cstCephesLogP8);
355ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x3, y1);
356ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x3, y2);
357ce976d2dSEugene Zhulenev   y0 = builder.create<MulFOp>(y0, x3);
358ce976d2dSEugene Zhulenev 
359ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(cstNegHalf, x2, y0);
360ce976d2dSEugene Zhulenev   x = builder.create<AddFOp>(x, y0);
361ce976d2dSEugene Zhulenev 
362c0891706SEmilio Cota   if (base2) {
363c0891706SEmilio Cota     Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
364c0891706SEmilio Cota     x = builder.create<FmaFOp>(x, cstLog2e, e);
365c0891706SEmilio Cota   } else {
366ce976d2dSEugene Zhulenev     Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
367ce976d2dSEugene Zhulenev     x = builder.create<FmaFOp>(e, cstLn2, x);
368c0891706SEmilio Cota   }
369ce976d2dSEugene Zhulenev 
370ce976d2dSEugene Zhulenev   Value invalidMask =
371ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::ULT, op.operand(), cstZero);
372ce976d2dSEugene Zhulenev   Value zeroMask =
373ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstZero);
374ce976d2dSEugene Zhulenev   Value posInfMask =
375ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstPosInf);
376ce976d2dSEugene Zhulenev 
377ce976d2dSEugene Zhulenev   // Filter out invalid values:
378ce976d2dSEugene Zhulenev   //  • x == 0     -> -INF
379ce976d2dSEugene Zhulenev   //  • x < 0      ->  NAN
380ce976d2dSEugene Zhulenev   //  • x == +INF  -> +INF
381ce976d2dSEugene Zhulenev   Value aproximation = builder.create<SelectOp>(
382ce976d2dSEugene Zhulenev       zeroMask, cstMinusInf,
383ce976d2dSEugene Zhulenev       builder.create<SelectOp>(
384ce976d2dSEugene Zhulenev           invalidMask, cstNan,
385ce976d2dSEugene Zhulenev           builder.create<SelectOp>(posInfMask, cstPosInf, x)));
386ce976d2dSEugene Zhulenev 
387ce976d2dSEugene Zhulenev   rewriter.replaceOp(op, aproximation);
388ce976d2dSEugene Zhulenev 
389ce976d2dSEugene Zhulenev   return success();
390ce976d2dSEugene Zhulenev }
391ce976d2dSEugene Zhulenev 
392c0891706SEmilio Cota namespace {
393c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> {
394c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
395c0891706SEmilio Cota 
396c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::LogOp op,
397c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
398c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/false);
399c0891706SEmilio Cota   }
400c0891706SEmilio Cota };
401c0891706SEmilio Cota } // namespace
402c0891706SEmilio Cota 
403c0891706SEmilio Cota namespace {
404c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
405c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
406c0891706SEmilio Cota 
407c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::Log2Op op,
408c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
409c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/true);
410c0891706SEmilio Cota   }
411c0891706SEmilio Cota };
412c0891706SEmilio Cota } // namespace
413c0891706SEmilio Cota 
414ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
415ea7f211bSAhmed Taei // Exp approximation.
416ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
417ea7f211bSAhmed Taei 
418ea7f211bSAhmed Taei namespace {
419ea7f211bSAhmed Taei 
420ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
421ea7f211bSAhmed Taei public:
422ea7f211bSAhmed Taei   using OpRewritePattern::OpRewritePattern;
423ea7f211bSAhmed Taei 
424ea7f211bSAhmed Taei   LogicalResult matchAndRewrite(math::ExpOp op,
425ea7f211bSAhmed Taei                                 PatternRewriter &rewriter) const final;
426ea7f211bSAhmed Taei };
427ea7f211bSAhmed Taei } // namespace
428ea7f211bSAhmed Taei 
429ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range
430ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
431ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y).
432ea7f211bSAhmed Taei LogicalResult
433ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op,
434ea7f211bSAhmed Taei                                   PatternRewriter &rewriter) const {
435ea7f211bSAhmed Taei   auto width = vectorWidth(op.operand().getType(), isF32);
436ea7f211bSAhmed Taei   if (!width.hasValue())
437ea7f211bSAhmed Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
438ea7f211bSAhmed Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
439ea7f211bSAhmed Taei 
440ea7f211bSAhmed Taei   // TODO: Consider a common pattern rewriter with all methods below to
441ea7f211bSAhmed Taei   // write the approximations.
442ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
443ea7f211bSAhmed Taei     return broadcast(builder, value, *width);
444ea7f211bSAhmed Taei   };
445ea7f211bSAhmed Taei   auto fmla = [&](Value a, Value b, Value c) {
446ea7f211bSAhmed Taei     return builder.create<FmaFOp>(a, b, c);
447ea7f211bSAhmed Taei   };
448ea7f211bSAhmed Taei   auto mul = [&](Value a, Value b) -> Value {
449ea7f211bSAhmed Taei     return builder.create<MulFOp>(a, b);
450ea7f211bSAhmed Taei   };
451ea7f211bSAhmed Taei   auto sub = [&](Value a, Value b) -> Value {
452ea7f211bSAhmed Taei     return builder.create<SubFOp>(a, b);
453ea7f211bSAhmed Taei   };
454ea7f211bSAhmed Taei   auto floor = [&](Value a) { return builder.create<FloorFOp>(a); };
455ea7f211bSAhmed Taei 
456ea7f211bSAhmed Taei   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
457c0891706SEmilio Cota   Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
458ea7f211bSAhmed Taei 
459ea7f211bSAhmed Taei   // Polynomial coefficients.
460ea7f211bSAhmed Taei   Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
461ea7f211bSAhmed Taei   Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
462ea7f211bSAhmed Taei   Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
463ea7f211bSAhmed Taei   Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
464ea7f211bSAhmed Taei   Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
465ea7f211bSAhmed Taei   Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
466ea7f211bSAhmed Taei 
467ea7f211bSAhmed Taei   Value x = op.operand();
468ea7f211bSAhmed Taei 
469ea7f211bSAhmed Taei   // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
470c0891706SEmilio Cota   Value xL2Inv = mul(x, cstLog2E);
471ea7f211bSAhmed Taei   Value kF32 = floor(xL2Inv);
472ea7f211bSAhmed Taei   Value kLn2 = mul(kF32, cstLn2);
473ea7f211bSAhmed Taei   Value y = sub(x, kLn2);
474ea7f211bSAhmed Taei 
475ea7f211bSAhmed Taei   // Use Estrin's evaluation scheme with 3 independent parts:
476ea7f211bSAhmed Taei   // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
477ea7f211bSAhmed Taei   Value y2 = mul(y, y);
478ea7f211bSAhmed Taei   Value y4 = mul(y2, y2);
479ea7f211bSAhmed Taei 
480ea7f211bSAhmed Taei   Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
481ea7f211bSAhmed Taei   Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
482ea7f211bSAhmed Taei   Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
483ea7f211bSAhmed Taei   Value expY = fmla(q1, y2, q0);
484ea7f211bSAhmed Taei   expY = fmla(q2, y4, expY);
485ea7f211bSAhmed Taei 
486ea7f211bSAhmed Taei   auto i32Vec = broadcast(builder.getI32Type(), *width);
487ea7f211bSAhmed Taei 
488ea7f211bSAhmed Taei   // exp2(k)
489ea7f211bSAhmed Taei   Value k = builder.create<FPToSIOp>(kF32, i32Vec);
490ea7f211bSAhmed Taei   Value exp2KValue = exp2I32(builder, k);
491ea7f211bSAhmed Taei 
492ea7f211bSAhmed Taei   // exp(x) = exp(y) * exp2(k)
493ea7f211bSAhmed Taei   expY = mul(expY, exp2KValue);
494ea7f211bSAhmed Taei 
495ea7f211bSAhmed Taei   // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
496ea7f211bSAhmed Taei   // partitioned as the following:
497ea7f211bSAhmed Taei   // exp(x) = 0, x <= -inf
498ea7f211bSAhmed Taei   // exp(x) = underflow (min_float), x <= -88
499ea7f211bSAhmed Taei   // exp(x) = inf (min_float), x >= 88
500ea7f211bSAhmed Taei   // Note: |k| = 127 is the value where the 8-bits exponent saturates.
501ea7f211bSAhmed Taei   Value zerof32Const = bcast(f32Cst(builder, 0));
502ea7f211bSAhmed Taei   auto constPosInfinity =
503ea7f211bSAhmed Taei       bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
504ea7f211bSAhmed Taei   auto constNegIfinity =
505ea7f211bSAhmed Taei       bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
506ea7f211bSAhmed Taei   auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
507ea7f211bSAhmed Taei 
508ea7f211bSAhmed Taei   Value kMaxConst = bcast(i32Cst(builder, 127));
509ea7f211bSAhmed Taei   Value kMaxNegConst = bcast(i32Cst(builder, -127));
510ea7f211bSAhmed Taei   Value rightBound = builder.create<CmpIOp>(CmpIPredicate::sle, k, kMaxConst);
511ea7f211bSAhmed Taei   Value leftBound = builder.create<CmpIOp>(CmpIPredicate::sge, k, kMaxNegConst);
512ea7f211bSAhmed Taei 
513ea7f211bSAhmed Taei   Value isNegInfinityX =
514ea7f211bSAhmed Taei       builder.create<CmpFOp>(CmpFPredicate::OEQ, x, constNegIfinity);
515ea7f211bSAhmed Taei   Value isPostiveX =
516ea7f211bSAhmed Taei       builder.create<CmpFOp>(CmpFPredicate::OGT, x, zerof32Const);
517ea7f211bSAhmed Taei   Value isComputable = builder.create<AndOp>(rightBound, leftBound);
518ea7f211bSAhmed Taei 
519ea7f211bSAhmed Taei   expY = builder.create<SelectOp>(
520ea7f211bSAhmed Taei       isComputable, expY,
521ea7f211bSAhmed Taei       builder.create<SelectOp>(
522ea7f211bSAhmed Taei           isPostiveX, constPosInfinity,
523ea7f211bSAhmed Taei           builder.create<SelectOp>(isNegInfinityX, zerof32Const, underflow)));
524ea7f211bSAhmed Taei 
525ea7f211bSAhmed Taei   rewriter.replaceOp(op, expY);
526ea7f211bSAhmed Taei 
527ea7f211bSAhmed Taei   return success();
528ea7f211bSAhmed Taei }
529ea7f211bSAhmed Taei 
530ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
531f99ccf65SEugene Zhulenev 
532f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns(
533f99ccf65SEugene Zhulenev     OwningRewritePatternList &patterns, MLIRContext *ctx) {
534c0891706SEmilio Cota   patterns.insert<TanhApproximation, LogApproximation, Log2Approximation,
535c0891706SEmilio Cota                   ExpApproximation>(ctx);
536f99ccf65SEugene Zhulenev }
537