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 //===----------------------------------------------------------------------===//
133a506b31SChris Lattner 
14*a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.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"
203a506b31SChris Lattner #include "mlir/Transforms/Bufferize.h"
21f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h"
22f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
233a506b31SChris Lattner #include <climits>
24f99ccf65SEugene Zhulenev 
25f99ccf65SEugene Zhulenev using namespace mlir;
26f99ccf65SEugene Zhulenev using namespace mlir::vector;
27f99ccf65SEugene Zhulenev 
28ce976d2dSEugene Zhulenev using TypePredicate = llvm::function_ref<bool(Type)>;
29ce976d2dSEugene Zhulenev 
30ce976d2dSEugene Zhulenev // Returns vector width if the element type is matching the predicate (scalars
31ce976d2dSEugene Zhulenev // that do match the predicate have width equal to `1`).
32ce976d2dSEugene Zhulenev static Optional<int> vectorWidth(Type type, TypePredicate pred) {
33ce976d2dSEugene Zhulenev   // If the type matches the predicate then its width is `1`.
34ce976d2dSEugene Zhulenev   if (pred(type))
35ce976d2dSEugene Zhulenev     return 1;
36ce976d2dSEugene Zhulenev 
37ce976d2dSEugene Zhulenev   // Otherwise check if the type is a vector type.
38ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
39ce976d2dSEugene Zhulenev   if (vectorType && pred(vectorType.getElementType())) {
40ce976d2dSEugene Zhulenev     assert(vectorType.getRank() == 1 && "only 1d vectors are supported");
41ce976d2dSEugene Zhulenev     return vectorType.getDimSize(0);
42ce976d2dSEugene Zhulenev   }
43ce976d2dSEugene Zhulenev 
44ce976d2dSEugene Zhulenev   return llvm::None;
45ce976d2dSEugene Zhulenev }
46ce976d2dSEugene Zhulenev 
47ce976d2dSEugene Zhulenev // Returns vector width of the type. If the type is a scalar returns `1`.
48ce976d2dSEugene Zhulenev static int vectorWidth(Type type) {
49ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
50ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getDimSize(0) : 1;
51ce976d2dSEugene Zhulenev }
52ce976d2dSEugene Zhulenev 
53ce976d2dSEugene Zhulenev // Returns vector element type. If the type is a scalar returns the argument.
5439b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static Type elementType(Type type) {
55ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
56ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getElementType() : type;
57f99ccf65SEugene Zhulenev }
58f99ccf65SEugene Zhulenev 
5939b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isF32(Type type) { return type.isF32(); }
6039b2cd40SEugene Zhulenev 
6139b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isI32(Type type) {
6239b2cd40SEugene Zhulenev   return type.isInteger(32);
6339b2cd40SEugene Zhulenev }
6439b2cd40SEugene Zhulenev 
65f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
66ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values.
67f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
68f99ccf65SEugene Zhulenev 
69ce976d2dSEugene Zhulenev // Broadcasts scalar type into vector type (iff width is greater then 1).
70ce976d2dSEugene Zhulenev static Type broadcast(Type type, int width) {
71ce976d2dSEugene Zhulenev   assert(!type.isa<VectorType>() && "must be scalar type");
72ce976d2dSEugene Zhulenev   return width > 1 ? VectorType::get({width}, type) : type;
73ce976d2dSEugene Zhulenev }
74f99ccf65SEugene Zhulenev 
75ce976d2dSEugene Zhulenev // Broadcasts scalar value into vector (iff width is greater then 1).
76ce976d2dSEugene Zhulenev static Value broadcast(ImplicitLocOpBuilder &builder, Value value, int width) {
77ce976d2dSEugene Zhulenev   assert(!value.getType().isa<VectorType>() && "must be scalar value");
78ce976d2dSEugene Zhulenev   auto type = broadcast(value.getType(), width);
79ce976d2dSEugene Zhulenev   return width > 1 ? builder.create<BroadcastOp>(type, value) : value;
80ce976d2dSEugene Zhulenev }
81f99ccf65SEugene Zhulenev 
82ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
83ce976d2dSEugene Zhulenev // Helper functions to create constants.
84ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
85f99ccf65SEugene Zhulenev 
86ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
87*a54f4eaeSMogball   return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value));
88ce976d2dSEugene Zhulenev }
89f99ccf65SEugene Zhulenev 
90ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
91*a54f4eaeSMogball   return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value));
92ce976d2dSEugene Zhulenev }
93f99ccf65SEugene Zhulenev 
94ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
95ce976d2dSEugene Zhulenev   Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
96*a54f4eaeSMogball   return builder.create<arith::BitcastOp>(builder.getF32Type(), i32Value);
97ce976d2dSEugene Zhulenev }
98f99ccf65SEugene Zhulenev 
99ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
100ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations.
101ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
102ce976d2dSEugene Zhulenev 
103ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) {
104ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
105*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, a, b), a, b);
106ce976d2dSEugene Zhulenev }
107ce976d2dSEugene Zhulenev 
108ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) {
109ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
110*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, a, b), a, b);
111ce976d2dSEugene Zhulenev }
112ce976d2dSEugene Zhulenev 
113ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
114ce976d2dSEugene Zhulenev                    Value upperBound) {
115ce976d2dSEugene Zhulenev   return max(builder, min(builder, value, upperBound), lowerBound);
116ce976d2dSEugene Zhulenev }
117ce976d2dSEugene Zhulenev 
118ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and
119ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type.
120ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
121ce976d2dSEugene Zhulenev                                      bool is_positive = false) {
122ce976d2dSEugene Zhulenev   assert(isF32(elementType(arg.getType())) && "argument must be f32 type");
123ce976d2dSEugene Zhulenev 
124ce976d2dSEugene Zhulenev   int width = vectorWidth(arg.getType());
125ce976d2dSEugene Zhulenev 
126ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
127ce976d2dSEugene Zhulenev     return broadcast(builder, value, width);
128f99ccf65SEugene Zhulenev   };
129f99ccf65SEugene Zhulenev 
130ce976d2dSEugene Zhulenev   auto i32 = builder.getIntegerType(32);
131ce976d2dSEugene Zhulenev   auto i32Vec = broadcast(i32, width);
132ce976d2dSEugene Zhulenev   auto f32Vec = broadcast(builder.getF32Type(), width);
133f99ccf65SEugene Zhulenev 
134ce976d2dSEugene Zhulenev   Value cst126f = f32Cst(builder, 126.0f);
135ce976d2dSEugene Zhulenev   Value cstHalf = f32Cst(builder, 0.5f);
136ce976d2dSEugene Zhulenev   Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
137f99ccf65SEugene Zhulenev 
138ce976d2dSEugene Zhulenev   // Bitcast to i32 for bitwise operations.
139*a54f4eaeSMogball   Value i32Half = builder.create<arith::BitcastOp>(i32, cstHalf);
140*a54f4eaeSMogball   Value i32InvMantMask = builder.create<arith::BitcastOp>(i32, cstInvMantMask);
141*a54f4eaeSMogball   Value i32Arg = builder.create<arith::BitcastOp>(i32Vec, arg);
142f99ccf65SEugene Zhulenev 
143ce976d2dSEugene Zhulenev   // Compute normalized fraction.
144*a54f4eaeSMogball   Value tmp0 = builder.create<arith::AndIOp>(i32Arg, bcast(i32InvMantMask));
145*a54f4eaeSMogball   Value tmp1 = builder.create<arith::OrIOp>(tmp0, bcast(i32Half));
146*a54f4eaeSMogball   Value normalizedFraction = builder.create<arith::BitcastOp>(f32Vec, tmp1);
147f99ccf65SEugene Zhulenev 
148ce976d2dSEugene Zhulenev   // Compute exponent.
149*a54f4eaeSMogball   Value arg0 = is_positive ? arg : builder.create<math::AbsOp>(arg);
150*a54f4eaeSMogball   Value biasedExponentBits = builder.create<arith::ShRUIOp>(
151*a54f4eaeSMogball       builder.create<arith::BitcastOp>(i32Vec, arg0),
152*a54f4eaeSMogball       bcast(i32Cst(builder, 23)));
153*a54f4eaeSMogball   Value biasedExponent =
154*a54f4eaeSMogball       builder.create<arith::SIToFPOp>(f32Vec, biasedExponentBits);
155*a54f4eaeSMogball   Value exponent =
156*a54f4eaeSMogball       builder.create<arith::SubFOp>(biasedExponent, bcast(cst126f));
157f99ccf65SEugene Zhulenev 
158ce976d2dSEugene Zhulenev   return {normalizedFraction, exponent};
159f99ccf65SEugene Zhulenev }
160f99ccf65SEugene Zhulenev 
161ea7f211bSAhmed Taei // Computes exp2 for an i32 argument.
162ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
163ea7f211bSAhmed Taei   assert(isI32(elementType(arg.getType())) && "argument must be i32 type");
164ea7f211bSAhmed Taei 
165ea7f211bSAhmed Taei   int width = vectorWidth(arg.getType());
166ea7f211bSAhmed Taei 
167ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
168ea7f211bSAhmed Taei     return broadcast(builder, value, width);
169ea7f211bSAhmed Taei   };
170ea7f211bSAhmed Taei 
171ea7f211bSAhmed Taei   auto f32Vec = broadcast(builder.getF32Type(), width);
172ea7f211bSAhmed Taei   // The exponent of f32 located at 23-bit.
173ea7f211bSAhmed Taei   auto exponetBitLocation = bcast(i32Cst(builder, 23));
174ea7f211bSAhmed Taei   // Set the exponent bias to zero.
175ea7f211bSAhmed Taei   auto bias = bcast(i32Cst(builder, 127));
176ea7f211bSAhmed Taei 
177*a54f4eaeSMogball   Value biasedArg = builder.create<arith::AddIOp>(arg, bias);
178ea7f211bSAhmed Taei   Value exp2ValueInt =
179*a54f4eaeSMogball       builder.create<arith::ShLIOp>(biasedArg, exponetBitLocation);
180*a54f4eaeSMogball   Value exp2ValueF32 = builder.create<arith::BitcastOp>(f32Vec, exp2ValueInt);
181ea7f211bSAhmed Taei 
182ea7f211bSAhmed Taei   return exp2ValueF32;
183ea7f211bSAhmed Taei }
184ea7f211bSAhmed Taei 
185f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
186f99ccf65SEugene Zhulenev // TanhOp approximation.
187f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
188f99ccf65SEugene Zhulenev 
189f99ccf65SEugene Zhulenev namespace {
190f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
191f99ccf65SEugene Zhulenev public:
192f99ccf65SEugene Zhulenev   using OpRewritePattern::OpRewritePattern;
193f99ccf65SEugene Zhulenev 
194f99ccf65SEugene Zhulenev   LogicalResult matchAndRewrite(math::TanhOp op,
195f99ccf65SEugene Zhulenev                                 PatternRewriter &rewriter) const final;
196f99ccf65SEugene Zhulenev };
197f99ccf65SEugene Zhulenev } // namespace
198f99ccf65SEugene Zhulenev 
199f99ccf65SEugene Zhulenev LogicalResult
200f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op,
201f99ccf65SEugene Zhulenev                                    PatternRewriter &rewriter) const {
202ce976d2dSEugene Zhulenev   auto width = vectorWidth(op.operand().getType(), isF32);
203ce976d2dSEugene Zhulenev   if (!width.hasValue())
204f99ccf65SEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
205f99ccf65SEugene Zhulenev 
206ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
207ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
208ce976d2dSEugene Zhulenev     return broadcast(builder, value, *width);
209ce976d2dSEugene Zhulenev   };
210f99ccf65SEugene Zhulenev 
211f99ccf65SEugene Zhulenev   // Clamp operand into [plusClamp, minusClamp] range.
212ce976d2dSEugene Zhulenev   Value minusClamp = bcast(f32Cst(builder, -7.9053111076354980f));
213ce976d2dSEugene Zhulenev   Value plusClamp = bcast(f32Cst(builder, 7.90531110763549805f));
214ce976d2dSEugene Zhulenev   Value x = clamp(builder, op.operand(), minusClamp, plusClamp);
215f99ccf65SEugene Zhulenev 
216f99ccf65SEugene Zhulenev   // Mask for tiny values that are approximated with `operand`.
217ce976d2dSEugene Zhulenev   Value tiny = bcast(f32Cst(builder, 0.0004f));
218*a54f4eaeSMogball   Value tinyMask = builder.create<arith::CmpFOp>(
219*a54f4eaeSMogball       arith::CmpFPredicate::OLT, builder.create<math::AbsOp>(op.operand()),
220*a54f4eaeSMogball       tiny);
221f99ccf65SEugene Zhulenev 
222f99ccf65SEugene Zhulenev   // The monomial coefficients of the numerator polynomial (odd).
223ce976d2dSEugene Zhulenev   Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
224ce976d2dSEugene Zhulenev   Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
225ce976d2dSEugene Zhulenev   Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
226ce976d2dSEugene Zhulenev   Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
227ce976d2dSEugene Zhulenev   Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
228ce976d2dSEugene Zhulenev   Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
229ce976d2dSEugene Zhulenev   Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
230f99ccf65SEugene Zhulenev 
231f99ccf65SEugene Zhulenev   // The monomial coefficients of the denominator polynomial (even).
232ce976d2dSEugene Zhulenev   Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
233ce976d2dSEugene Zhulenev   Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
234ce976d2dSEugene Zhulenev   Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
235ce976d2dSEugene Zhulenev   Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
236f99ccf65SEugene Zhulenev 
237f99ccf65SEugene Zhulenev   // Since the polynomials are odd/even, we need x^2.
238*a54f4eaeSMogball   Value x2 = builder.create<arith::MulFOp>(x, x);
239f99ccf65SEugene Zhulenev 
240f99ccf65SEugene Zhulenev   // Evaluate the numerator polynomial p.
241*a54f4eaeSMogball   Value p = builder.create<math::FmaOp>(x2, alpha13, alpha11);
242*a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha9);
243*a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha7);
244*a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha5);
245*a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha3);
246*a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha1);
247*a54f4eaeSMogball   p = builder.create<arith::MulFOp>(x, p);
248f99ccf65SEugene Zhulenev 
249f99ccf65SEugene Zhulenev   // Evaluate the denominator polynomial q.
250*a54f4eaeSMogball   Value q = builder.create<math::FmaOp>(x2, beta6, beta4);
251*a54f4eaeSMogball   q = builder.create<math::FmaOp>(x2, q, beta2);
252*a54f4eaeSMogball   q = builder.create<math::FmaOp>(x2, q, beta0);
253f99ccf65SEugene Zhulenev 
254f99ccf65SEugene Zhulenev   // Divide the numerator by the denominator.
255*a54f4eaeSMogball   Value res = builder.create<SelectOp>(tinyMask, x,
256*a54f4eaeSMogball                                        builder.create<arith::DivFOp>(p, q));
257f99ccf65SEugene Zhulenev 
258f99ccf65SEugene Zhulenev   rewriter.replaceOp(op, res);
259f99ccf65SEugene Zhulenev 
260f99ccf65SEugene Zhulenev   return success();
261f99ccf65SEugene Zhulenev }
262f99ccf65SEugene Zhulenev 
263ea7f211bSAhmed Taei #define LN2_VALUE                                                              \
264ea7f211bSAhmed Taei   0.693147180559945309417232121458176568075500134360255254120680009493393621L
265c0891706SEmilio Cota #define LOG2E_VALUE                                                            \
266ea7f211bSAhmed Taei   1.442695040888963407359924681001892137426645954152985934135449406931109219L
267ea7f211bSAhmed Taei 
268f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
269c0891706SEmilio Cota // LogOp and Log2Op approximation.
270ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
271ce976d2dSEugene Zhulenev 
272ce976d2dSEugene Zhulenev namespace {
273c0891706SEmilio Cota template <typename Op>
274c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> {
275c0891706SEmilio Cota   using OpRewritePattern<Op>::OpRewritePattern;
276ce976d2dSEugene Zhulenev 
277c0891706SEmilio Cota   /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise.
278c0891706SEmilio Cota   LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter,
279c0891706SEmilio Cota                                    bool base2) const;
280ce976d2dSEugene Zhulenev };
281ce976d2dSEugene Zhulenev } // namespace
282ce976d2dSEugene Zhulenev 
283c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library.
284c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath
285c0891706SEmilio Cota template <typename Op>
286ce976d2dSEugene Zhulenev LogicalResult
287c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter,
288c0891706SEmilio Cota                                              bool base2) const {
289ce976d2dSEugene Zhulenev   auto width = vectorWidth(op.operand().getType(), isF32);
290ce976d2dSEugene Zhulenev   if (!width.hasValue())
291ce976d2dSEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
292ce976d2dSEugene Zhulenev 
293ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
294ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
295ce976d2dSEugene Zhulenev     return broadcast(builder, value, *width);
296ce976d2dSEugene Zhulenev   };
297ce976d2dSEugene Zhulenev 
298ce976d2dSEugene Zhulenev   Value cstZero = bcast(f32Cst(builder, 0.0f));
299ce976d2dSEugene Zhulenev   Value cstOne = bcast(f32Cst(builder, 1.0f));
300ce976d2dSEugene Zhulenev   Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
301ce976d2dSEugene Zhulenev 
302ce976d2dSEugene Zhulenev   // The smallest non denormalized float number.
303ce976d2dSEugene Zhulenev   Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
304ce976d2dSEugene Zhulenev   Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
305ce976d2dSEugene Zhulenev   Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
306ce976d2dSEugene Zhulenev   Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
307ce976d2dSEugene Zhulenev 
308ce976d2dSEugene Zhulenev   // Polynomial coefficients.
309ce976d2dSEugene Zhulenev   Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
310ce976d2dSEugene Zhulenev   Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
311ce976d2dSEugene Zhulenev   Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
312ce976d2dSEugene Zhulenev   Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
313ce976d2dSEugene Zhulenev   Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
314ce976d2dSEugene Zhulenev   Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
315ce976d2dSEugene Zhulenev   Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
316ce976d2dSEugene Zhulenev   Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
317ce976d2dSEugene Zhulenev   Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
318ce976d2dSEugene Zhulenev   Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
319ce976d2dSEugene Zhulenev 
320ce976d2dSEugene Zhulenev   Value x = op.operand();
321ce976d2dSEugene Zhulenev 
322ce976d2dSEugene Zhulenev   // Truncate input values to the minimum positive normal.
323ce976d2dSEugene Zhulenev   x = max(builder, x, cstMinNormPos);
324ce976d2dSEugene Zhulenev 
325ce976d2dSEugene Zhulenev   // Extract significant in the range [0.5,1) and exponent.
326ce976d2dSEugene Zhulenev   std::pair<Value, Value> pair = frexp(builder, x, /*is_positive=*/true);
327ce976d2dSEugene Zhulenev   x = pair.first;
328ce976d2dSEugene Zhulenev   Value e = pair.second;
329ce976d2dSEugene Zhulenev 
330ce976d2dSEugene Zhulenev   // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
331ce976d2dSEugene Zhulenev   // by -1.0. The values are then centered around 0, which improves the
332ce976d2dSEugene Zhulenev   // stability of the polynomial evaluation:
333ce976d2dSEugene Zhulenev   //
334ce976d2dSEugene Zhulenev   //   if( x < SQRTHF ) {
335ce976d2dSEugene Zhulenev   //     e -= 1;
336ce976d2dSEugene Zhulenev   //     x = x + x - 1.0;
337ce976d2dSEugene Zhulenev   //   } else { x = x - 1.0; }
338*a54f4eaeSMogball   Value mask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x,
339*a54f4eaeSMogball                                              cstCephesSQRTHF);
340ce976d2dSEugene Zhulenev   Value tmp = builder.create<SelectOp>(mask, x, cstZero);
341ce976d2dSEugene Zhulenev 
342*a54f4eaeSMogball   x = builder.create<arith::SubFOp>(x, cstOne);
343*a54f4eaeSMogball   e = builder.create<arith::SubFOp>(
344*a54f4eaeSMogball       e, builder.create<SelectOp>(mask, cstOne, cstZero));
345*a54f4eaeSMogball   x = builder.create<arith::AddFOp>(x, tmp);
346ce976d2dSEugene Zhulenev 
347*a54f4eaeSMogball   Value x2 = builder.create<arith::MulFOp>(x, x);
348*a54f4eaeSMogball   Value x3 = builder.create<arith::MulFOp>(x2, x);
349ce976d2dSEugene Zhulenev 
350ce976d2dSEugene Zhulenev   // Evaluate the polynomial approximant of degree 8 in three parts.
351ce976d2dSEugene Zhulenev   Value y0, y1, y2;
352*a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(cstCephesLogP0, x, cstCephesLogP1);
353*a54f4eaeSMogball   y1 = builder.create<math::FmaOp>(cstCephesLogP3, x, cstCephesLogP4);
354*a54f4eaeSMogball   y2 = builder.create<math::FmaOp>(cstCephesLogP6, x, cstCephesLogP7);
355*a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x, cstCephesLogP2);
356*a54f4eaeSMogball   y1 = builder.create<math::FmaOp>(y1, x, cstCephesLogP5);
357*a54f4eaeSMogball   y2 = builder.create<math::FmaOp>(y2, x, cstCephesLogP8);
358*a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x3, y1);
359*a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x3, y2);
360*a54f4eaeSMogball   y0 = builder.create<arith::MulFOp>(y0, x3);
361ce976d2dSEugene Zhulenev 
362*a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(cstNegHalf, x2, y0);
363*a54f4eaeSMogball   x = builder.create<arith::AddFOp>(x, y0);
364ce976d2dSEugene Zhulenev 
365c0891706SEmilio Cota   if (base2) {
366c0891706SEmilio Cota     Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
367*a54f4eaeSMogball     x = builder.create<math::FmaOp>(x, cstLog2e, e);
368c0891706SEmilio Cota   } else {
369ce976d2dSEugene Zhulenev     Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
370*a54f4eaeSMogball     x = builder.create<math::FmaOp>(e, cstLn2, x);
371c0891706SEmilio Cota   }
372ce976d2dSEugene Zhulenev 
373*a54f4eaeSMogball   Value invalidMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT,
374*a54f4eaeSMogball                                                     op.operand(), cstZero);
375*a54f4eaeSMogball   Value zeroMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
376*a54f4eaeSMogball                                                  op.operand(), cstZero);
377*a54f4eaeSMogball   Value posInfMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
378*a54f4eaeSMogball                                                    op.operand(), cstPosInf);
379ce976d2dSEugene Zhulenev 
380ce976d2dSEugene Zhulenev   // Filter out invalid values:
381ce976d2dSEugene Zhulenev   //  • x == 0     -> -INF
382ce976d2dSEugene Zhulenev   //  • x < 0      ->  NAN
383ce976d2dSEugene Zhulenev   //  • x == +INF  -> +INF
384ce976d2dSEugene Zhulenev   Value aproximation = builder.create<SelectOp>(
385ce976d2dSEugene Zhulenev       zeroMask, cstMinusInf,
386ce976d2dSEugene Zhulenev       builder.create<SelectOp>(
387ce976d2dSEugene Zhulenev           invalidMask, cstNan,
388ce976d2dSEugene Zhulenev           builder.create<SelectOp>(posInfMask, cstPosInf, x)));
389ce976d2dSEugene Zhulenev 
390ce976d2dSEugene Zhulenev   rewriter.replaceOp(op, aproximation);
391ce976d2dSEugene Zhulenev 
392ce976d2dSEugene Zhulenev   return success();
393ce976d2dSEugene Zhulenev }
394ce976d2dSEugene Zhulenev 
395c0891706SEmilio Cota namespace {
396c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> {
397c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
398c0891706SEmilio Cota 
399c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::LogOp op,
400c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
401c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/false);
402c0891706SEmilio Cota   }
403c0891706SEmilio Cota };
404c0891706SEmilio Cota } // namespace
405c0891706SEmilio Cota 
406c0891706SEmilio Cota namespace {
407c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
408c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
409c0891706SEmilio Cota 
410c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::Log2Op op,
411c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
412c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/true);
413c0891706SEmilio Cota   }
414c0891706SEmilio Cota };
415c0891706SEmilio Cota } // namespace
416c0891706SEmilio Cota 
417ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
4181c0374e7SEmilio Cota // Log1p approximation.
4191c0374e7SEmilio Cota //----------------------------------------------------------------------------//
4201c0374e7SEmilio Cota 
4211c0374e7SEmilio Cota namespace {
4221c0374e7SEmilio Cota struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> {
4231c0374e7SEmilio Cota public:
4241c0374e7SEmilio Cota   using OpRewritePattern::OpRewritePattern;
4251c0374e7SEmilio Cota 
4261c0374e7SEmilio Cota   LogicalResult matchAndRewrite(math::Log1pOp op,
4271c0374e7SEmilio Cota                                 PatternRewriter &rewriter) const final;
4281c0374e7SEmilio Cota };
4291c0374e7SEmilio Cota } // namespace
4301c0374e7SEmilio Cota 
4311c0374e7SEmilio Cota // Approximate log(1+x).
4321c0374e7SEmilio Cota LogicalResult
4331c0374e7SEmilio Cota Log1pApproximation::matchAndRewrite(math::Log1pOp op,
4341c0374e7SEmilio Cota                                     PatternRewriter &rewriter) const {
4351c0374e7SEmilio Cota   auto width = vectorWidth(op.operand().getType(), isF32);
4361c0374e7SEmilio Cota   if (!width.hasValue())
4371c0374e7SEmilio Cota     return rewriter.notifyMatchFailure(op, "unsupported operand type");
4381c0374e7SEmilio Cota 
4391c0374e7SEmilio Cota   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
4401c0374e7SEmilio Cota   auto bcast = [&](Value value) -> Value {
4411c0374e7SEmilio Cota     return broadcast(builder, value, *width);
4421c0374e7SEmilio Cota   };
4431c0374e7SEmilio Cota 
4441c0374e7SEmilio Cota   // Approximate log(1+x) using the following, due to W. Kahan:
4451c0374e7SEmilio Cota   //   u = x + 1.0;
4461c0374e7SEmilio Cota   //   if (u == 1.0 || u == inf) return x;
4471c0374e7SEmilio Cota   //   return x * log(u) / (u - 1.0);
4481c0374e7SEmilio Cota   //          ^^^^^^^^^^^^^^^^^^^^^^
4491c0374e7SEmilio Cota   //             "logLarge" below.
4501c0374e7SEmilio Cota   Value cstOne = bcast(f32Cst(builder, 1.0f));
4511c0374e7SEmilio Cota   Value x = op.operand();
452*a54f4eaeSMogball   Value u = builder.create<arith::AddFOp>(x, cstOne);
453*a54f4eaeSMogball   Value uSmall =
454*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
4551c0374e7SEmilio Cota   Value logU = builder.create<math::LogOp>(u);
456*a54f4eaeSMogball   Value uInf =
457*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, logU);
458*a54f4eaeSMogball   Value logLarge = builder.create<arith::MulFOp>(
459*a54f4eaeSMogball       x, builder.create<arith::DivFOp>(
460*a54f4eaeSMogball              logU, builder.create<arith::SubFOp>(u, cstOne)));
461*a54f4eaeSMogball   Value approximation = builder.create<SelectOp>(
462*a54f4eaeSMogball       builder.create<arith::OrIOp>(uSmall, uInf), x, logLarge);
4631c0374e7SEmilio Cota   rewriter.replaceOp(op, approximation);
4641c0374e7SEmilio Cota   return success();
4651c0374e7SEmilio Cota }
4661c0374e7SEmilio Cota 
4671c0374e7SEmilio Cota //----------------------------------------------------------------------------//
468ea7f211bSAhmed Taei // Exp approximation.
469ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
470ea7f211bSAhmed Taei 
471ea7f211bSAhmed Taei namespace {
472ea7f211bSAhmed Taei 
473ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
474ea7f211bSAhmed Taei public:
475ea7f211bSAhmed Taei   using OpRewritePattern::OpRewritePattern;
476ea7f211bSAhmed Taei 
477ea7f211bSAhmed Taei   LogicalResult matchAndRewrite(math::ExpOp op,
478ea7f211bSAhmed Taei                                 PatternRewriter &rewriter) const final;
479ea7f211bSAhmed Taei };
480ea7f211bSAhmed Taei } // namespace
481ea7f211bSAhmed Taei 
482ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range
483ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
484ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y).
485ea7f211bSAhmed Taei LogicalResult
486ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op,
487ea7f211bSAhmed Taei                                   PatternRewriter &rewriter) const {
488ea7f211bSAhmed Taei   auto width = vectorWidth(op.operand().getType(), isF32);
489ea7f211bSAhmed Taei   if (!width.hasValue())
490ea7f211bSAhmed Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
491ea7f211bSAhmed Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
492ea7f211bSAhmed Taei 
493ea7f211bSAhmed Taei   // TODO: Consider a common pattern rewriter with all methods below to
494ea7f211bSAhmed Taei   // write the approximations.
495ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
496ea7f211bSAhmed Taei     return broadcast(builder, value, *width);
497ea7f211bSAhmed Taei   };
498ea7f211bSAhmed Taei   auto fmla = [&](Value a, Value b, Value c) {
499*a54f4eaeSMogball     return builder.create<math::FmaOp>(a, b, c);
500ea7f211bSAhmed Taei   };
501ea7f211bSAhmed Taei   auto mul = [&](Value a, Value b) -> Value {
502*a54f4eaeSMogball     return builder.create<arith::MulFOp>(a, b);
503ea7f211bSAhmed Taei   };
504ea7f211bSAhmed Taei   auto sub = [&](Value a, Value b) -> Value {
505*a54f4eaeSMogball     return builder.create<arith::SubFOp>(a, b);
506ea7f211bSAhmed Taei   };
507*a54f4eaeSMogball   auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
508ea7f211bSAhmed Taei 
509ea7f211bSAhmed Taei   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
510c0891706SEmilio Cota   Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
511ea7f211bSAhmed Taei 
512ea7f211bSAhmed Taei   // Polynomial coefficients.
513ea7f211bSAhmed Taei   Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
514ea7f211bSAhmed Taei   Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
515ea7f211bSAhmed Taei   Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
516ea7f211bSAhmed Taei   Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
517ea7f211bSAhmed Taei   Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
518ea7f211bSAhmed Taei   Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
519ea7f211bSAhmed Taei 
520ea7f211bSAhmed Taei   Value x = op.operand();
521ea7f211bSAhmed Taei 
522ea7f211bSAhmed Taei   // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
523c0891706SEmilio Cota   Value xL2Inv = mul(x, cstLog2E);
524ea7f211bSAhmed Taei   Value kF32 = floor(xL2Inv);
525ea7f211bSAhmed Taei   Value kLn2 = mul(kF32, cstLn2);
526ea7f211bSAhmed Taei   Value y = sub(x, kLn2);
527ea7f211bSAhmed Taei 
528ea7f211bSAhmed Taei   // Use Estrin's evaluation scheme with 3 independent parts:
529ea7f211bSAhmed Taei   // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
530ea7f211bSAhmed Taei   Value y2 = mul(y, y);
531ea7f211bSAhmed Taei   Value y4 = mul(y2, y2);
532ea7f211bSAhmed Taei 
533ea7f211bSAhmed Taei   Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
534ea7f211bSAhmed Taei   Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
535ea7f211bSAhmed Taei   Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
536ea7f211bSAhmed Taei   Value expY = fmla(q1, y2, q0);
537ea7f211bSAhmed Taei   expY = fmla(q2, y4, expY);
538ea7f211bSAhmed Taei 
539ea7f211bSAhmed Taei   auto i32Vec = broadcast(builder.getI32Type(), *width);
540ea7f211bSAhmed Taei 
541ea7f211bSAhmed Taei   // exp2(k)
542*a54f4eaeSMogball   Value k = builder.create<arith::FPToSIOp>(kF32, i32Vec);
543ea7f211bSAhmed Taei   Value exp2KValue = exp2I32(builder, k);
544ea7f211bSAhmed Taei 
545ea7f211bSAhmed Taei   // exp(x) = exp(y) * exp2(k)
546ea7f211bSAhmed Taei   expY = mul(expY, exp2KValue);
547ea7f211bSAhmed Taei 
548ea7f211bSAhmed Taei   // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
549ea7f211bSAhmed Taei   // partitioned as the following:
550ea7f211bSAhmed Taei   // exp(x) = 0, x <= -inf
551ea7f211bSAhmed Taei   // exp(x) = underflow (min_float), x <= -88
552ea7f211bSAhmed Taei   // exp(x) = inf (min_float), x >= 88
553ea7f211bSAhmed Taei   // Note: |k| = 127 is the value where the 8-bits exponent saturates.
554ea7f211bSAhmed Taei   Value zerof32Const = bcast(f32Cst(builder, 0));
555ea7f211bSAhmed Taei   auto constPosInfinity =
556ea7f211bSAhmed Taei       bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
557ea7f211bSAhmed Taei   auto constNegIfinity =
558ea7f211bSAhmed Taei       bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
559ea7f211bSAhmed Taei   auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
560ea7f211bSAhmed Taei 
561ea7f211bSAhmed Taei   Value kMaxConst = bcast(i32Cst(builder, 127));
562ea7f211bSAhmed Taei   Value kMaxNegConst = bcast(i32Cst(builder, -127));
563*a54f4eaeSMogball   Value rightBound =
564*a54f4eaeSMogball       builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, k, kMaxConst);
565*a54f4eaeSMogball   Value leftBound =
566*a54f4eaeSMogball       builder.create<arith::CmpIOp>(arith::CmpIPredicate::sge, k, kMaxNegConst);
567ea7f211bSAhmed Taei 
568*a54f4eaeSMogball   Value isNegInfinityX = builder.create<arith::CmpFOp>(
569*a54f4eaeSMogball       arith::CmpFPredicate::OEQ, x, constNegIfinity);
570ea7f211bSAhmed Taei   Value isPostiveX =
571*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zerof32Const);
572*a54f4eaeSMogball   Value isComputable = builder.create<arith::AndIOp>(rightBound, leftBound);
573ea7f211bSAhmed Taei 
574ea7f211bSAhmed Taei   expY = builder.create<SelectOp>(
575ea7f211bSAhmed Taei       isComputable, expY,
576ea7f211bSAhmed Taei       builder.create<SelectOp>(
577ea7f211bSAhmed Taei           isPostiveX, constPosInfinity,
578ea7f211bSAhmed Taei           builder.create<SelectOp>(isNegInfinityX, zerof32Const, underflow)));
579ea7f211bSAhmed Taei 
580ea7f211bSAhmed Taei   rewriter.replaceOp(op, expY);
581ea7f211bSAhmed Taei 
582ea7f211bSAhmed Taei   return success();
583ea7f211bSAhmed Taei }
584ea7f211bSAhmed Taei 
585ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
5860edc4bc8SEmilio Cota // ExpM1 approximation.
5870edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
5880edc4bc8SEmilio Cota 
5890edc4bc8SEmilio Cota namespace {
5900edc4bc8SEmilio Cota 
5910edc4bc8SEmilio Cota struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> {
5920edc4bc8SEmilio Cota public:
5930edc4bc8SEmilio Cota   using OpRewritePattern::OpRewritePattern;
5940edc4bc8SEmilio Cota 
5950edc4bc8SEmilio Cota   LogicalResult matchAndRewrite(math::ExpM1Op op,
5960edc4bc8SEmilio Cota                                 PatternRewriter &rewriter) const final;
5970edc4bc8SEmilio Cota };
5980edc4bc8SEmilio Cota } // namespace
5990edc4bc8SEmilio Cota 
6000edc4bc8SEmilio Cota LogicalResult
6010edc4bc8SEmilio Cota ExpM1Approximation::matchAndRewrite(math::ExpM1Op op,
6020edc4bc8SEmilio Cota                                     PatternRewriter &rewriter) const {
6030edc4bc8SEmilio Cota   auto width = vectorWidth(op.operand().getType(), isF32);
6040edc4bc8SEmilio Cota   if (!width.hasValue())
6050edc4bc8SEmilio Cota     return rewriter.notifyMatchFailure(op, "unsupported operand type");
6060edc4bc8SEmilio Cota 
6070edc4bc8SEmilio Cota   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
6080edc4bc8SEmilio Cota   auto bcast = [&](Value value) -> Value {
6090edc4bc8SEmilio Cota     return broadcast(builder, value, *width);
6100edc4bc8SEmilio Cota   };
6110edc4bc8SEmilio Cota 
6120edc4bc8SEmilio Cota   // expm1(x) = exp(x) - 1 = u - 1.
6130edc4bc8SEmilio Cota   // We have to handle it carefully when x is near 0, i.e. u ~= 1,
6140edc4bc8SEmilio Cota   // and when the input is ~= -inf, i.e. u - 1 ~= -1.
6150edc4bc8SEmilio Cota   Value cstOne = bcast(f32Cst(builder, 1.0f));
6160edc4bc8SEmilio Cota   Value cstNegOne = bcast(f32Cst(builder, -1.0f));
6170edc4bc8SEmilio Cota   Value x = op.operand();
6180edc4bc8SEmilio Cota   Value u = builder.create<math::ExpOp>(x);
619*a54f4eaeSMogball   Value uEqOne =
620*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
621*a54f4eaeSMogball   Value uMinusOne = builder.create<arith::SubFOp>(u, cstOne);
622*a54f4eaeSMogball   Value uMinusOneEqNegOne = builder.create<arith::CmpFOp>(
623*a54f4eaeSMogball       arith::CmpFPredicate::OEQ, uMinusOne, cstNegOne);
6240edc4bc8SEmilio Cota   // logU = log(u) ~= x
6250edc4bc8SEmilio Cota   Value logU = builder.create<math::LogOp>(u);
6260edc4bc8SEmilio Cota 
6270edc4bc8SEmilio Cota   // Detect exp(x) = +inf; written this way to avoid having to form +inf.
628*a54f4eaeSMogball   Value isInf =
629*a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, logU, u);
6300edc4bc8SEmilio Cota 
6310edc4bc8SEmilio Cota   // (u - 1) * (x / ~x)
632*a54f4eaeSMogball   Value expm1 = builder.create<arith::MulFOp>(
633*a54f4eaeSMogball       uMinusOne, builder.create<arith::DivFOp>(x, logU));
6340edc4bc8SEmilio Cota   expm1 = builder.create<SelectOp>(isInf, u, expm1);
6350edc4bc8SEmilio Cota   Value approximation = builder.create<SelectOp>(
6360edc4bc8SEmilio Cota       uEqOne, x, builder.create<SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1));
6370edc4bc8SEmilio Cota   rewriter.replaceOp(op, approximation);
6380edc4bc8SEmilio Cota   return success();
6390edc4bc8SEmilio Cota }
6400edc4bc8SEmilio Cota 
6410edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
6427e2d672aSAhmed S. Taei // Sin and Cos approximation.
6437e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
6447e2d672aSAhmed S. Taei 
6457e2d672aSAhmed S. Taei namespace {
6467e2d672aSAhmed S. Taei 
6477e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
6487e2d672aSAhmed S. Taei struct SinAndCosApproximation : public OpRewritePattern<OpTy> {
6497e2d672aSAhmed S. Taei public:
6507e2d672aSAhmed S. Taei   using OpRewritePattern<OpTy>::OpRewritePattern;
6517e2d672aSAhmed S. Taei 
6527e2d672aSAhmed S. Taei   LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final;
6537e2d672aSAhmed S. Taei };
6547e2d672aSAhmed S. Taei } // namespace
6557e2d672aSAhmed S. Taei 
6567e2d672aSAhmed S. Taei #define TWO_OVER_PI                                                            \
6577e2d672aSAhmed S. Taei   0.6366197723675813430755350534900574481378385829618257949906693762L
6587e2d672aSAhmed S. Taei #define PI_OVER_2                                                              \
6597e2d672aSAhmed S. Taei   1.5707963267948966192313216916397514420985846996875529104874722961L
6607e2d672aSAhmed S. Taei 
6617e2d672aSAhmed S. Taei // Approximates sin(x) or cos(x) by finding the best approximation polynomial in
6627e2d672aSAhmed S. Taei // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the
6637e2d672aSAhmed S. Taei // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y).
6647e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
6657e2d672aSAhmed S. Taei LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite(
6667e2d672aSAhmed S. Taei     OpTy op, PatternRewriter &rewriter) const {
6677e2d672aSAhmed S. Taei   static_assert(
6687e2d672aSAhmed S. Taei       llvm::is_one_of<OpTy, math::SinOp, math::CosOp>::value,
6697e2d672aSAhmed S. Taei       "SinAndCosApproximation pattern expects math::SinOp or math::CosOp");
6707e2d672aSAhmed S. Taei   auto width = vectorWidth(op.operand().getType(), isF32);
6717e2d672aSAhmed S. Taei   if (!width.hasValue())
6727e2d672aSAhmed S. Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
6737e2d672aSAhmed S. Taei 
6747e2d672aSAhmed S. Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
6757e2d672aSAhmed S. Taei   auto bcast = [&](Value value) -> Value {
6767e2d672aSAhmed S. Taei     return broadcast(builder, value, *width);
6777e2d672aSAhmed S. Taei   };
6787e2d672aSAhmed S. Taei   auto mul = [&](Value a, Value b) -> Value {
679*a54f4eaeSMogball     return builder.create<arith::MulFOp>(a, b);
6807e2d672aSAhmed S. Taei   };
6817e2d672aSAhmed S. Taei   auto sub = [&](Value a, Value b) -> Value {
682*a54f4eaeSMogball     return builder.create<arith::SubFOp>(a, b);
6837e2d672aSAhmed S. Taei   };
684*a54f4eaeSMogball   auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
6857e2d672aSAhmed S. Taei 
6867e2d672aSAhmed S. Taei   auto i32Vec = broadcast(builder.getI32Type(), *width);
6877e2d672aSAhmed S. Taei   auto fPToSingedInteger = [&](Value a) -> Value {
688*a54f4eaeSMogball     return builder.create<arith::FPToSIOp>(a, i32Vec);
6897e2d672aSAhmed S. Taei   };
6907e2d672aSAhmed S. Taei 
6917e2d672aSAhmed S. Taei   auto modulo4 = [&](Value a) -> Value {
692*a54f4eaeSMogball     return builder.create<arith::AndIOp>(a, bcast(i32Cst(builder, 3)));
6937e2d672aSAhmed S. Taei   };
6947e2d672aSAhmed S. Taei 
6957e2d672aSAhmed S. Taei   auto isEqualTo = [&](Value a, Value b) -> Value {
696*a54f4eaeSMogball     return builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, a, b);
6977e2d672aSAhmed S. Taei   };
6987e2d672aSAhmed S. Taei 
6997e2d672aSAhmed S. Taei   auto isGreaterThan = [&](Value a, Value b) -> Value {
700*a54f4eaeSMogball     return builder.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, a, b);
7017e2d672aSAhmed S. Taei   };
7027e2d672aSAhmed S. Taei 
7037e2d672aSAhmed S. Taei   auto select = [&](Value cond, Value t, Value f) -> Value {
7047e2d672aSAhmed S. Taei     return builder.create<SelectOp>(cond, t, f);
7057e2d672aSAhmed S. Taei   };
7067e2d672aSAhmed S. Taei 
7077e2d672aSAhmed S. Taei   auto fmla = [&](Value a, Value b, Value c) {
708*a54f4eaeSMogball     return builder.create<math::FmaOp>(a, b, c);
7097e2d672aSAhmed S. Taei   };
7107e2d672aSAhmed S. Taei 
711*a54f4eaeSMogball   auto bitwiseOr = [&](Value a, Value b) {
712*a54f4eaeSMogball     return builder.create<arith::OrIOp>(a, b);
713*a54f4eaeSMogball   };
7147e2d672aSAhmed S. Taei 
7157e2d672aSAhmed S. Taei   Value twoOverPi = bcast(f32Cst(builder, TWO_OVER_PI));
7167e2d672aSAhmed S. Taei   Value piOverTwo = bcast(f32Cst(builder, PI_OVER_2));
7177e2d672aSAhmed S. Taei 
7187e2d672aSAhmed S. Taei   Value x = op.operand();
7197e2d672aSAhmed S. Taei 
7207e2d672aSAhmed S. Taei   Value k = floor(mul(x, twoOverPi));
7217e2d672aSAhmed S. Taei 
7227e2d672aSAhmed S. Taei   Value y = sub(x, mul(k, piOverTwo));
7237e2d672aSAhmed S. Taei 
7247e2d672aSAhmed S. Taei   Value cstOne = bcast(f32Cst(builder, 1.0));
7257e2d672aSAhmed S. Taei   Value cstNegativeOne = bcast(f32Cst(builder, -1.0));
7267e2d672aSAhmed S. Taei 
7277e2d672aSAhmed S. Taei   Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f));
7287e2d672aSAhmed S. Taei   Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f));
7297e2d672aSAhmed S. Taei   Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f));
7307e2d672aSAhmed S. Taei   Value cstSC8 =
7317e2d672aSAhmed S. Taei       bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f));
7327e2d672aSAhmed S. Taei   Value cstSC10 =
7337e2d672aSAhmed S. Taei       bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f));
7347e2d672aSAhmed S. Taei 
7357e2d672aSAhmed S. Taei   Value cstCC2 = bcast(f32Cst(builder, -0.5f));
7367e2d672aSAhmed S. Taei   Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f));
7377e2d672aSAhmed S. Taei   Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f));
7387e2d672aSAhmed S. Taei   Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f));
7397e2d672aSAhmed S. Taei   Value cstCC10 =
7407e2d672aSAhmed S. Taei       bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f));
7417e2d672aSAhmed S. Taei 
7427e2d672aSAhmed S. Taei   Value kMod4 = modulo4(fPToSingedInteger(k));
7437e2d672aSAhmed S. Taei 
7447e2d672aSAhmed S. Taei   Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0)));
7457e2d672aSAhmed S. Taei   Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1)));
7467e2d672aSAhmed S. Taei   Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2)));
7477e2d672aSAhmed S. Taei   Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3)));
7487e2d672aSAhmed S. Taei 
7497e2d672aSAhmed S. Taei   Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2);
7507e2d672aSAhmed S. Taei   Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1)))
7517e2d672aSAhmed S. Taei                                : bitwiseOr(kR1, kR2);
7527e2d672aSAhmed S. Taei 
7537e2d672aSAhmed S. Taei   Value y2 = mul(y, y);
7547e2d672aSAhmed S. Taei 
7557e2d672aSAhmed S. Taei   Value base = select(sinuseCos, cstOne, y);
7567e2d672aSAhmed S. Taei   Value cstC2 = select(sinuseCos, cstCC2, cstSC2);
7577e2d672aSAhmed S. Taei   Value cstC4 = select(sinuseCos, cstCC4, cstSC4);
7587e2d672aSAhmed S. Taei   Value cstC6 = select(sinuseCos, cstCC6, cstSC6);
7597e2d672aSAhmed S. Taei   Value cstC8 = select(sinuseCos, cstCC8, cstSC8);
7607e2d672aSAhmed S. Taei   Value cstC10 = select(sinuseCos, cstCC10, cstSC10);
7617e2d672aSAhmed S. Taei 
7627e2d672aSAhmed S. Taei   Value v1 = fmla(y2, cstC10, cstC8);
7637e2d672aSAhmed S. Taei   Value v2 = fmla(y2, v1, cstC6);
7647e2d672aSAhmed S. Taei   Value v3 = fmla(y2, v2, cstC4);
7657e2d672aSAhmed S. Taei   Value v4 = fmla(y2, v3, cstC2);
7667e2d672aSAhmed S. Taei   Value v5 = fmla(y2, v4, cstOne);
7677e2d672aSAhmed S. Taei   Value v6 = mul(base, v5);
7687e2d672aSAhmed S. Taei 
7697e2d672aSAhmed S. Taei   Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6);
7707e2d672aSAhmed S. Taei 
7717e2d672aSAhmed S. Taei   rewriter.replaceOp(op, approximation);
7727e2d672aSAhmed S. Taei 
7737e2d672aSAhmed S. Taei   return success();
7747e2d672aSAhmed S. Taei }
7757e2d672aSAhmed S. Taei 
7767e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
777f99ccf65SEugene Zhulenev 
778f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns(
779dc4e913bSChris Lattner     RewritePatternSet &patterns) {
780dc4e913bSChris Lattner   patterns.add<TanhApproximation, LogApproximation, Log2Approximation,
7817e2d672aSAhmed S. Taei                Log1pApproximation, ExpApproximation, ExpM1Approximation,
7827e2d672aSAhmed S. Taei                SinAndCosApproximation<true, math::SinOp>,
7837e2d672aSAhmed S. Taei                SinAndCosApproximation<false, math::CosOp>>(
7840edc4bc8SEmilio Cota       patterns.getContext());
785f99ccf65SEugene Zhulenev }
786