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 
14ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
15ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMTypes.h"
16f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/IR/Math.h"
17f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/Transforms/Passes.h"
18f99ccf65SEugene Zhulenev #include "mlir/Dialect/Vector/VectorOps.h"
19f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h"
20ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
213a506b31SChris Lattner #include "mlir/Transforms/Bufferize.h"
22f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h"
23f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
243a506b31SChris Lattner #include <climits>
25f99ccf65SEugene Zhulenev 
26f99ccf65SEugene Zhulenev using namespace mlir;
27f99ccf65SEugene Zhulenev using namespace mlir::vector;
28f99ccf65SEugene Zhulenev 
29ce976d2dSEugene Zhulenev using TypePredicate = llvm::function_ref<bool(Type)>;
30ce976d2dSEugene Zhulenev 
31ce976d2dSEugene Zhulenev // Returns vector width if the element type is matching the predicate (scalars
32ce976d2dSEugene Zhulenev // that do match the predicate have width equal to `1`).
33ce976d2dSEugene Zhulenev static Optional<int> vectorWidth(Type type, TypePredicate pred) {
34ce976d2dSEugene Zhulenev   // If the type matches the predicate then its width is `1`.
35ce976d2dSEugene Zhulenev   if (pred(type))
36ce976d2dSEugene Zhulenev     return 1;
37ce976d2dSEugene Zhulenev 
38ce976d2dSEugene Zhulenev   // Otherwise check if the type is a vector type.
39ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
40ce976d2dSEugene Zhulenev   if (vectorType && pred(vectorType.getElementType())) {
41ce976d2dSEugene Zhulenev     assert(vectorType.getRank() == 1 && "only 1d vectors are supported");
42ce976d2dSEugene Zhulenev     return vectorType.getDimSize(0);
43ce976d2dSEugene Zhulenev   }
44ce976d2dSEugene Zhulenev 
45ce976d2dSEugene Zhulenev   return llvm::None;
46ce976d2dSEugene Zhulenev }
47ce976d2dSEugene Zhulenev 
48ce976d2dSEugene Zhulenev // Returns vector width of the type. If the type is a scalar returns `1`.
49ce976d2dSEugene Zhulenev static int vectorWidth(Type type) {
50ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
51ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getDimSize(0) : 1;
52ce976d2dSEugene Zhulenev }
53ce976d2dSEugene Zhulenev 
54ce976d2dSEugene Zhulenev // Returns vector element type. If the type is a scalar returns the argument.
5539b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static Type elementType(Type type) {
56ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
57ce976d2dSEugene Zhulenev   return vectorType ? vectorType.getElementType() : type;
58f99ccf65SEugene Zhulenev }
59f99ccf65SEugene Zhulenev 
6039b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isF32(Type type) { return type.isF32(); }
6139b2cd40SEugene Zhulenev 
6239b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isI32(Type type) {
6339b2cd40SEugene Zhulenev   return type.isInteger(32);
6439b2cd40SEugene Zhulenev }
6539b2cd40SEugene Zhulenev 
66f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
67ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values.
68f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
69f99ccf65SEugene Zhulenev 
70ce976d2dSEugene Zhulenev // Broadcasts scalar type into vector type (iff width is greater then 1).
71ce976d2dSEugene Zhulenev static Type broadcast(Type type, int width) {
72ce976d2dSEugene Zhulenev   assert(!type.isa<VectorType>() && "must be scalar type");
73ce976d2dSEugene Zhulenev   return width > 1 ? VectorType::get({width}, type) : type;
74ce976d2dSEugene Zhulenev }
75f99ccf65SEugene Zhulenev 
76ce976d2dSEugene Zhulenev // Broadcasts scalar value into vector (iff width is greater then 1).
77ce976d2dSEugene Zhulenev static Value broadcast(ImplicitLocOpBuilder &builder, Value value, int width) {
78ce976d2dSEugene Zhulenev   assert(!value.getType().isa<VectorType>() && "must be scalar value");
79ce976d2dSEugene Zhulenev   auto type = broadcast(value.getType(), width);
80ce976d2dSEugene Zhulenev   return width > 1 ? builder.create<BroadcastOp>(type, value) : value;
81ce976d2dSEugene Zhulenev }
82f99ccf65SEugene Zhulenev 
83ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
84ce976d2dSEugene Zhulenev // Helper functions to create constants.
85ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
86f99ccf65SEugene Zhulenev 
87ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
88ce976d2dSEugene Zhulenev   return builder.create<ConstantOp>(builder.getF32Type(),
89ce976d2dSEugene Zhulenev                                     builder.getF32FloatAttr(value));
90ce976d2dSEugene Zhulenev }
91f99ccf65SEugene Zhulenev 
92ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
93ce976d2dSEugene Zhulenev   return builder.create<ConstantOp>(builder.getI32Type(),
94ce976d2dSEugene Zhulenev                                     builder.getI32IntegerAttr(value));
95ce976d2dSEugene Zhulenev }
96f99ccf65SEugene Zhulenev 
97ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
98ce976d2dSEugene Zhulenev   Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
99ce976d2dSEugene Zhulenev   return builder.create<LLVM::BitcastOp>(builder.getF32Type(), i32Value);
100ce976d2dSEugene Zhulenev }
101f99ccf65SEugene Zhulenev 
102ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
103ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations.
104ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
105ce976d2dSEugene Zhulenev 
106ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) {
107ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
108ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OLT, a, b), a, b);
109ce976d2dSEugene Zhulenev }
110ce976d2dSEugene Zhulenev 
111ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) {
112ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
113ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OGT, a, b), a, b);
114ce976d2dSEugene Zhulenev }
115ce976d2dSEugene Zhulenev 
116ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
117ce976d2dSEugene Zhulenev                    Value upperBound) {
118ce976d2dSEugene Zhulenev   return max(builder, min(builder, value, upperBound), lowerBound);
119ce976d2dSEugene Zhulenev }
120ce976d2dSEugene Zhulenev 
121ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and
122ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type.
123ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
124ce976d2dSEugene Zhulenev                                      bool is_positive = false) {
125ce976d2dSEugene Zhulenev   assert(isF32(elementType(arg.getType())) && "argument must be f32 type");
126ce976d2dSEugene Zhulenev 
127ce976d2dSEugene Zhulenev   int width = vectorWidth(arg.getType());
128ce976d2dSEugene Zhulenev 
129ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
130ce976d2dSEugene Zhulenev     return broadcast(builder, value, width);
131f99ccf65SEugene Zhulenev   };
132f99ccf65SEugene Zhulenev 
133ce976d2dSEugene Zhulenev   auto i32 = builder.getIntegerType(32);
134ce976d2dSEugene Zhulenev   auto i32Vec = broadcast(i32, width);
135ce976d2dSEugene Zhulenev   auto f32Vec = broadcast(builder.getF32Type(), width);
136f99ccf65SEugene Zhulenev 
137ce976d2dSEugene Zhulenev   Value cst126f = f32Cst(builder, 126.0f);
138ce976d2dSEugene Zhulenev   Value cstHalf = f32Cst(builder, 0.5f);
139ce976d2dSEugene Zhulenev   Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
140f99ccf65SEugene Zhulenev 
141ce976d2dSEugene Zhulenev   // Bitcast to i32 for bitwise operations.
142ce976d2dSEugene Zhulenev   Value i32Half = builder.create<LLVM::BitcastOp>(i32, cstHalf);
143ce976d2dSEugene Zhulenev   Value i32InvMantMask = builder.create<LLVM::BitcastOp>(i32, cstInvMantMask);
144ce976d2dSEugene Zhulenev   Value i32Arg = builder.create<LLVM::BitcastOp>(i32Vec, arg);
145f99ccf65SEugene Zhulenev 
146ce976d2dSEugene Zhulenev   // Compute normalized fraction.
147ce976d2dSEugene Zhulenev   Value tmp0 = builder.create<LLVM::AndOp>(i32Arg, bcast(i32InvMantMask));
148ce976d2dSEugene Zhulenev   Value tmp1 = builder.create<LLVM::OrOp>(tmp0, bcast(i32Half));
149ce976d2dSEugene Zhulenev   Value normalizedFraction = builder.create<LLVM::BitcastOp>(f32Vec, tmp1);
150f99ccf65SEugene Zhulenev 
151ce976d2dSEugene Zhulenev   // Compute exponent.
152ce976d2dSEugene Zhulenev   Value arg0 = is_positive ? arg : builder.create<AbsFOp>(arg);
153ce976d2dSEugene Zhulenev   Value biasedExponentBits = builder.create<UnsignedShiftRightOp>(
154ce976d2dSEugene Zhulenev       builder.create<LLVM::BitcastOp>(i32Vec, arg0),
155ce976d2dSEugene Zhulenev       bcast(i32Cst(builder, 23)));
156ce976d2dSEugene Zhulenev   Value biasedExponent = builder.create<SIToFPOp>(f32Vec, biasedExponentBits);
157ce976d2dSEugene Zhulenev   Value exponent = builder.create<SubFOp>(biasedExponent, bcast(cst126f));
158f99ccf65SEugene Zhulenev 
159ce976d2dSEugene Zhulenev   return {normalizedFraction, exponent};
160f99ccf65SEugene Zhulenev }
161f99ccf65SEugene Zhulenev 
162ea7f211bSAhmed Taei // Computes exp2 for an i32 argument.
163ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
164ea7f211bSAhmed Taei   assert(isI32(elementType(arg.getType())) && "argument must be i32 type");
165ea7f211bSAhmed Taei 
166ea7f211bSAhmed Taei   int width = vectorWidth(arg.getType());
167ea7f211bSAhmed Taei 
168ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
169ea7f211bSAhmed Taei     return broadcast(builder, value, width);
170ea7f211bSAhmed Taei   };
171ea7f211bSAhmed Taei 
172ea7f211bSAhmed Taei   auto f32Vec = broadcast(builder.getF32Type(), width);
173ea7f211bSAhmed Taei   // The exponent of f32 located at 23-bit.
174ea7f211bSAhmed Taei   auto exponetBitLocation = bcast(i32Cst(builder, 23));
175ea7f211bSAhmed Taei   // Set the exponent bias to zero.
176ea7f211bSAhmed Taei   auto bias = bcast(i32Cst(builder, 127));
177ea7f211bSAhmed Taei 
178ea7f211bSAhmed Taei   Value biasedArg = builder.create<AddIOp>(arg, bias);
179ea7f211bSAhmed Taei   Value exp2ValueInt =
180ea7f211bSAhmed Taei       builder.create<ShiftLeftOp>(biasedArg, exponetBitLocation);
181ea7f211bSAhmed Taei   Value exp2ValueF32 = builder.create<LLVM::BitcastOp>(f32Vec, exp2ValueInt);
182ea7f211bSAhmed Taei 
183ea7f211bSAhmed Taei   return exp2ValueF32;
184ea7f211bSAhmed Taei }
185ea7f211bSAhmed Taei 
186f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
187f99ccf65SEugene Zhulenev // TanhOp approximation.
188f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
189f99ccf65SEugene Zhulenev 
190f99ccf65SEugene Zhulenev namespace {
191f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
192f99ccf65SEugene Zhulenev public:
193f99ccf65SEugene Zhulenev   using OpRewritePattern::OpRewritePattern;
194f99ccf65SEugene Zhulenev 
195f99ccf65SEugene Zhulenev   LogicalResult matchAndRewrite(math::TanhOp op,
196f99ccf65SEugene Zhulenev                                 PatternRewriter &rewriter) const final;
197f99ccf65SEugene Zhulenev };
198f99ccf65SEugene Zhulenev } // namespace
199f99ccf65SEugene Zhulenev 
200f99ccf65SEugene Zhulenev LogicalResult
201f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op,
202f99ccf65SEugene Zhulenev                                    PatternRewriter &rewriter) const {
203ce976d2dSEugene Zhulenev   auto width = vectorWidth(op.operand().getType(), isF32);
204ce976d2dSEugene Zhulenev   if (!width.hasValue())
205f99ccf65SEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
206f99ccf65SEugene Zhulenev 
207ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
208ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
209ce976d2dSEugene Zhulenev     return broadcast(builder, value, *width);
210ce976d2dSEugene Zhulenev   };
211f99ccf65SEugene Zhulenev 
212f99ccf65SEugene Zhulenev   // Clamp operand into [plusClamp, minusClamp] range.
213ce976d2dSEugene Zhulenev   Value minusClamp = bcast(f32Cst(builder, -7.9053111076354980f));
214ce976d2dSEugene Zhulenev   Value plusClamp = bcast(f32Cst(builder, 7.90531110763549805f));
215ce976d2dSEugene Zhulenev   Value x = clamp(builder, op.operand(), minusClamp, plusClamp);
216f99ccf65SEugene Zhulenev 
217f99ccf65SEugene Zhulenev   // Mask for tiny values that are approximated with `operand`.
218ce976d2dSEugene Zhulenev   Value tiny = bcast(f32Cst(builder, 0.0004f));
219ce976d2dSEugene Zhulenev   Value tinyMask = builder.create<CmpFOp>(
220ce976d2dSEugene Zhulenev       CmpFPredicate::OLT, builder.create<AbsFOp>(op.operand()), 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.
238ce976d2dSEugene Zhulenev   Value x2 = builder.create<MulFOp>(x, x);
239f99ccf65SEugene Zhulenev 
240f99ccf65SEugene Zhulenev   // Evaluate the numerator polynomial p.
241ce976d2dSEugene Zhulenev   Value p = builder.create<FmaFOp>(x2, alpha13, alpha11);
242ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha9);
243ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha7);
244ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha5);
245ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha3);
246ce976d2dSEugene Zhulenev   p = builder.create<FmaFOp>(x2, p, alpha1);
247ce976d2dSEugene Zhulenev   p = builder.create<MulFOp>(x, p);
248f99ccf65SEugene Zhulenev 
249f99ccf65SEugene Zhulenev   // Evaluate the denominator polynomial q.
250ce976d2dSEugene Zhulenev   Value q = builder.create<FmaFOp>(x2, beta6, beta4);
251ce976d2dSEugene Zhulenev   q = builder.create<FmaFOp>(x2, q, beta2);
252ce976d2dSEugene Zhulenev   q = builder.create<FmaFOp>(x2, q, beta0);
253f99ccf65SEugene Zhulenev 
254f99ccf65SEugene Zhulenev   // Divide the numerator by the denominator.
255ce976d2dSEugene Zhulenev   Value res =
256ce976d2dSEugene Zhulenev       builder.create<SelectOp>(tinyMask, x, builder.create<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; }
338ce976d2dSEugene Zhulenev   Value mask = builder.create<CmpFOp>(CmpFPredicate::OLT, x, cstCephesSQRTHF);
339ce976d2dSEugene Zhulenev   Value tmp = builder.create<SelectOp>(mask, x, cstZero);
340ce976d2dSEugene Zhulenev 
341ce976d2dSEugene Zhulenev   x = builder.create<SubFOp>(x, cstOne);
342ce976d2dSEugene Zhulenev   e = builder.create<SubFOp>(e,
343ce976d2dSEugene Zhulenev                              builder.create<SelectOp>(mask, cstOne, cstZero));
344ce976d2dSEugene Zhulenev   x = builder.create<AddFOp>(x, tmp);
345ce976d2dSEugene Zhulenev 
346ce976d2dSEugene Zhulenev   Value x2 = builder.create<MulFOp>(x, x);
347ce976d2dSEugene Zhulenev   Value x3 = builder.create<MulFOp>(x2, x);
348ce976d2dSEugene Zhulenev 
349ce976d2dSEugene Zhulenev   // Evaluate the polynomial approximant of degree 8 in three parts.
350ce976d2dSEugene Zhulenev   Value y0, y1, y2;
351ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(cstCephesLogP0, x, cstCephesLogP1);
352ce976d2dSEugene Zhulenev   y1 = builder.create<FmaFOp>(cstCephesLogP3, x, cstCephesLogP4);
353ce976d2dSEugene Zhulenev   y2 = builder.create<FmaFOp>(cstCephesLogP6, x, cstCephesLogP7);
354ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x, cstCephesLogP2);
355ce976d2dSEugene Zhulenev   y1 = builder.create<FmaFOp>(y1, x, cstCephesLogP5);
356ce976d2dSEugene Zhulenev   y2 = builder.create<FmaFOp>(y2, x, cstCephesLogP8);
357ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x3, y1);
358ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(y0, x3, y2);
359ce976d2dSEugene Zhulenev   y0 = builder.create<MulFOp>(y0, x3);
360ce976d2dSEugene Zhulenev 
361ce976d2dSEugene Zhulenev   y0 = builder.create<FmaFOp>(cstNegHalf, x2, y0);
362ce976d2dSEugene Zhulenev   x = builder.create<AddFOp>(x, y0);
363ce976d2dSEugene Zhulenev 
364c0891706SEmilio Cota   if (base2) {
365c0891706SEmilio Cota     Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
366c0891706SEmilio Cota     x = builder.create<FmaFOp>(x, cstLog2e, e);
367c0891706SEmilio Cota   } else {
368ce976d2dSEugene Zhulenev     Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
369ce976d2dSEugene Zhulenev     x = builder.create<FmaFOp>(e, cstLn2, x);
370c0891706SEmilio Cota   }
371ce976d2dSEugene Zhulenev 
372ce976d2dSEugene Zhulenev   Value invalidMask =
373ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::ULT, op.operand(), cstZero);
374ce976d2dSEugene Zhulenev   Value zeroMask =
375ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstZero);
376ce976d2dSEugene Zhulenev   Value posInfMask =
377ce976d2dSEugene Zhulenev       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstPosInf);
378ce976d2dSEugene Zhulenev 
379ce976d2dSEugene Zhulenev   // Filter out invalid values:
380ce976d2dSEugene Zhulenev   //  • x == 0     -> -INF
381ce976d2dSEugene Zhulenev   //  • x < 0      ->  NAN
382ce976d2dSEugene Zhulenev   //  • x == +INF  -> +INF
383ce976d2dSEugene Zhulenev   Value aproximation = builder.create<SelectOp>(
384ce976d2dSEugene Zhulenev       zeroMask, cstMinusInf,
385ce976d2dSEugene Zhulenev       builder.create<SelectOp>(
386ce976d2dSEugene Zhulenev           invalidMask, cstNan,
387ce976d2dSEugene Zhulenev           builder.create<SelectOp>(posInfMask, cstPosInf, x)));
388ce976d2dSEugene Zhulenev 
389ce976d2dSEugene Zhulenev   rewriter.replaceOp(op, aproximation);
390ce976d2dSEugene Zhulenev 
391ce976d2dSEugene Zhulenev   return success();
392ce976d2dSEugene Zhulenev }
393ce976d2dSEugene Zhulenev 
394c0891706SEmilio Cota namespace {
395c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> {
396c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
397c0891706SEmilio Cota 
398c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::LogOp op,
399c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
400c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/false);
401c0891706SEmilio Cota   }
402c0891706SEmilio Cota };
403c0891706SEmilio Cota } // namespace
404c0891706SEmilio Cota 
405c0891706SEmilio Cota namespace {
406c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
407c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
408c0891706SEmilio Cota 
409c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::Log2Op op,
410c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
411c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/true);
412c0891706SEmilio Cota   }
413c0891706SEmilio Cota };
414c0891706SEmilio Cota } // namespace
415c0891706SEmilio Cota 
416ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
417ea7f211bSAhmed Taei // Exp approximation.
418ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
419ea7f211bSAhmed Taei 
420ea7f211bSAhmed Taei namespace {
421ea7f211bSAhmed Taei 
422ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
423ea7f211bSAhmed Taei public:
424ea7f211bSAhmed Taei   using OpRewritePattern::OpRewritePattern;
425ea7f211bSAhmed Taei 
426ea7f211bSAhmed Taei   LogicalResult matchAndRewrite(math::ExpOp op,
427ea7f211bSAhmed Taei                                 PatternRewriter &rewriter) const final;
428ea7f211bSAhmed Taei };
429ea7f211bSAhmed Taei } // namespace
430ea7f211bSAhmed Taei 
431ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range
432ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
433ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y).
434ea7f211bSAhmed Taei LogicalResult
435ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op,
436ea7f211bSAhmed Taei                                   PatternRewriter &rewriter) const {
437ea7f211bSAhmed Taei   auto width = vectorWidth(op.operand().getType(), isF32);
438ea7f211bSAhmed Taei   if (!width.hasValue())
439ea7f211bSAhmed Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
440ea7f211bSAhmed Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
441ea7f211bSAhmed Taei 
442ea7f211bSAhmed Taei   // TODO: Consider a common pattern rewriter with all methods below to
443ea7f211bSAhmed Taei   // write the approximations.
444ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
445ea7f211bSAhmed Taei     return broadcast(builder, value, *width);
446ea7f211bSAhmed Taei   };
447ea7f211bSAhmed Taei   auto fmla = [&](Value a, Value b, Value c) {
448ea7f211bSAhmed Taei     return builder.create<FmaFOp>(a, b, c);
449ea7f211bSAhmed Taei   };
450ea7f211bSAhmed Taei   auto mul = [&](Value a, Value b) -> Value {
451ea7f211bSAhmed Taei     return builder.create<MulFOp>(a, b);
452ea7f211bSAhmed Taei   };
453ea7f211bSAhmed Taei   auto sub = [&](Value a, Value b) -> Value {
454ea7f211bSAhmed Taei     return builder.create<SubFOp>(a, b);
455ea7f211bSAhmed Taei   };
456ea7f211bSAhmed Taei   auto floor = [&](Value a) { return builder.create<FloorFOp>(a); };
457ea7f211bSAhmed Taei 
458ea7f211bSAhmed Taei   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
459c0891706SEmilio Cota   Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
460ea7f211bSAhmed Taei 
461ea7f211bSAhmed Taei   // Polynomial coefficients.
462ea7f211bSAhmed Taei   Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
463ea7f211bSAhmed Taei   Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
464ea7f211bSAhmed Taei   Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
465ea7f211bSAhmed Taei   Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
466ea7f211bSAhmed Taei   Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
467ea7f211bSAhmed Taei   Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
468ea7f211bSAhmed Taei 
469ea7f211bSAhmed Taei   Value x = op.operand();
470ea7f211bSAhmed Taei 
471ea7f211bSAhmed Taei   // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
472c0891706SEmilio Cota   Value xL2Inv = mul(x, cstLog2E);
473ea7f211bSAhmed Taei   Value kF32 = floor(xL2Inv);
474ea7f211bSAhmed Taei   Value kLn2 = mul(kF32, cstLn2);
475ea7f211bSAhmed Taei   Value y = sub(x, kLn2);
476ea7f211bSAhmed Taei 
477ea7f211bSAhmed Taei   // Use Estrin's evaluation scheme with 3 independent parts:
478ea7f211bSAhmed Taei   // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
479ea7f211bSAhmed Taei   Value y2 = mul(y, y);
480ea7f211bSAhmed Taei   Value y4 = mul(y2, y2);
481ea7f211bSAhmed Taei 
482ea7f211bSAhmed Taei   Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
483ea7f211bSAhmed Taei   Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
484ea7f211bSAhmed Taei   Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
485ea7f211bSAhmed Taei   Value expY = fmla(q1, y2, q0);
486ea7f211bSAhmed Taei   expY = fmla(q2, y4, expY);
487ea7f211bSAhmed Taei 
488ea7f211bSAhmed Taei   auto i32Vec = broadcast(builder.getI32Type(), *width);
489ea7f211bSAhmed Taei 
490ea7f211bSAhmed Taei   // exp2(k)
491ea7f211bSAhmed Taei   Value k = builder.create<FPToSIOp>(kF32, i32Vec);
492ea7f211bSAhmed Taei   Value exp2KValue = exp2I32(builder, k);
493ea7f211bSAhmed Taei 
494ea7f211bSAhmed Taei   // exp(x) = exp(y) * exp2(k)
495ea7f211bSAhmed Taei   expY = mul(expY, exp2KValue);
496ea7f211bSAhmed Taei 
497ea7f211bSAhmed Taei   // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
498ea7f211bSAhmed Taei   // partitioned as the following:
499ea7f211bSAhmed Taei   // exp(x) = 0, x <= -inf
500ea7f211bSAhmed Taei   // exp(x) = underflow (min_float), x <= -88
501ea7f211bSAhmed Taei   // exp(x) = inf (min_float), x >= 88
502ea7f211bSAhmed Taei   // Note: |k| = 127 is the value where the 8-bits exponent saturates.
503ea7f211bSAhmed Taei   Value zerof32Const = bcast(f32Cst(builder, 0));
504ea7f211bSAhmed Taei   auto constPosInfinity =
505ea7f211bSAhmed Taei       bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
506ea7f211bSAhmed Taei   auto constNegIfinity =
507ea7f211bSAhmed Taei       bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
508ea7f211bSAhmed Taei   auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
509ea7f211bSAhmed Taei 
510ea7f211bSAhmed Taei   Value kMaxConst = bcast(i32Cst(builder, 127));
511ea7f211bSAhmed Taei   Value kMaxNegConst = bcast(i32Cst(builder, -127));
512ea7f211bSAhmed Taei   Value rightBound = builder.create<CmpIOp>(CmpIPredicate::sle, k, kMaxConst);
513ea7f211bSAhmed Taei   Value leftBound = builder.create<CmpIOp>(CmpIPredicate::sge, k, kMaxNegConst);
514ea7f211bSAhmed Taei 
515ea7f211bSAhmed Taei   Value isNegInfinityX =
516ea7f211bSAhmed Taei       builder.create<CmpFOp>(CmpFPredicate::OEQ, x, constNegIfinity);
517ea7f211bSAhmed Taei   Value isPostiveX =
518ea7f211bSAhmed Taei       builder.create<CmpFOp>(CmpFPredicate::OGT, x, zerof32Const);
519ea7f211bSAhmed Taei   Value isComputable = builder.create<AndOp>(rightBound, leftBound);
520ea7f211bSAhmed Taei 
521ea7f211bSAhmed Taei   expY = builder.create<SelectOp>(
522ea7f211bSAhmed Taei       isComputable, expY,
523ea7f211bSAhmed Taei       builder.create<SelectOp>(
524ea7f211bSAhmed Taei           isPostiveX, constPosInfinity,
525ea7f211bSAhmed Taei           builder.create<SelectOp>(isNegInfinityX, zerof32Const, underflow)));
526ea7f211bSAhmed Taei 
527ea7f211bSAhmed Taei   rewriter.replaceOp(op, expY);
528ea7f211bSAhmed Taei 
529ea7f211bSAhmed Taei   return success();
530ea7f211bSAhmed Taei }
531ea7f211bSAhmed Taei 
532ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
533f99ccf65SEugene Zhulenev 
534f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns(
535*dc4e913bSChris Lattner     RewritePatternSet &patterns) {
536*dc4e913bSChris Lattner   patterns.add<TanhApproximation, LogApproximation, Log2Approximation,
5373a506b31SChris Lattner                ExpApproximation>(patterns.getContext());
538f99ccf65SEugene Zhulenev }
539