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
14ec32d540SEugene Zhulenev #include <climits>
15ec32d540SEugene Zhulenev #include <cstddef>
16ec32d540SEugene Zhulenev
17a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
18f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/IR/Math.h"
19f1b92218SBoian Petkantchin #include "mlir/Dialect/Math/Transforms/Approximation.h"
20f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/Transforms/Passes.h"
2199ef9eebSMatthias Springer #include "mlir/Dialect/Utils/IndexingUtils.h"
2299ef9eebSMatthias Springer #include "mlir/Dialect/Vector/IR/VectorOps.h"
2399ef9eebSMatthias Springer #include "mlir/Dialect/Vector/Utils/VectorUtils.h"
2435553d45SEmilio Cota #include "mlir/Dialect/X86Vector/X86VectorDialect.h"
25f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h"
26bbddd19eSJacques Pienaar #include "mlir/IR/BuiltinTypes.h"
27ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
28bbddd19eSJacques Pienaar #include "mlir/IR/OpDefinition.h"
29bbddd19eSJacques Pienaar #include "mlir/IR/PatternMatch.h"
30ec32d540SEugene Zhulenev #include "mlir/IR/TypeUtilities.h"
31f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h"
32f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
33f1b92218SBoian Petkantchin #include "llvm/ADT/ArrayRef.h"
34bbddd19eSJacques Pienaar #include "llvm/ADT/STLExtras.h"
35f99ccf65SEugene Zhulenev
36f99ccf65SEugene Zhulenev using namespace mlir;
37f1b92218SBoian Petkantchin using namespace mlir::math;
38f99ccf65SEugene Zhulenev using namespace mlir::vector;
39f99ccf65SEugene Zhulenev
40ec32d540SEugene Zhulenev // Returns vector shape if the type is a vector. Returns an empty shape if it is
41ec32d540SEugene Zhulenev // not a vector.
vectorShape(Type type)42ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Type type) {
43ce976d2dSEugene Zhulenev auto vectorType = type.dyn_cast<VectorType>();
44ec32d540SEugene Zhulenev return vectorType ? vectorType.getShape() : ArrayRef<int64_t>();
45ce976d2dSEugene Zhulenev }
46ce976d2dSEugene Zhulenev
vectorShape(Value value)47ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Value value) {
48ec32d540SEugene Zhulenev return vectorShape(value.getType());
4939b2cd40SEugene Zhulenev }
5039b2cd40SEugene Zhulenev
51f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
52ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values.
53f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
54f99ccf65SEugene Zhulenev
5596cee297SAlexander Belyaev // Broadcasts scalar type into vector type (iff shape is non-scalar).
broadcast(Type type,ArrayRef<int64_t> shape)5696cee297SAlexander Belyaev static Type broadcast(Type type, ArrayRef<int64_t> shape) {
5796cee297SAlexander Belyaev assert(!type.isa<VectorType>() && "must be scalar type");
58ec32d540SEugene Zhulenev return !shape.empty() ? VectorType::get(shape, type) : type;
5996cee297SAlexander Belyaev }
6096cee297SAlexander Belyaev
6196cee297SAlexander Belyaev // Broadcasts scalar value into vector (iff shape is non-scalar).
broadcast(ImplicitLocOpBuilder & builder,Value value,ArrayRef<int64_t> shape)6296cee297SAlexander Belyaev static Value broadcast(ImplicitLocOpBuilder &builder, Value value,
6396cee297SAlexander Belyaev ArrayRef<int64_t> shape) {
64ce976d2dSEugene Zhulenev assert(!value.getType().isa<VectorType>() && "must be scalar value");
6596cee297SAlexander Belyaev auto type = broadcast(value.getType(), shape);
66ec32d540SEugene Zhulenev return !shape.empty() ? builder.create<BroadcastOp>(type, value) : value;
67ce976d2dSEugene Zhulenev }
68f99ccf65SEugene Zhulenev
69ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
70627fa0b9SEugene Zhulenev // Helper function to handle n-D vectors with 1-D operations.
71627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------//
72627fa0b9SEugene Zhulenev
73627fa0b9SEugene Zhulenev // Expands and unrolls n-D vector operands into multiple fixed size 1-D vectors
74627fa0b9SEugene Zhulenev // and calls the compute function with 1-D vector operands. Stitches back all
75627fa0b9SEugene Zhulenev // results into the original n-D vector result.
76627fa0b9SEugene Zhulenev //
77627fa0b9SEugene Zhulenev // Examples: vectorWidth = 8
78627fa0b9SEugene Zhulenev // - vector<4x8xf32> unrolled 4 times
79627fa0b9SEugene Zhulenev // - vector<16xf32> expanded to vector<2x8xf32> and unrolled 2 times
80627fa0b9SEugene Zhulenev // - vector<4x16xf32> expanded to vector<4x2x8xf32> and unrolled 4*2 times
81627fa0b9SEugene Zhulenev //
82627fa0b9SEugene Zhulenev // Some math approximations rely on ISA-specific operations that only accept
83627fa0b9SEugene Zhulenev // fixed size 1-D vectors (e.g. AVX expects vectors of width 8).
84627fa0b9SEugene Zhulenev //
85627fa0b9SEugene Zhulenev // It is the caller's responsibility to verify that the inner dimension is
86627fa0b9SEugene Zhulenev // divisible by the vectorWidth, and that all operands have the same vector
87627fa0b9SEugene Zhulenev // shape.
88627fa0b9SEugene Zhulenev static Value
handleMultidimensionalVectors(ImplicitLocOpBuilder & builder,ValueRange operands,int64_t vectorWidth,llvm::function_ref<Value (ValueRange)> compute)89627fa0b9SEugene Zhulenev handleMultidimensionalVectors(ImplicitLocOpBuilder &builder,
90627fa0b9SEugene Zhulenev ValueRange operands, int64_t vectorWidth,
911fc096afSMehdi Amini llvm::function_ref<Value(ValueRange)> compute) {
92627fa0b9SEugene Zhulenev assert(!operands.empty() && "operands must be not empty");
93627fa0b9SEugene Zhulenev assert(vectorWidth > 0 && "vector width must be larger than 0");
94627fa0b9SEugene Zhulenev
95627fa0b9SEugene Zhulenev VectorType inputType = operands[0].getType().cast<VectorType>();
96627fa0b9SEugene Zhulenev ArrayRef<int64_t> inputShape = inputType.getShape();
97627fa0b9SEugene Zhulenev
98627fa0b9SEugene Zhulenev // If input shape matches target vector width, we can just call the
99627fa0b9SEugene Zhulenev // user-provided compute function with the operands.
100627fa0b9SEugene Zhulenev if (inputShape == llvm::makeArrayRef(vectorWidth))
101627fa0b9SEugene Zhulenev return compute(operands);
102627fa0b9SEugene Zhulenev
103627fa0b9SEugene Zhulenev // Check if the inner dimension has to be expanded, or we can directly iterate
104627fa0b9SEugene Zhulenev // over the outer dimensions of the vector.
105627fa0b9SEugene Zhulenev int64_t innerDim = inputShape.back();
106627fa0b9SEugene Zhulenev int64_t expansionDim = innerDim / vectorWidth;
107627fa0b9SEugene Zhulenev assert((innerDim % vectorWidth == 0) && "invalid inner dimension size");
108627fa0b9SEugene Zhulenev
109627fa0b9SEugene Zhulenev // Maybe expand operands to the higher rank vector shape that we'll use to
110627fa0b9SEugene Zhulenev // iterate over and extract one dimensional vectors.
111627fa0b9SEugene Zhulenev SmallVector<int64_t> expandedShape(inputShape.begin(), inputShape.end());
112627fa0b9SEugene Zhulenev SmallVector<Value> expandedOperands(operands);
113627fa0b9SEugene Zhulenev
114627fa0b9SEugene Zhulenev if (expansionDim > 1) {
115627fa0b9SEugene Zhulenev // Expand shape from [..., innerDim] to [..., expansionDim, vectorWidth].
116627fa0b9SEugene Zhulenev expandedShape.insert(expandedShape.end() - 1, expansionDim);
117627fa0b9SEugene Zhulenev expandedShape.back() = vectorWidth;
118627fa0b9SEugene Zhulenev
119627fa0b9SEugene Zhulenev for (unsigned i = 0; i < operands.size(); ++i) {
120627fa0b9SEugene Zhulenev auto operand = operands[i];
121627fa0b9SEugene Zhulenev auto eltType = operand.getType().cast<VectorType>().getElementType();
122627fa0b9SEugene Zhulenev auto expandedType = VectorType::get(expandedShape, eltType);
123627fa0b9SEugene Zhulenev expandedOperands[i] =
124627fa0b9SEugene Zhulenev builder.create<vector::ShapeCastOp>(expandedType, operand);
125627fa0b9SEugene Zhulenev }
126627fa0b9SEugene Zhulenev }
127627fa0b9SEugene Zhulenev
128627fa0b9SEugene Zhulenev // Iterate over all outer dimensions of the compute shape vector type.
129627fa0b9SEugene Zhulenev auto iterationDims = ArrayRef<int64_t>(expandedShape).drop_back();
130627fa0b9SEugene Zhulenev int64_t maxLinearIndex = computeMaxLinearIndex(iterationDims);
131627fa0b9SEugene Zhulenev
132627fa0b9SEugene Zhulenev SmallVector<int64_t> ones(iterationDims.size(), 1);
133627fa0b9SEugene Zhulenev auto strides = computeStrides(iterationDims, ones);
134627fa0b9SEugene Zhulenev
135627fa0b9SEugene Zhulenev // Compute results for each one dimensional vector.
136627fa0b9SEugene Zhulenev SmallVector<Value> results(maxLinearIndex);
137627fa0b9SEugene Zhulenev
138627fa0b9SEugene Zhulenev for (int64_t i = 0; i < maxLinearIndex; ++i) {
139627fa0b9SEugene Zhulenev auto offsets = delinearize(strides, i);
140627fa0b9SEugene Zhulenev
141627fa0b9SEugene Zhulenev SmallVector<Value> extracted(expandedOperands.size());
14289de9cc8SMehdi Amini for (const auto &tuple : llvm::enumerate(expandedOperands))
143627fa0b9SEugene Zhulenev extracted[tuple.index()] =
144627fa0b9SEugene Zhulenev builder.create<vector::ExtractOp>(tuple.value(), offsets);
145627fa0b9SEugene Zhulenev
146627fa0b9SEugene Zhulenev results[i] = compute(extracted);
147627fa0b9SEugene Zhulenev }
148627fa0b9SEugene Zhulenev
149627fa0b9SEugene Zhulenev // Stitch results together into one large vector.
150627fa0b9SEugene Zhulenev Type resultEltType = results[0].getType().cast<VectorType>().getElementType();
151627fa0b9SEugene Zhulenev Type resultExpandedType = VectorType::get(expandedShape, resultEltType);
1528e123ca6SRiver Riddle Value result = builder.create<arith::ConstantOp>(
153627fa0b9SEugene Zhulenev resultExpandedType, builder.getZeroAttr(resultExpandedType));
154627fa0b9SEugene Zhulenev
155627fa0b9SEugene Zhulenev for (int64_t i = 0; i < maxLinearIndex; ++i)
156627fa0b9SEugene Zhulenev result = builder.create<vector::InsertOp>(results[i], result,
157627fa0b9SEugene Zhulenev delinearize(strides, i));
158627fa0b9SEugene Zhulenev
159627fa0b9SEugene Zhulenev // Reshape back to the original vector shape.
160627fa0b9SEugene Zhulenev return builder.create<vector::ShapeCastOp>(
161627fa0b9SEugene Zhulenev VectorType::get(inputShape, resultEltType), result);
162627fa0b9SEugene Zhulenev }
163627fa0b9SEugene Zhulenev
164627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------//
165ce976d2dSEugene Zhulenev // Helper functions to create constants.
166ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
167f99ccf65SEugene Zhulenev
f32Cst(ImplicitLocOpBuilder & builder,float value)168ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
169a54f4eaeSMogball return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value));
170ce976d2dSEugene Zhulenev }
171f99ccf65SEugene Zhulenev
i32Cst(ImplicitLocOpBuilder & builder,int32_t value)172ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
173a54f4eaeSMogball return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value));
174ce976d2dSEugene Zhulenev }
175f99ccf65SEugene Zhulenev
f32FromBits(ImplicitLocOpBuilder & builder,uint32_t bits)176ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
177ce976d2dSEugene Zhulenev Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
178a54f4eaeSMogball return builder.create<arith::BitcastOp>(builder.getF32Type(), i32Value);
179ce976d2dSEugene Zhulenev }
180f99ccf65SEugene Zhulenev
181ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
182ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations.
183ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
184ce976d2dSEugene Zhulenev
185*f5efe280STres Popp // Return the minimum of the two values or NaN if value is NaN
min(ImplicitLocOpBuilder & builder,Value value,Value bound)186*f5efe280STres Popp static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound) {
187dec8af70SRiver Riddle return builder.create<arith::SelectOp>(
188*f5efe280STres Popp builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT, value, bound),
189*f5efe280STres Popp value, bound);
190ce976d2dSEugene Zhulenev }
191ce976d2dSEugene Zhulenev
192*f5efe280STres Popp // Return the maximum of the two values or NaN if value is NaN
max(ImplicitLocOpBuilder & builder,Value value,Value bound)193*f5efe280STres Popp static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound) {
194dec8af70SRiver Riddle return builder.create<arith::SelectOp>(
195*f5efe280STres Popp builder.create<arith::CmpFOp>(arith::CmpFPredicate::UGT, value, bound),
196*f5efe280STres Popp value, bound);
197ce976d2dSEugene Zhulenev }
198ce976d2dSEugene Zhulenev
199*f5efe280STres Popp // Return the clamped value or NaN if value is NaN
clamp(ImplicitLocOpBuilder & builder,Value value,Value lowerBound,Value upperBound)200ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
201ce976d2dSEugene Zhulenev Value upperBound) {
202ce976d2dSEugene Zhulenev return max(builder, min(builder, value, upperBound), lowerBound);
203ce976d2dSEugene Zhulenev }
204ce976d2dSEugene Zhulenev
205ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and
206ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type.
frexp(ImplicitLocOpBuilder & builder,Value arg,bool isPositive=false)207ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
20802b6fb21SMehdi Amini bool isPositive = false) {
209ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(arg).isF32() && "arg must be f32 type");
210ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(arg);
211ce976d2dSEugene Zhulenev
212ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value {
21396cee297SAlexander Belyaev return broadcast(builder, value, shape);
214f99ccf65SEugene Zhulenev };
215f99ccf65SEugene Zhulenev
216ce976d2dSEugene Zhulenev auto i32 = builder.getIntegerType(32);
21796cee297SAlexander Belyaev auto i32Vec = broadcast(i32, shape);
21896cee297SAlexander Belyaev auto f32Vec = broadcast(builder.getF32Type(), shape);
219f99ccf65SEugene Zhulenev
220ce976d2dSEugene Zhulenev Value cst126f = f32Cst(builder, 126.0f);
221ce976d2dSEugene Zhulenev Value cstHalf = f32Cst(builder, 0.5f);
222ce976d2dSEugene Zhulenev Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
223f99ccf65SEugene Zhulenev
224ce976d2dSEugene Zhulenev // Bitcast to i32 for bitwise operations.
225a54f4eaeSMogball Value i32Half = builder.create<arith::BitcastOp>(i32, cstHalf);
226a54f4eaeSMogball Value i32InvMantMask = builder.create<arith::BitcastOp>(i32, cstInvMantMask);
227a54f4eaeSMogball Value i32Arg = builder.create<arith::BitcastOp>(i32Vec, arg);
228f99ccf65SEugene Zhulenev
229ce976d2dSEugene Zhulenev // Compute normalized fraction.
230a54f4eaeSMogball Value tmp0 = builder.create<arith::AndIOp>(i32Arg, bcast(i32InvMantMask));
231a54f4eaeSMogball Value tmp1 = builder.create<arith::OrIOp>(tmp0, bcast(i32Half));
232a54f4eaeSMogball Value normalizedFraction = builder.create<arith::BitcastOp>(f32Vec, tmp1);
233f99ccf65SEugene Zhulenev
234ce976d2dSEugene Zhulenev // Compute exponent.
23502b6fb21SMehdi Amini Value arg0 = isPositive ? arg : builder.create<math::AbsOp>(arg);
236a54f4eaeSMogball Value biasedExponentBits = builder.create<arith::ShRUIOp>(
237a54f4eaeSMogball builder.create<arith::BitcastOp>(i32Vec, arg0),
238a54f4eaeSMogball bcast(i32Cst(builder, 23)));
239a54f4eaeSMogball Value biasedExponent =
240a54f4eaeSMogball builder.create<arith::SIToFPOp>(f32Vec, biasedExponentBits);
241a54f4eaeSMogball Value exponent =
242a54f4eaeSMogball builder.create<arith::SubFOp>(biasedExponent, bcast(cst126f));
243f99ccf65SEugene Zhulenev
244ce976d2dSEugene Zhulenev return {normalizedFraction, exponent};
245f99ccf65SEugene Zhulenev }
246f99ccf65SEugene Zhulenev
247ea7f211bSAhmed Taei // Computes exp2 for an i32 argument.
exp2I32(ImplicitLocOpBuilder & builder,Value arg)248ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
249ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(arg).isInteger(32) && "arg must be i32 type");
250ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(arg);
251ea7f211bSAhmed Taei
252ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value {
25396cee297SAlexander Belyaev return broadcast(builder, value, shape);
254ea7f211bSAhmed Taei };
255ea7f211bSAhmed Taei
25696cee297SAlexander Belyaev auto f32Vec = broadcast(builder.getF32Type(), shape);
257ea7f211bSAhmed Taei // The exponent of f32 located at 23-bit.
258ea7f211bSAhmed Taei auto exponetBitLocation = bcast(i32Cst(builder, 23));
259ea7f211bSAhmed Taei // Set the exponent bias to zero.
260ea7f211bSAhmed Taei auto bias = bcast(i32Cst(builder, 127));
261ea7f211bSAhmed Taei
262a54f4eaeSMogball Value biasedArg = builder.create<arith::AddIOp>(arg, bias);
263ea7f211bSAhmed Taei Value exp2ValueInt =
264a54f4eaeSMogball builder.create<arith::ShLIOp>(biasedArg, exponetBitLocation);
265a54f4eaeSMogball Value exp2ValueF32 = builder.create<arith::BitcastOp>(f32Vec, exp2ValueInt);
266ea7f211bSAhmed Taei
267ea7f211bSAhmed Taei return exp2ValueF32;
268ea7f211bSAhmed Taei }
269ea7f211bSAhmed Taei
270f1b92218SBoian Petkantchin namespace {
makePolynomialCalculation(ImplicitLocOpBuilder & builder,llvm::ArrayRef<Value> coeffs,Value x)271f1b92218SBoian Petkantchin Value makePolynomialCalculation(ImplicitLocOpBuilder &builder,
272f1b92218SBoian Petkantchin llvm::ArrayRef<Value> coeffs, Value x) {
273ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(x).isF32() && "x must be f32 type");
274ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(x);
275ec32d540SEugene Zhulenev
276ec32d540SEugene Zhulenev if (coeffs.empty())
277ec32d540SEugene Zhulenev return broadcast(builder, f32Cst(builder, 0.0f), shape);
278ec32d540SEugene Zhulenev
279ec32d540SEugene Zhulenev if (coeffs.size() == 1)
280f1b92218SBoian Petkantchin return coeffs[0];
281ec32d540SEugene Zhulenev
282f1b92218SBoian Petkantchin Value res = builder.create<math::FmaOp>(x, coeffs[coeffs.size() - 1],
283f1b92218SBoian Petkantchin coeffs[coeffs.size() - 2]);
284f1b92218SBoian Petkantchin for (auto i = ptrdiff_t(coeffs.size()) - 3; i >= 0; --i) {
285f1b92218SBoian Petkantchin res = builder.create<math::FmaOp>(x, res, coeffs[i]);
286f1b92218SBoian Petkantchin }
287f1b92218SBoian Petkantchin return res;
288f1b92218SBoian Petkantchin }
289f1b92218SBoian Petkantchin } // namespace
290f1b92218SBoian Petkantchin
291f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
292bbddd19eSJacques Pienaar // Helper function/pattern to insert casts for reusing F32 bit expansion.
293bbddd19eSJacques Pienaar //----------------------------------------------------------------------------//
294bbddd19eSJacques Pienaar
295bbddd19eSJacques Pienaar template <typename T>
insertCasts(Operation * op,PatternRewriter & rewriter)296bbddd19eSJacques Pienaar LogicalResult insertCasts(Operation *op, PatternRewriter &rewriter) {
297bbddd19eSJacques Pienaar // Conservatively only allow where the operand and result types are exactly 1.
298bbddd19eSJacques Pienaar Type origType = op->getResultTypes().front();
299bbddd19eSJacques Pienaar for (Type t : llvm::drop_begin(op->getResultTypes()))
300bbddd19eSJacques Pienaar if (origType != t)
301bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op, "required all types to match");
302bbddd19eSJacques Pienaar for (Type t : op->getOperandTypes())
303bbddd19eSJacques Pienaar if (origType != t)
304bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op, "required all types to match");
305bbddd19eSJacques Pienaar
306bbddd19eSJacques Pienaar // Skip if already F32 or larger than 32 bits.
307bbddd19eSJacques Pienaar if (getElementTypeOrSelf(origType).isF32() ||
308bbddd19eSJacques Pienaar getElementTypeOrSelf(origType).getIntOrFloatBitWidth() > 32)
309bbddd19eSJacques Pienaar return failure();
310bbddd19eSJacques Pienaar
311bbddd19eSJacques Pienaar // Create F32 equivalent type.
312bbddd19eSJacques Pienaar Type newType;
313bbddd19eSJacques Pienaar if (auto shaped = origType.dyn_cast<ShapedType>()) {
314bbddd19eSJacques Pienaar newType = shaped.clone(rewriter.getF32Type());
315bbddd19eSJacques Pienaar } else if (origType.isa<FloatType>()) {
316bbddd19eSJacques Pienaar newType = rewriter.getF32Type();
317bbddd19eSJacques Pienaar } else {
318bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op,
319bbddd19eSJacques Pienaar "unable to find F32 equivalent type");
320bbddd19eSJacques Pienaar }
321bbddd19eSJacques Pienaar
322bbddd19eSJacques Pienaar Location loc = op->getLoc();
323bbddd19eSJacques Pienaar SmallVector<Value> operands;
324bbddd19eSJacques Pienaar for (auto operand : op->getOperands())
325bbddd19eSJacques Pienaar operands.push_back(rewriter.create<arith::ExtFOp>(loc, newType, operand));
326bbddd19eSJacques Pienaar auto result = rewriter.create<math::Atan2Op>(loc, newType, operands);
327bbddd19eSJacques Pienaar rewriter.replaceOpWithNewOp<arith::TruncFOp>(op, origType, result);
328bbddd19eSJacques Pienaar return success();
329bbddd19eSJacques Pienaar }
330bbddd19eSJacques Pienaar
331bbddd19eSJacques Pienaar namespace {
332bbddd19eSJacques Pienaar // Pattern to cast to F32 to reuse F32 expansion as fallback for single-result
333bbddd19eSJacques Pienaar // op.
334bbddd19eSJacques Pienaar // TODO: Consider revising to avoid adding multiple casts for a subgraph that is
335bbddd19eSJacques Pienaar // all in lower precision. Currently this is only fallback support and performs
336bbddd19eSJacques Pienaar // simplistic casting.
337bbddd19eSJacques Pienaar template <typename T>
338bbddd19eSJacques Pienaar struct ReuseF32Expansion : public OpRewritePattern<T> {
339bbddd19eSJacques Pienaar public:
340bbddd19eSJacques Pienaar using OpRewritePattern<T>::OpRewritePattern;
matchAndRewrite__anond27a14240411::ReuseF32Expansion341bbddd19eSJacques Pienaar LogicalResult matchAndRewrite(T op, PatternRewriter &rewriter) const final {
342bbddd19eSJacques Pienaar static_assert(
343bbddd19eSJacques Pienaar T::template hasTrait<mlir::OpTrait::SameOperandsAndResultType>(),
344bbddd19eSJacques Pienaar "requires same operands and result types");
345bbddd19eSJacques Pienaar return insertCasts<T>(op, rewriter);
346bbddd19eSJacques Pienaar }
347bbddd19eSJacques Pienaar };
348bbddd19eSJacques Pienaar } // namespace
349bbddd19eSJacques Pienaar
350bbddd19eSJacques Pienaar //----------------------------------------------------------------------------//
3512f9f9afaSRob Suderman // AtanOp approximation.
3522f9f9afaSRob Suderman //----------------------------------------------------------------------------//
3532f9f9afaSRob Suderman
3542f9f9afaSRob Suderman namespace {
3552f9f9afaSRob Suderman struct AtanApproximation : public OpRewritePattern<math::AtanOp> {
3562f9f9afaSRob Suderman public:
3572f9f9afaSRob Suderman using OpRewritePattern::OpRewritePattern;
3582f9f9afaSRob Suderman
3592f9f9afaSRob Suderman LogicalResult matchAndRewrite(math::AtanOp op,
3602f9f9afaSRob Suderman PatternRewriter &rewriter) const final;
3612f9f9afaSRob Suderman };
3622f9f9afaSRob Suderman } // namespace
3632f9f9afaSRob Suderman
3642f9f9afaSRob Suderman LogicalResult
matchAndRewrite(math::AtanOp op,PatternRewriter & rewriter) const3652f9f9afaSRob Suderman AtanApproximation::matchAndRewrite(math::AtanOp op,
3662f9f9afaSRob Suderman PatternRewriter &rewriter) const {
3672f9f9afaSRob Suderman auto operand = op.getOperand();
3682f9f9afaSRob Suderman if (!getElementTypeOrSelf(operand).isF32())
3692f9f9afaSRob Suderman return rewriter.notifyMatchFailure(op, "unsupported operand type");
3702f9f9afaSRob Suderman
3712f9f9afaSRob Suderman ArrayRef<int64_t> shape = vectorShape(op.getOperand());
3722f9f9afaSRob Suderman
3732f9f9afaSRob Suderman ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
3742f9f9afaSRob Suderman auto one = broadcast(builder, f32Cst(builder, 1.0f), shape);
3752f9f9afaSRob Suderman
3762f9f9afaSRob Suderman // Remap the problem over [0.0, 1.0] by looking at the absolute value and the
3772f9f9afaSRob Suderman // handling symmetry.
3782f9f9afaSRob Suderman Value abs = builder.create<math::AbsOp>(operand);
3792f9f9afaSRob Suderman Value reciprocal = builder.create<arith::DivFOp>(one, abs);
3802f9f9afaSRob Suderman Value compare =
3812f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, abs, reciprocal);
382dec8af70SRiver Riddle Value x = builder.create<arith::SelectOp>(compare, abs, reciprocal);
3832f9f9afaSRob Suderman
3842f9f9afaSRob Suderman // Perform the Taylor series approximation for atan over the range
3852f9f9afaSRob Suderman // [-1.0, 1.0].
386dc3b9365SAlexandre Ganea auto n1 = broadcast(builder, f32Cst(builder, 0.14418283f), shape);
387dc3b9365SAlexandre Ganea auto n2 = broadcast(builder, f32Cst(builder, -0.34999234f), shape);
388dc3b9365SAlexandre Ganea auto n3 = broadcast(builder, f32Cst(builder, -0.01067831f), shape);
389dc3b9365SAlexandre Ganea auto n4 = broadcast(builder, f32Cst(builder, 1.00209986f), shape);
3902f9f9afaSRob Suderman
3912f9f9afaSRob Suderman Value p = builder.create<math::FmaOp>(x, n1, n2);
3922f9f9afaSRob Suderman p = builder.create<math::FmaOp>(x, p, n3);
3932f9f9afaSRob Suderman p = builder.create<math::FmaOp>(x, p, n4);
3942f9f9afaSRob Suderman p = builder.create<arith::MulFOp>(x, p);
3952f9f9afaSRob Suderman
3962f9f9afaSRob Suderman // Remap the solution for over [0.0, 1.0] to [0.0, inf]
39770ed93ecSMehdi Amini auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape);
39870ed93ecSMehdi Amini Value sub = builder.create<arith::SubFOp>(halfPi, p);
399dec8af70SRiver Riddle Value select = builder.create<arith::SelectOp>(compare, p, sub);
4002f9f9afaSRob Suderman
4012f9f9afaSRob Suderman // Correct for signing of the input.
4022f9f9afaSRob Suderman rewriter.replaceOpWithNewOp<math::CopySignOp>(op, select, operand);
4032f9f9afaSRob Suderman return success();
4042f9f9afaSRob Suderman }
4052f9f9afaSRob Suderman
4062f9f9afaSRob Suderman //----------------------------------------------------------------------------//
4072f9f9afaSRob Suderman // AtanOp approximation.
4082f9f9afaSRob Suderman //----------------------------------------------------------------------------//
4092f9f9afaSRob Suderman
4102f9f9afaSRob Suderman namespace {
4112f9f9afaSRob Suderman struct Atan2Approximation : public OpRewritePattern<math::Atan2Op> {
4122f9f9afaSRob Suderman public:
4132f9f9afaSRob Suderman using OpRewritePattern::OpRewritePattern;
4142f9f9afaSRob Suderman
4152f9f9afaSRob Suderman LogicalResult matchAndRewrite(math::Atan2Op op,
4162f9f9afaSRob Suderman PatternRewriter &rewriter) const final;
4172f9f9afaSRob Suderman };
4182f9f9afaSRob Suderman } // namespace
4192f9f9afaSRob Suderman
4202f9f9afaSRob Suderman LogicalResult
matchAndRewrite(math::Atan2Op op,PatternRewriter & rewriter) const4212f9f9afaSRob Suderman Atan2Approximation::matchAndRewrite(math::Atan2Op op,
4222f9f9afaSRob Suderman PatternRewriter &rewriter) const {
4232f9f9afaSRob Suderman auto y = op.getOperand(0);
4242f9f9afaSRob Suderman auto x = op.getOperand(1);
4252f9f9afaSRob Suderman if (!getElementTypeOrSelf(x).isF32())
4262f9f9afaSRob Suderman return rewriter.notifyMatchFailure(op, "unsupported operand type");
4272f9f9afaSRob Suderman
4282f9f9afaSRob Suderman ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
4292f9f9afaSRob Suderman ArrayRef<int64_t> shape = vectorShape(op.getResult());
4302f9f9afaSRob Suderman
4312f9f9afaSRob Suderman // Compute atan in the valid range.
4322f9f9afaSRob Suderman auto div = builder.create<arith::DivFOp>(y, x);
4332f9f9afaSRob Suderman auto atan = builder.create<math::AtanOp>(div);
4342f9f9afaSRob Suderman
4352f9f9afaSRob Suderman // Determine what the atan would be for a 180 degree rotation.
4362f9f9afaSRob Suderman auto zero = broadcast(builder, f32Cst(builder, 0.0f), shape);
4372f9f9afaSRob Suderman auto pi = broadcast(builder, f32Cst(builder, 3.14159265359f), shape);
43870ed93ecSMehdi Amini auto addPi = builder.create<arith::AddFOp>(atan, pi);
43970ed93ecSMehdi Amini auto subPi = builder.create<arith::SubFOp>(atan, pi);
44070ed93ecSMehdi Amini auto atanGt =
4412f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, atan, zero);
442dec8af70SRiver Riddle auto flippedAtan = builder.create<arith::SelectOp>(atanGt, subPi, addPi);
4432f9f9afaSRob Suderman
4442f9f9afaSRob Suderman // Determine whether to directly use atan or use the 180 degree flip
44570ed93ecSMehdi Amini auto xGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zero);
446dec8af70SRiver Riddle Value result = builder.create<arith::SelectOp>(xGt, atan, flippedAtan);
4472f9f9afaSRob Suderman
4482f9f9afaSRob Suderman // Handle x = 0, y > 0
44970ed93ecSMehdi Amini Value xZero =
4502f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, x, zero);
45170ed93ecSMehdi Amini Value yGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, y, zero);
45270ed93ecSMehdi Amini Value isHalfPi = builder.create<arith::AndIOp>(xZero, yGt);
45370ed93ecSMehdi Amini auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape);
454dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isHalfPi, halfPi, result);
4552f9f9afaSRob Suderman
4562f9f9afaSRob Suderman // Handle x = 0, y < 0
45770ed93ecSMehdi Amini Value yLt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, y, zero);
45870ed93ecSMehdi Amini Value isNegativeHalfPiPi = builder.create<arith::AndIOp>(xZero, yLt);
45970ed93ecSMehdi Amini auto negativeHalfPiPi =
460dc3b9365SAlexandre Ganea broadcast(builder, f32Cst(builder, -1.57079632679f), shape);
461dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isNegativeHalfPiPi, negativeHalfPiPi,
462dec8af70SRiver Riddle result);
4632f9f9afaSRob Suderman
4642f9f9afaSRob Suderman // Handle x = 0, y = 0;
46570ed93ecSMehdi Amini Value yZero =
4662f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, y, zero);
46770ed93ecSMehdi Amini Value isNan = builder.create<arith::AndIOp>(xZero, yZero);
46870ed93ecSMehdi Amini Value cstNan = broadcast(builder, f32FromBits(builder, 0x7fc00000), shape);
469dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isNan, cstNan, result);
4702f9f9afaSRob Suderman
4712f9f9afaSRob Suderman rewriter.replaceOp(op, result);
4722f9f9afaSRob Suderman return success();
4732f9f9afaSRob Suderman }
4742f9f9afaSRob Suderman
4752f9f9afaSRob Suderman //----------------------------------------------------------------------------//
476f99ccf65SEugene Zhulenev // TanhOp approximation.
477f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
478f99ccf65SEugene Zhulenev
479f99ccf65SEugene Zhulenev namespace {
480f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
481f99ccf65SEugene Zhulenev public:
482f99ccf65SEugene Zhulenev using OpRewritePattern::OpRewritePattern;
483f99ccf65SEugene Zhulenev
484f99ccf65SEugene Zhulenev LogicalResult matchAndRewrite(math::TanhOp op,
485f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const final;
486f99ccf65SEugene Zhulenev };
487f99ccf65SEugene Zhulenev } // namespace
488f99ccf65SEugene Zhulenev
489f99ccf65SEugene Zhulenev LogicalResult
matchAndRewrite(math::TanhOp op,PatternRewriter & rewriter) const490f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op,
491f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const {
49262fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
493f99ccf65SEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type");
494f99ccf65SEugene Zhulenev
49562fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
496ec32d540SEugene Zhulenev
497ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
498ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value {
499ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
500ce976d2dSEugene Zhulenev };
501f99ccf65SEugene Zhulenev
502f99ccf65SEugene Zhulenev // Clamp operand into [plusClamp, minusClamp] range.
503bf32bb7eSEugene Zhulenev Value minusClamp = bcast(f32Cst(builder, -7.99881172180175781f));
504bf32bb7eSEugene Zhulenev Value plusClamp = bcast(f32Cst(builder, 7.99881172180175781f));
50562fea88bSJacques Pienaar Value x = clamp(builder, op.getOperand(), minusClamp, plusClamp);
506f99ccf65SEugene Zhulenev
507f99ccf65SEugene Zhulenev // Mask for tiny values that are approximated with `operand`.
508ce976d2dSEugene Zhulenev Value tiny = bcast(f32Cst(builder, 0.0004f));
509a54f4eaeSMogball Value tinyMask = builder.create<arith::CmpFOp>(
51062fea88bSJacques Pienaar arith::CmpFPredicate::OLT, builder.create<math::AbsOp>(op.getOperand()),
511a54f4eaeSMogball tiny);
512f99ccf65SEugene Zhulenev
513f99ccf65SEugene Zhulenev // The monomial coefficients of the numerator polynomial (odd).
514ce976d2dSEugene Zhulenev Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
515ce976d2dSEugene Zhulenev Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
516ce976d2dSEugene Zhulenev Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
517ce976d2dSEugene Zhulenev Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
518ce976d2dSEugene Zhulenev Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
519ce976d2dSEugene Zhulenev Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
520ce976d2dSEugene Zhulenev Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
521f99ccf65SEugene Zhulenev
522f99ccf65SEugene Zhulenev // The monomial coefficients of the denominator polynomial (even).
523ce976d2dSEugene Zhulenev Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
524ce976d2dSEugene Zhulenev Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
525ce976d2dSEugene Zhulenev Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
526ce976d2dSEugene Zhulenev Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
527f99ccf65SEugene Zhulenev
528f99ccf65SEugene Zhulenev // Since the polynomials are odd/even, we need x^2.
529a54f4eaeSMogball Value x2 = builder.create<arith::MulFOp>(x, x);
530f99ccf65SEugene Zhulenev
531f99ccf65SEugene Zhulenev // Evaluate the numerator polynomial p.
532a54f4eaeSMogball Value p = builder.create<math::FmaOp>(x2, alpha13, alpha11);
533a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha9);
534a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha7);
535a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha5);
536a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha3);
537a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha1);
538a54f4eaeSMogball p = builder.create<arith::MulFOp>(x, p);
539f99ccf65SEugene Zhulenev
540f99ccf65SEugene Zhulenev // Evaluate the denominator polynomial q.
541a54f4eaeSMogball Value q = builder.create<math::FmaOp>(x2, beta6, beta4);
542a54f4eaeSMogball q = builder.create<math::FmaOp>(x2, q, beta2);
543a54f4eaeSMogball q = builder.create<math::FmaOp>(x2, q, beta0);
544f99ccf65SEugene Zhulenev
545f99ccf65SEugene Zhulenev // Divide the numerator by the denominator.
546dec8af70SRiver Riddle Value res = builder.create<arith::SelectOp>(
547dec8af70SRiver Riddle tinyMask, x, builder.create<arith::DivFOp>(p, q));
548f99ccf65SEugene Zhulenev
549f99ccf65SEugene Zhulenev rewriter.replaceOp(op, res);
550f99ccf65SEugene Zhulenev
551f99ccf65SEugene Zhulenev return success();
552f99ccf65SEugene Zhulenev }
553f99ccf65SEugene Zhulenev
554ea7f211bSAhmed Taei #define LN2_VALUE \
555ea7f211bSAhmed Taei 0.693147180559945309417232121458176568075500134360255254120680009493393621L
556c0891706SEmilio Cota #define LOG2E_VALUE \
557ea7f211bSAhmed Taei 1.442695040888963407359924681001892137426645954152985934135449406931109219L
558ea7f211bSAhmed Taei
559f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
560c0891706SEmilio Cota // LogOp and Log2Op approximation.
561ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
562ce976d2dSEugene Zhulenev
563ce976d2dSEugene Zhulenev namespace {
564c0891706SEmilio Cota template <typename Op>
565c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> {
566c0891706SEmilio Cota using OpRewritePattern<Op>::OpRewritePattern;
567ce976d2dSEugene Zhulenev
568c0891706SEmilio Cota /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise.
569c0891706SEmilio Cota LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter,
570c0891706SEmilio Cota bool base2) const;
571ce976d2dSEugene Zhulenev };
572ce976d2dSEugene Zhulenev } // namespace
573ce976d2dSEugene Zhulenev
574c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library.
575c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath
576c0891706SEmilio Cota template <typename Op>
577ce976d2dSEugene Zhulenev LogicalResult
logMatchAndRewrite(Op op,PatternRewriter & rewriter,bool base2) const578c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter,
579c0891706SEmilio Cota bool base2) const {
58062fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
581ce976d2dSEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type");
582ce976d2dSEugene Zhulenev
58362fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
584ec32d540SEugene Zhulenev
585ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
586ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value {
587ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
588ce976d2dSEugene Zhulenev };
589ce976d2dSEugene Zhulenev
590ce976d2dSEugene Zhulenev Value cstZero = bcast(f32Cst(builder, 0.0f));
591ce976d2dSEugene Zhulenev Value cstOne = bcast(f32Cst(builder, 1.0f));
592ce976d2dSEugene Zhulenev Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
593ce976d2dSEugene Zhulenev
594ce976d2dSEugene Zhulenev // The smallest non denormalized float number.
595ce976d2dSEugene Zhulenev Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
596ce976d2dSEugene Zhulenev Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
597ce976d2dSEugene Zhulenev Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
598ce976d2dSEugene Zhulenev Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
599ce976d2dSEugene Zhulenev
600ce976d2dSEugene Zhulenev // Polynomial coefficients.
601ce976d2dSEugene Zhulenev Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
602ce976d2dSEugene Zhulenev Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
603ce976d2dSEugene Zhulenev Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
604ce976d2dSEugene Zhulenev Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
605ce976d2dSEugene Zhulenev Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
606ce976d2dSEugene Zhulenev Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
607ce976d2dSEugene Zhulenev Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
608ce976d2dSEugene Zhulenev Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
609ce976d2dSEugene Zhulenev Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
610ce976d2dSEugene Zhulenev Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
611ce976d2dSEugene Zhulenev
61262fea88bSJacques Pienaar Value x = op.getOperand();
613ce976d2dSEugene Zhulenev
614ce976d2dSEugene Zhulenev // Truncate input values to the minimum positive normal.
615ce976d2dSEugene Zhulenev x = max(builder, x, cstMinNormPos);
616ce976d2dSEugene Zhulenev
617ce976d2dSEugene Zhulenev // Extract significant in the range [0.5,1) and exponent.
618ced8690dSMehdi Amini std::pair<Value, Value> pair = frexp(builder, x, /*isPositive=*/true);
619ce976d2dSEugene Zhulenev x = pair.first;
620ce976d2dSEugene Zhulenev Value e = pair.second;
621ce976d2dSEugene Zhulenev
622ce976d2dSEugene Zhulenev // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
623ce976d2dSEugene Zhulenev // by -1.0. The values are then centered around 0, which improves the
624ce976d2dSEugene Zhulenev // stability of the polynomial evaluation:
625ce976d2dSEugene Zhulenev //
626ce976d2dSEugene Zhulenev // if( x < SQRTHF ) {
627ce976d2dSEugene Zhulenev // e -= 1;
628ce976d2dSEugene Zhulenev // x = x + x - 1.0;
629ce976d2dSEugene Zhulenev // } else { x = x - 1.0; }
630a54f4eaeSMogball Value mask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x,
631a54f4eaeSMogball cstCephesSQRTHF);
632dec8af70SRiver Riddle Value tmp = builder.create<arith::SelectOp>(mask, x, cstZero);
633ce976d2dSEugene Zhulenev
634a54f4eaeSMogball x = builder.create<arith::SubFOp>(x, cstOne);
635a54f4eaeSMogball e = builder.create<arith::SubFOp>(
636dec8af70SRiver Riddle e, builder.create<arith::SelectOp>(mask, cstOne, cstZero));
637a54f4eaeSMogball x = builder.create<arith::AddFOp>(x, tmp);
638ce976d2dSEugene Zhulenev
639a54f4eaeSMogball Value x2 = builder.create<arith::MulFOp>(x, x);
640a54f4eaeSMogball Value x3 = builder.create<arith::MulFOp>(x2, x);
641ce976d2dSEugene Zhulenev
642ce976d2dSEugene Zhulenev // Evaluate the polynomial approximant of degree 8 in three parts.
643ce976d2dSEugene Zhulenev Value y0, y1, y2;
644a54f4eaeSMogball y0 = builder.create<math::FmaOp>(cstCephesLogP0, x, cstCephesLogP1);
645a54f4eaeSMogball y1 = builder.create<math::FmaOp>(cstCephesLogP3, x, cstCephesLogP4);
646a54f4eaeSMogball y2 = builder.create<math::FmaOp>(cstCephesLogP6, x, cstCephesLogP7);
647a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x, cstCephesLogP2);
648a54f4eaeSMogball y1 = builder.create<math::FmaOp>(y1, x, cstCephesLogP5);
649a54f4eaeSMogball y2 = builder.create<math::FmaOp>(y2, x, cstCephesLogP8);
650a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x3, y1);
651a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x3, y2);
652a54f4eaeSMogball y0 = builder.create<arith::MulFOp>(y0, x3);
653ce976d2dSEugene Zhulenev
654a54f4eaeSMogball y0 = builder.create<math::FmaOp>(cstNegHalf, x2, y0);
655a54f4eaeSMogball x = builder.create<arith::AddFOp>(x, y0);
656ce976d2dSEugene Zhulenev
657c0891706SEmilio Cota if (base2) {
658c0891706SEmilio Cota Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
659a54f4eaeSMogball x = builder.create<math::FmaOp>(x, cstLog2e, e);
660c0891706SEmilio Cota } else {
661ce976d2dSEugene Zhulenev Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
662a54f4eaeSMogball x = builder.create<math::FmaOp>(e, cstLn2, x);
663c0891706SEmilio Cota }
664ce976d2dSEugene Zhulenev
665a54f4eaeSMogball Value invalidMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT,
66662fea88bSJacques Pienaar op.getOperand(), cstZero);
667a54f4eaeSMogball Value zeroMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
66862fea88bSJacques Pienaar op.getOperand(), cstZero);
669a54f4eaeSMogball Value posInfMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
67062fea88bSJacques Pienaar op.getOperand(), cstPosInf);
671ce976d2dSEugene Zhulenev
672ce976d2dSEugene Zhulenev // Filter out invalid values:
673ce976d2dSEugene Zhulenev // • x == 0 -> -INF
674ce976d2dSEugene Zhulenev // • x < 0 -> NAN
675ce976d2dSEugene Zhulenev // • x == +INF -> +INF
676dec8af70SRiver Riddle Value aproximation = builder.create<arith::SelectOp>(
677ce976d2dSEugene Zhulenev zeroMask, cstMinusInf,
678dec8af70SRiver Riddle builder.create<arith::SelectOp>(
679ce976d2dSEugene Zhulenev invalidMask, cstNan,
680dec8af70SRiver Riddle builder.create<arith::SelectOp>(posInfMask, cstPosInf, x)));
681ce976d2dSEugene Zhulenev
682ce976d2dSEugene Zhulenev rewriter.replaceOp(op, aproximation);
683ce976d2dSEugene Zhulenev
684ce976d2dSEugene Zhulenev return success();
685ce976d2dSEugene Zhulenev }
686ce976d2dSEugene Zhulenev
687c0891706SEmilio Cota namespace {
688c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> {
689c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase;
690c0891706SEmilio Cota
matchAndRewrite__anond27a14240b11::LogApproximation691c0891706SEmilio Cota LogicalResult matchAndRewrite(math::LogOp op,
692c0891706SEmilio Cota PatternRewriter &rewriter) const final {
693c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/false);
694c0891706SEmilio Cota }
695c0891706SEmilio Cota };
696c0891706SEmilio Cota } // namespace
697c0891706SEmilio Cota
698c0891706SEmilio Cota namespace {
699c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
700c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase;
701c0891706SEmilio Cota
matchAndRewrite__anond27a14240c11::Log2Approximation702c0891706SEmilio Cota LogicalResult matchAndRewrite(math::Log2Op op,
703c0891706SEmilio Cota PatternRewriter &rewriter) const final {
704c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/true);
705c0891706SEmilio Cota }
706c0891706SEmilio Cota };
707c0891706SEmilio Cota } // namespace
708c0891706SEmilio Cota
709ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
7101c0374e7SEmilio Cota // Log1p approximation.
7111c0374e7SEmilio Cota //----------------------------------------------------------------------------//
7121c0374e7SEmilio Cota
7131c0374e7SEmilio Cota namespace {
7141c0374e7SEmilio Cota struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> {
7151c0374e7SEmilio Cota public:
7161c0374e7SEmilio Cota using OpRewritePattern::OpRewritePattern;
7171c0374e7SEmilio Cota
7181c0374e7SEmilio Cota LogicalResult matchAndRewrite(math::Log1pOp op,
7191c0374e7SEmilio Cota PatternRewriter &rewriter) const final;
7201c0374e7SEmilio Cota };
7211c0374e7SEmilio Cota } // namespace
7221c0374e7SEmilio Cota
7231c0374e7SEmilio Cota // Approximate log(1+x).
7241c0374e7SEmilio Cota LogicalResult
matchAndRewrite(math::Log1pOp op,PatternRewriter & rewriter) const7251c0374e7SEmilio Cota Log1pApproximation::matchAndRewrite(math::Log1pOp op,
7261c0374e7SEmilio Cota PatternRewriter &rewriter) const {
72762fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
7281c0374e7SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type");
7291c0374e7SEmilio Cota
73062fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
731ec32d540SEugene Zhulenev
7321c0374e7SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
7331c0374e7SEmilio Cota auto bcast = [&](Value value) -> Value {
734ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
7351c0374e7SEmilio Cota };
7361c0374e7SEmilio Cota
7371c0374e7SEmilio Cota // Approximate log(1+x) using the following, due to W. Kahan:
7381c0374e7SEmilio Cota // u = x + 1.0;
7391c0374e7SEmilio Cota // if (u == 1.0 || u == inf) return x;
7401c0374e7SEmilio Cota // return x * log(u) / (u - 1.0);
7411c0374e7SEmilio Cota // ^^^^^^^^^^^^^^^^^^^^^^
7421c0374e7SEmilio Cota // "logLarge" below.
7431c0374e7SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f));
74462fea88bSJacques Pienaar Value x = op.getOperand();
745a54f4eaeSMogball Value u = builder.create<arith::AddFOp>(x, cstOne);
746a54f4eaeSMogball Value uSmall =
747a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
7481c0374e7SEmilio Cota Value logU = builder.create<math::LogOp>(u);
749a54f4eaeSMogball Value uInf =
750a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, logU);
751a54f4eaeSMogball Value logLarge = builder.create<arith::MulFOp>(
752a54f4eaeSMogball x, builder.create<arith::DivFOp>(
753a54f4eaeSMogball logU, builder.create<arith::SubFOp>(u, cstOne)));
754dec8af70SRiver Riddle Value approximation = builder.create<arith::SelectOp>(
755a54f4eaeSMogball builder.create<arith::OrIOp>(uSmall, uInf), x, logLarge);
7561c0374e7SEmilio Cota rewriter.replaceOp(op, approximation);
7571c0374e7SEmilio Cota return success();
7581c0374e7SEmilio Cota }
7591c0374e7SEmilio Cota
7601c0374e7SEmilio Cota //----------------------------------------------------------------------------//
761f1b92218SBoian Petkantchin // Erf approximation.
762f1b92218SBoian Petkantchin //----------------------------------------------------------------------------//
763f1b92218SBoian Petkantchin
764f1b92218SBoian Petkantchin // Approximates erf(x) with
765f1b92218SBoian Petkantchin // a - P(x)/Q(x)
766f1b92218SBoian Petkantchin // where P and Q are polynomials of degree 4.
767f1b92218SBoian Petkantchin // Different coefficients are chosen based on the value of x.
768f1b92218SBoian Petkantchin // The approximation error is ~2.5e-07.
769f1b92218SBoian Petkantchin // Boost's minimax tool that utilizes the Remez method was used to find the
770f1b92218SBoian Petkantchin // coefficients.
771f1b92218SBoian Petkantchin LogicalResult
matchAndRewrite(math::ErfOp op,PatternRewriter & rewriter) const772f1b92218SBoian Petkantchin ErfPolynomialApproximation::matchAndRewrite(math::ErfOp op,
773f1b92218SBoian Petkantchin PatternRewriter &rewriter) const {
77462fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
775f1b92218SBoian Petkantchin return rewriter.notifyMatchFailure(op, "unsupported operand type");
776f1b92218SBoian Petkantchin
77762fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
778ec32d540SEugene Zhulenev
779f1b92218SBoian Petkantchin ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
780f1b92218SBoian Petkantchin auto bcast = [&](Value value) -> Value {
781ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
782f1b92218SBoian Petkantchin };
783f1b92218SBoian Petkantchin
784f1b92218SBoian Petkantchin const int intervalsCount = 3;
785f1b92218SBoian Petkantchin const int polyDegree = 4;
786f1b92218SBoian Petkantchin
787f1b92218SBoian Petkantchin Value zero = bcast(f32Cst(builder, 0));
788f1b92218SBoian Petkantchin Value one = bcast(f32Cst(builder, 1));
789f1b92218SBoian Petkantchin Value pp[intervalsCount][polyDegree + 1];
7907d79a257SAlexander Belyaev pp[0][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f));
7917d79a257SAlexander Belyaev pp[0][1] = bcast(f32Cst(builder, +1.12837916222975858e+00f));
7927d79a257SAlexander Belyaev pp[0][2] = bcast(f32Cst(builder, -5.23018562988006470e-01f));
7937d79a257SAlexander Belyaev pp[0][3] = bcast(f32Cst(builder, +2.09741709609267072e-01f));
7947d79a257SAlexander Belyaev pp[0][4] = bcast(f32Cst(builder, +2.58146801602987875e-02f));
7957d79a257SAlexander Belyaev pp[1][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f));
7967d79a257SAlexander Belyaev pp[1][1] = bcast(f32Cst(builder, +1.12750687816789140e+00f));
7977d79a257SAlexander Belyaev pp[1][2] = bcast(f32Cst(builder, -3.64721408487825775e-01f));
7987d79a257SAlexander Belyaev pp[1][3] = bcast(f32Cst(builder, +1.18407396425136952e-01f));
7997d79a257SAlexander Belyaev pp[1][4] = bcast(f32Cst(builder, +3.70645533056476558e-02f));
8007d79a257SAlexander Belyaev pp[2][0] = bcast(f32Cst(builder, -3.30093071049483172e-03f));
8017d79a257SAlexander Belyaev pp[2][1] = bcast(f32Cst(builder, +3.51961938357697011e-03f));
8027d79a257SAlexander Belyaev pp[2][2] = bcast(f32Cst(builder, -1.41373622814988039e-03f));
8037d79a257SAlexander Belyaev pp[2][3] = bcast(f32Cst(builder, +2.53447094961941348e-04f));
8047d79a257SAlexander Belyaev pp[2][4] = bcast(f32Cst(builder, -1.71048029455037401e-05f));
805f1b92218SBoian Petkantchin
806f1b92218SBoian Petkantchin Value qq[intervalsCount][polyDegree + 1];
8077d79a257SAlexander Belyaev qq[0][0] = bcast(f32Cst(builder, +1.000000000000000000e+00f));
8087d79a257SAlexander Belyaev qq[0][1] = bcast(f32Cst(builder, -4.635138185962547255e-01f));
8097d79a257SAlexander Belyaev qq[0][2] = bcast(f32Cst(builder, +5.192301327279782447e-01f));
8107d79a257SAlexander Belyaev qq[0][3] = bcast(f32Cst(builder, -1.318089722204810087e-01f));
8117d79a257SAlexander Belyaev qq[0][4] = bcast(f32Cst(builder, +7.397964654672315005e-02f));
8127d79a257SAlexander Belyaev qq[1][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f));
8137d79a257SAlexander Belyaev qq[1][1] = bcast(f32Cst(builder, -3.27607011824493086e-01f));
8147d79a257SAlexander Belyaev qq[1][2] = bcast(f32Cst(builder, +4.48369090658821977e-01f));
8157d79a257SAlexander Belyaev qq[1][3] = bcast(f32Cst(builder, -8.83462621207857930e-02f));
8167d79a257SAlexander Belyaev qq[1][4] = bcast(f32Cst(builder, +5.72442770283176093e-02f));
8177d79a257SAlexander Belyaev qq[2][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f));
8187d79a257SAlexander Belyaev qq[2][1] = bcast(f32Cst(builder, -2.06069165953913769e+00f));
8197d79a257SAlexander Belyaev qq[2][2] = bcast(f32Cst(builder, +1.62705939945477759e+00f));
8207d79a257SAlexander Belyaev qq[2][3] = bcast(f32Cst(builder, -5.83389859211130017e-01f));
8217d79a257SAlexander Belyaev qq[2][4] = bcast(f32Cst(builder, +8.21908939856640930e-02f));
822f1b92218SBoian Petkantchin
823f1b92218SBoian Petkantchin Value offsets[intervalsCount];
8247d79a257SAlexander Belyaev offsets[0] = bcast(f32Cst(builder, 0.0f));
8257d79a257SAlexander Belyaev offsets[1] = bcast(f32Cst(builder, 0.0f));
8267d79a257SAlexander Belyaev offsets[2] = bcast(f32Cst(builder, 1.0f));
827f1b92218SBoian Petkantchin
828f1b92218SBoian Petkantchin Value bounds[intervalsCount];
8297d79a257SAlexander Belyaev bounds[0] = bcast(f32Cst(builder, 0.8f));
8307d79a257SAlexander Belyaev bounds[1] = bcast(f32Cst(builder, 2.0f));
8317d79a257SAlexander Belyaev bounds[2] = bcast(f32Cst(builder, 3.75f));
832f1b92218SBoian Petkantchin
833f1b92218SBoian Petkantchin Value isNegativeArg = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT,
83462fea88bSJacques Pienaar op.getOperand(), zero);
83562fea88bSJacques Pienaar Value negArg = builder.create<arith::NegFOp>(op.getOperand());
836dec8af70SRiver Riddle Value x =
837dec8af70SRiver Riddle builder.create<arith::SelectOp>(isNegativeArg, negArg, op.getOperand());
838f1b92218SBoian Petkantchin
839f1b92218SBoian Petkantchin Value offset = offsets[0];
840f1b92218SBoian Petkantchin Value p[polyDegree + 1];
841f1b92218SBoian Petkantchin Value q[polyDegree + 1];
842f1b92218SBoian Petkantchin for (int i = 0; i <= polyDegree; ++i) {
843f1b92218SBoian Petkantchin p[i] = pp[0][i];
844f1b92218SBoian Petkantchin q[i] = qq[0][i];
845f1b92218SBoian Petkantchin }
846f1b92218SBoian Petkantchin
847f1b92218SBoian Petkantchin // TODO: maybe use vector stacking to reduce the number of selects.
848f1b92218SBoian Petkantchin Value isLessThanBound[intervalsCount];
849f1b92218SBoian Petkantchin for (int j = 0; j < intervalsCount - 1; ++j) {
850f1b92218SBoian Petkantchin isLessThanBound[j] =
851f1b92218SBoian Petkantchin builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x, bounds[j]);
852f1b92218SBoian Petkantchin for (int i = 0; i <= polyDegree; ++i) {
853dec8af70SRiver Riddle p[i] = builder.create<arith::SelectOp>(isLessThanBound[j], p[i],
854dec8af70SRiver Riddle pp[j + 1][i]);
855dec8af70SRiver Riddle q[i] = builder.create<arith::SelectOp>(isLessThanBound[j], q[i],
856dec8af70SRiver Riddle qq[j + 1][i]);
857f1b92218SBoian Petkantchin }
858dec8af70SRiver Riddle offset = builder.create<arith::SelectOp>(isLessThanBound[j], offset,
859dec8af70SRiver Riddle offsets[j + 1]);
860f1b92218SBoian Petkantchin }
861f1b92218SBoian Petkantchin isLessThanBound[intervalsCount - 1] = builder.create<arith::CmpFOp>(
862f1b92218SBoian Petkantchin arith::CmpFPredicate::ULT, x, bounds[intervalsCount - 1]);
863f1b92218SBoian Petkantchin
864f1b92218SBoian Petkantchin Value pPoly = makePolynomialCalculation(builder, p, x);
865f1b92218SBoian Petkantchin Value qPoly = makePolynomialCalculation(builder, q, x);
866f1b92218SBoian Petkantchin Value rationalPoly = builder.create<arith::DivFOp>(pPoly, qPoly);
867f1b92218SBoian Petkantchin Value formula = builder.create<arith::AddFOp>(offset, rationalPoly);
868dec8af70SRiver Riddle formula = builder.create<arith::SelectOp>(isLessThanBound[intervalsCount - 1],
869f1b92218SBoian Petkantchin formula, one);
870f1b92218SBoian Petkantchin
871f1b92218SBoian Petkantchin // erf is odd function: erf(x) = -erf(-x).
872f1b92218SBoian Petkantchin Value negFormula = builder.create<arith::NegFOp>(formula);
873dec8af70SRiver Riddle Value res =
874dec8af70SRiver Riddle builder.create<arith::SelectOp>(isNegativeArg, negFormula, formula);
875f1b92218SBoian Petkantchin
876f1b92218SBoian Petkantchin rewriter.replaceOp(op, res);
877f1b92218SBoian Petkantchin
878f1b92218SBoian Petkantchin return success();
879f1b92218SBoian Petkantchin }
880f1b92218SBoian Petkantchin
881f1b92218SBoian Petkantchin //----------------------------------------------------------------------------//
882ea7f211bSAhmed Taei // Exp approximation.
883ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
884ea7f211bSAhmed Taei
885ea7f211bSAhmed Taei namespace {
886ea7f211bSAhmed Taei
887ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
888ea7f211bSAhmed Taei public:
889ea7f211bSAhmed Taei using OpRewritePattern::OpRewritePattern;
890ea7f211bSAhmed Taei
891ea7f211bSAhmed Taei LogicalResult matchAndRewrite(math::ExpOp op,
892ea7f211bSAhmed Taei PatternRewriter &rewriter) const final;
893ea7f211bSAhmed Taei };
894ea7f211bSAhmed Taei } // namespace
895ea7f211bSAhmed Taei
896ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range
897ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
898ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y).
899ea7f211bSAhmed Taei LogicalResult
matchAndRewrite(math::ExpOp op,PatternRewriter & rewriter) const900ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op,
901ea7f211bSAhmed Taei PatternRewriter &rewriter) const {
90262fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
903ea7f211bSAhmed Taei return rewriter.notifyMatchFailure(op, "unsupported operand type");
904ec32d540SEugene Zhulenev
90562fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
906ec32d540SEugene Zhulenev
907ea7f211bSAhmed Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
908ea7f211bSAhmed Taei
909ea7f211bSAhmed Taei // TODO: Consider a common pattern rewriter with all methods below to
910ea7f211bSAhmed Taei // write the approximations.
911ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value {
912ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
913ea7f211bSAhmed Taei };
914ea7f211bSAhmed Taei auto fmla = [&](Value a, Value b, Value c) {
915a54f4eaeSMogball return builder.create<math::FmaOp>(a, b, c);
916ea7f211bSAhmed Taei };
917ea7f211bSAhmed Taei auto mul = [&](Value a, Value b) -> Value {
918a54f4eaeSMogball return builder.create<arith::MulFOp>(a, b);
919ea7f211bSAhmed Taei };
920ea7f211bSAhmed Taei auto sub = [&](Value a, Value b) -> Value {
921a54f4eaeSMogball return builder.create<arith::SubFOp>(a, b);
922ea7f211bSAhmed Taei };
923a54f4eaeSMogball auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
924ea7f211bSAhmed Taei
925ea7f211bSAhmed Taei Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
926c0891706SEmilio Cota Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
927ea7f211bSAhmed Taei
928ea7f211bSAhmed Taei // Polynomial coefficients.
929ea7f211bSAhmed Taei Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
930ea7f211bSAhmed Taei Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
931ea7f211bSAhmed Taei Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
932ea7f211bSAhmed Taei Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
933ea7f211bSAhmed Taei Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
934ea7f211bSAhmed Taei Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
935ea7f211bSAhmed Taei
93662fea88bSJacques Pienaar Value x = op.getOperand();
937ea7f211bSAhmed Taei
938b122cbebSAdrian Kuegel Value isNan = builder.create<arith::CmpFOp>(arith::CmpFPredicate::UNO, x, x);
939b122cbebSAdrian Kuegel
940ea7f211bSAhmed Taei // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
941c0891706SEmilio Cota Value xL2Inv = mul(x, cstLog2E);
942ea7f211bSAhmed Taei Value kF32 = floor(xL2Inv);
943ea7f211bSAhmed Taei Value kLn2 = mul(kF32, cstLn2);
944ea7f211bSAhmed Taei Value y = sub(x, kLn2);
945ea7f211bSAhmed Taei
946ea7f211bSAhmed Taei // Use Estrin's evaluation scheme with 3 independent parts:
947ea7f211bSAhmed Taei // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
948ea7f211bSAhmed Taei Value y2 = mul(y, y);
949ea7f211bSAhmed Taei Value y4 = mul(y2, y2);
950ea7f211bSAhmed Taei
951ea7f211bSAhmed Taei Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
952ea7f211bSAhmed Taei Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
953ea7f211bSAhmed Taei Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
954ea7f211bSAhmed Taei Value expY = fmla(q1, y2, q0);
955ea7f211bSAhmed Taei expY = fmla(q2, y4, expY);
956ea7f211bSAhmed Taei
957ec32d540SEugene Zhulenev auto i32Vec = broadcast(builder.getI32Type(), shape);
958ea7f211bSAhmed Taei
959ea7f211bSAhmed Taei // exp2(k)
9603c69bc4dSRiver Riddle Value k = builder.create<arith::FPToSIOp>(i32Vec, kF32);
961ea7f211bSAhmed Taei Value exp2KValue = exp2I32(builder, k);
962ea7f211bSAhmed Taei
963ea7f211bSAhmed Taei // exp(x) = exp(y) * exp2(k)
964ea7f211bSAhmed Taei expY = mul(expY, exp2KValue);
965ea7f211bSAhmed Taei
966ea7f211bSAhmed Taei // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
967ea7f211bSAhmed Taei // partitioned as the following:
968ea7f211bSAhmed Taei // exp(x) = 0, x <= -inf
969ea7f211bSAhmed Taei // exp(x) = underflow (min_float), x <= -88
970ea7f211bSAhmed Taei // exp(x) = inf (min_float), x >= 88
971ea7f211bSAhmed Taei // Note: |k| = 127 is the value where the 8-bits exponent saturates.
972ea7f211bSAhmed Taei Value zerof32Const = bcast(f32Cst(builder, 0));
973ea7f211bSAhmed Taei auto constPosInfinity =
974ea7f211bSAhmed Taei bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
975ea7f211bSAhmed Taei auto constNegIfinity =
976ea7f211bSAhmed Taei bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
977ea7f211bSAhmed Taei auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
978ea7f211bSAhmed Taei
979ea7f211bSAhmed Taei Value kMaxConst = bcast(i32Cst(builder, 127));
980ea7f211bSAhmed Taei Value kMaxNegConst = bcast(i32Cst(builder, -127));
981a54f4eaeSMogball Value rightBound =
982a54f4eaeSMogball builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, k, kMaxConst);
983a54f4eaeSMogball Value leftBound =
984a54f4eaeSMogball builder.create<arith::CmpIOp>(arith::CmpIPredicate::sge, k, kMaxNegConst);
985ea7f211bSAhmed Taei
986a54f4eaeSMogball Value isNegInfinityX = builder.create<arith::CmpFOp>(
987a54f4eaeSMogball arith::CmpFPredicate::OEQ, x, constNegIfinity);
98821f9e4a1SAhmed Taei Value isPosInfinityX = builder.create<arith::CmpFOp>(
98921f9e4a1SAhmed Taei arith::CmpFPredicate::OEQ, x, constPosInfinity);
990ea7f211bSAhmed Taei Value isPostiveX =
991a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zerof32Const);
992a54f4eaeSMogball Value isComputable = builder.create<arith::AndIOp>(rightBound, leftBound);
993ea7f211bSAhmed Taei
994dec8af70SRiver Riddle expY = builder.create<arith::SelectOp>(
995b122cbebSAdrian Kuegel isNan, x,
996b122cbebSAdrian Kuegel builder.create<arith::SelectOp>(
99721f9e4a1SAhmed Taei isNegInfinityX, zerof32Const,
998dec8af70SRiver Riddle builder.create<arith::SelectOp>(
99921f9e4a1SAhmed Taei isPosInfinityX, constPosInfinity,
1000dec8af70SRiver Riddle builder.create<arith::SelectOp>(
1001dec8af70SRiver Riddle isComputable, expY,
1002dec8af70SRiver Riddle builder.create<arith::SelectOp>(isPostiveX, constPosInfinity,
1003b122cbebSAdrian Kuegel underflow)))));
1004ea7f211bSAhmed Taei
1005ea7f211bSAhmed Taei rewriter.replaceOp(op, expY);
1006ea7f211bSAhmed Taei
1007ea7f211bSAhmed Taei return success();
1008ea7f211bSAhmed Taei }
1009ea7f211bSAhmed Taei
1010ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
10110edc4bc8SEmilio Cota // ExpM1 approximation.
10120edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
10130edc4bc8SEmilio Cota
10140edc4bc8SEmilio Cota namespace {
10150edc4bc8SEmilio Cota
10160edc4bc8SEmilio Cota struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> {
10170edc4bc8SEmilio Cota public:
10180edc4bc8SEmilio Cota using OpRewritePattern::OpRewritePattern;
10190edc4bc8SEmilio Cota
10200edc4bc8SEmilio Cota LogicalResult matchAndRewrite(math::ExpM1Op op,
10210edc4bc8SEmilio Cota PatternRewriter &rewriter) const final;
10220edc4bc8SEmilio Cota };
10230edc4bc8SEmilio Cota } // namespace
10240edc4bc8SEmilio Cota
10250edc4bc8SEmilio Cota LogicalResult
matchAndRewrite(math::ExpM1Op op,PatternRewriter & rewriter) const10260edc4bc8SEmilio Cota ExpM1Approximation::matchAndRewrite(math::ExpM1Op op,
10270edc4bc8SEmilio Cota PatternRewriter &rewriter) const {
102862fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
10290edc4bc8SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type");
10300edc4bc8SEmilio Cota
103162fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1032ec32d540SEugene Zhulenev
10330edc4bc8SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
10340edc4bc8SEmilio Cota auto bcast = [&](Value value) -> Value {
1035ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
10360edc4bc8SEmilio Cota };
10370edc4bc8SEmilio Cota
10380edc4bc8SEmilio Cota // expm1(x) = exp(x) - 1 = u - 1.
10390edc4bc8SEmilio Cota // We have to handle it carefully when x is near 0, i.e. u ~= 1,
10400edc4bc8SEmilio Cota // and when the input is ~= -inf, i.e. u - 1 ~= -1.
10410edc4bc8SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f));
10420edc4bc8SEmilio Cota Value cstNegOne = bcast(f32Cst(builder, -1.0f));
104362fea88bSJacques Pienaar Value x = op.getOperand();
10440edc4bc8SEmilio Cota Value u = builder.create<math::ExpOp>(x);
104587de451bSAdrian Kuegel Value uEqOneOrNaN =
104687de451bSAdrian Kuegel builder.create<arith::CmpFOp>(arith::CmpFPredicate::UEQ, u, cstOne);
1047a54f4eaeSMogball Value uMinusOne = builder.create<arith::SubFOp>(u, cstOne);
1048a54f4eaeSMogball Value uMinusOneEqNegOne = builder.create<arith::CmpFOp>(
1049a54f4eaeSMogball arith::CmpFPredicate::OEQ, uMinusOne, cstNegOne);
10500edc4bc8SEmilio Cota // logU = log(u) ~= x
10510edc4bc8SEmilio Cota Value logU = builder.create<math::LogOp>(u);
10520edc4bc8SEmilio Cota
10530edc4bc8SEmilio Cota // Detect exp(x) = +inf; written this way to avoid having to form +inf.
1054a54f4eaeSMogball Value isInf =
1055a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, logU, u);
10560edc4bc8SEmilio Cota
10570edc4bc8SEmilio Cota // (u - 1) * (x / ~x)
1058a54f4eaeSMogball Value expm1 = builder.create<arith::MulFOp>(
1059a54f4eaeSMogball uMinusOne, builder.create<arith::DivFOp>(x, logU));
1060dec8af70SRiver Riddle expm1 = builder.create<arith::SelectOp>(isInf, u, expm1);
1061dec8af70SRiver Riddle Value approximation = builder.create<arith::SelectOp>(
106287de451bSAdrian Kuegel uEqOneOrNaN, x,
1063dec8af70SRiver Riddle builder.create<arith::SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1));
10640edc4bc8SEmilio Cota rewriter.replaceOp(op, approximation);
10650edc4bc8SEmilio Cota return success();
10660edc4bc8SEmilio Cota }
10670edc4bc8SEmilio Cota
10680edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
10697e2d672aSAhmed S. Taei // Sin and Cos approximation.
10707e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
10717e2d672aSAhmed S. Taei
10727e2d672aSAhmed S. Taei namespace {
10737e2d672aSAhmed S. Taei
10747e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
10757e2d672aSAhmed S. Taei struct SinAndCosApproximation : public OpRewritePattern<OpTy> {
10767e2d672aSAhmed S. Taei public:
10777e2d672aSAhmed S. Taei using OpRewritePattern<OpTy>::OpRewritePattern;
10787e2d672aSAhmed S. Taei
10797e2d672aSAhmed S. Taei LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final;
10807e2d672aSAhmed S. Taei };
10817e2d672aSAhmed S. Taei } // namespace
10827e2d672aSAhmed S. Taei
10837e2d672aSAhmed S. Taei #define TWO_OVER_PI \
10847e2d672aSAhmed S. Taei 0.6366197723675813430755350534900574481378385829618257949906693762L
10857e2d672aSAhmed S. Taei #define PI_OVER_2 \
10867e2d672aSAhmed S. Taei 1.5707963267948966192313216916397514420985846996875529104874722961L
10877e2d672aSAhmed S. Taei
10887e2d672aSAhmed S. Taei // Approximates sin(x) or cos(x) by finding the best approximation polynomial in
10897e2d672aSAhmed S. Taei // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the
10907e2d672aSAhmed S. Taei // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y).
10917e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
matchAndRewrite(OpTy op,PatternRewriter & rewriter) const10927e2d672aSAhmed S. Taei LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite(
10937e2d672aSAhmed S. Taei OpTy op, PatternRewriter &rewriter) const {
10947e2d672aSAhmed S. Taei static_assert(
10957e2d672aSAhmed S. Taei llvm::is_one_of<OpTy, math::SinOp, math::CosOp>::value,
10967e2d672aSAhmed S. Taei "SinAndCosApproximation pattern expects math::SinOp or math::CosOp");
1097ec32d540SEugene Zhulenev
109862fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
10997e2d672aSAhmed S. Taei return rewriter.notifyMatchFailure(op, "unsupported operand type");
11007e2d672aSAhmed S. Taei
110162fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1102ec32d540SEugene Zhulenev
11037e2d672aSAhmed S. Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
11047e2d672aSAhmed S. Taei auto bcast = [&](Value value) -> Value {
1105ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
11067e2d672aSAhmed S. Taei };
11077e2d672aSAhmed S. Taei auto mul = [&](Value a, Value b) -> Value {
1108a54f4eaeSMogball return builder.create<arith::MulFOp>(a, b);
11097e2d672aSAhmed S. Taei };
11107e2d672aSAhmed S. Taei auto sub = [&](Value a, Value b) -> Value {
1111a54f4eaeSMogball return builder.create<arith::SubFOp>(a, b);
11127e2d672aSAhmed S. Taei };
1113a54f4eaeSMogball auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
11147e2d672aSAhmed S. Taei
1115ec32d540SEugene Zhulenev auto i32Vec = broadcast(builder.getI32Type(), shape);
11167e2d672aSAhmed S. Taei auto fPToSingedInteger = [&](Value a) -> Value {
11173c69bc4dSRiver Riddle return builder.create<arith::FPToSIOp>(i32Vec, a);
11187e2d672aSAhmed S. Taei };
11197e2d672aSAhmed S. Taei
11207e2d672aSAhmed S. Taei auto modulo4 = [&](Value a) -> Value {
1121a54f4eaeSMogball return builder.create<arith::AndIOp>(a, bcast(i32Cst(builder, 3)));
11227e2d672aSAhmed S. Taei };
11237e2d672aSAhmed S. Taei
11247e2d672aSAhmed S. Taei auto isEqualTo = [&](Value a, Value b) -> Value {
1125a54f4eaeSMogball return builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, a, b);
11267e2d672aSAhmed S. Taei };
11277e2d672aSAhmed S. Taei
11287e2d672aSAhmed S. Taei auto isGreaterThan = [&](Value a, Value b) -> Value {
1129a54f4eaeSMogball return builder.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, a, b);
11307e2d672aSAhmed S. Taei };
11317e2d672aSAhmed S. Taei
11327e2d672aSAhmed S. Taei auto select = [&](Value cond, Value t, Value f) -> Value {
1133dec8af70SRiver Riddle return builder.create<arith::SelectOp>(cond, t, f);
11347e2d672aSAhmed S. Taei };
11357e2d672aSAhmed S. Taei
11367e2d672aSAhmed S. Taei auto fmla = [&](Value a, Value b, Value c) {
1137a54f4eaeSMogball return builder.create<math::FmaOp>(a, b, c);
11387e2d672aSAhmed S. Taei };
11397e2d672aSAhmed S. Taei
1140a54f4eaeSMogball auto bitwiseOr = [&](Value a, Value b) {
1141a54f4eaeSMogball return builder.create<arith::OrIOp>(a, b);
1142a54f4eaeSMogball };
11437e2d672aSAhmed S. Taei
1144dc3b9365SAlexandre Ganea Value twoOverPi = bcast(f32Cst(builder, (float)TWO_OVER_PI));
1145dc3b9365SAlexandre Ganea Value piOverTwo = bcast(f32Cst(builder, (float)PI_OVER_2));
11467e2d672aSAhmed S. Taei
114762fea88bSJacques Pienaar Value x = op.getOperand();
11487e2d672aSAhmed S. Taei
11497e2d672aSAhmed S. Taei Value k = floor(mul(x, twoOverPi));
11507e2d672aSAhmed S. Taei
11517e2d672aSAhmed S. Taei Value y = sub(x, mul(k, piOverTwo));
11527e2d672aSAhmed S. Taei
11537e2d672aSAhmed S. Taei Value cstOne = bcast(f32Cst(builder, 1.0));
11547e2d672aSAhmed S. Taei Value cstNegativeOne = bcast(f32Cst(builder, -1.0));
11557e2d672aSAhmed S. Taei
11567e2d672aSAhmed S. Taei Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f));
11577e2d672aSAhmed S. Taei Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f));
11587e2d672aSAhmed S. Taei Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f));
11597e2d672aSAhmed S. Taei Value cstSC8 =
11607e2d672aSAhmed S. Taei bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f));
11617e2d672aSAhmed S. Taei Value cstSC10 =
11627e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f));
11637e2d672aSAhmed S. Taei
11647e2d672aSAhmed S. Taei Value cstCC2 = bcast(f32Cst(builder, -0.5f));
11657e2d672aSAhmed S. Taei Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f));
11667e2d672aSAhmed S. Taei Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f));
11677e2d672aSAhmed S. Taei Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f));
11687e2d672aSAhmed S. Taei Value cstCC10 =
11697e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f));
11707e2d672aSAhmed S. Taei
11717e2d672aSAhmed S. Taei Value kMod4 = modulo4(fPToSingedInteger(k));
11727e2d672aSAhmed S. Taei
11737e2d672aSAhmed S. Taei Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0)));
11747e2d672aSAhmed S. Taei Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1)));
11757e2d672aSAhmed S. Taei Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2)));
11767e2d672aSAhmed S. Taei Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3)));
11777e2d672aSAhmed S. Taei
11787e2d672aSAhmed S. Taei Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2);
11797e2d672aSAhmed S. Taei Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1)))
11807e2d672aSAhmed S. Taei : bitwiseOr(kR1, kR2);
11817e2d672aSAhmed S. Taei
11827e2d672aSAhmed S. Taei Value y2 = mul(y, y);
11837e2d672aSAhmed S. Taei
11847e2d672aSAhmed S. Taei Value base = select(sinuseCos, cstOne, y);
11857e2d672aSAhmed S. Taei Value cstC2 = select(sinuseCos, cstCC2, cstSC2);
11867e2d672aSAhmed S. Taei Value cstC4 = select(sinuseCos, cstCC4, cstSC4);
11877e2d672aSAhmed S. Taei Value cstC6 = select(sinuseCos, cstCC6, cstSC6);
11887e2d672aSAhmed S. Taei Value cstC8 = select(sinuseCos, cstCC8, cstSC8);
11897e2d672aSAhmed S. Taei Value cstC10 = select(sinuseCos, cstCC10, cstSC10);
11907e2d672aSAhmed S. Taei
11917e2d672aSAhmed S. Taei Value v1 = fmla(y2, cstC10, cstC8);
11927e2d672aSAhmed S. Taei Value v2 = fmla(y2, v1, cstC6);
11937e2d672aSAhmed S. Taei Value v3 = fmla(y2, v2, cstC4);
11947e2d672aSAhmed S. Taei Value v4 = fmla(y2, v3, cstC2);
11957e2d672aSAhmed S. Taei Value v5 = fmla(y2, v4, cstOne);
11967e2d672aSAhmed S. Taei Value v6 = mul(base, v5);
11977e2d672aSAhmed S. Taei
11987e2d672aSAhmed S. Taei Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6);
11997e2d672aSAhmed S. Taei
12007e2d672aSAhmed S. Taei rewriter.replaceOp(op, approximation);
12017e2d672aSAhmed S. Taei
12027e2d672aSAhmed S. Taei return success();
12037e2d672aSAhmed S. Taei }
12047e2d672aSAhmed S. Taei
12057e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
120635553d45SEmilio Cota // Rsqrt approximation.
120735553d45SEmilio Cota //----------------------------------------------------------------------------//
120835553d45SEmilio Cota
120935553d45SEmilio Cota namespace {
121035553d45SEmilio Cota struct RsqrtApproximation : public OpRewritePattern<math::RsqrtOp> {
121135553d45SEmilio Cota using OpRewritePattern::OpRewritePattern;
121235553d45SEmilio Cota
121335553d45SEmilio Cota LogicalResult matchAndRewrite(math::RsqrtOp op,
121435553d45SEmilio Cota PatternRewriter &rewriter) const final;
121535553d45SEmilio Cota };
121635553d45SEmilio Cota } // namespace
121735553d45SEmilio Cota
121835553d45SEmilio Cota LogicalResult
matchAndRewrite(math::RsqrtOp op,PatternRewriter & rewriter) const121935553d45SEmilio Cota RsqrtApproximation::matchAndRewrite(math::RsqrtOp op,
122035553d45SEmilio Cota PatternRewriter &rewriter) const {
122162fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32())
1222ec32d540SEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type");
1223ec32d540SEugene Zhulenev
122462fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1225ec32d540SEugene Zhulenev
122635553d45SEmilio Cota // Only support already-vectorized rsqrt's.
1227ec32d540SEugene Zhulenev if (shape.empty() || shape.back() % 8 != 0)
122835553d45SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type");
122935553d45SEmilio Cota
123035553d45SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
123135553d45SEmilio Cota auto bcast = [&](Value value) -> Value {
1232ec32d540SEugene Zhulenev return broadcast(builder, value, shape);
123335553d45SEmilio Cota };
123435553d45SEmilio Cota
123535553d45SEmilio Cota Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
123635553d45SEmilio Cota Value cstOnePointFive = bcast(f32Cst(builder, 1.5f));
123735553d45SEmilio Cota Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
123835553d45SEmilio Cota Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
123935553d45SEmilio Cota
124062fea88bSJacques Pienaar Value negHalf = builder.create<arith::MulFOp>(op.getOperand(), cstNegHalf);
124135553d45SEmilio Cota
124235553d45SEmilio Cota // Select only the inverse sqrt of positive normals (denormals are
124335553d45SEmilio Cota // flushed to zero).
124462fea88bSJacques Pienaar Value ltMinMask = builder.create<arith::CmpFOp>(
124562fea88bSJacques Pienaar arith::CmpFPredicate::OLT, op.getOperand(), cstMinNormPos);
124635553d45SEmilio Cota Value infMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
124762fea88bSJacques Pienaar op.getOperand(), cstPosInf);
124835553d45SEmilio Cota Value notNormalFiniteMask = builder.create<arith::OrIOp>(ltMinMask, infMask);
124935553d45SEmilio Cota
125035553d45SEmilio Cota // Compute an approximate result.
1251627fa0b9SEugene Zhulenev Value yApprox = handleMultidimensionalVectors(
1252627fa0b9SEugene Zhulenev builder, op->getOperands(), 8, [&builder](ValueRange operands) -> Value {
1253627fa0b9SEugene Zhulenev return builder.create<x86vector::RsqrtOp>(operands);
1254627fa0b9SEugene Zhulenev });
125535553d45SEmilio Cota
125635553d45SEmilio Cota // Do a single step of Newton-Raphson iteration to improve the approximation.
125735553d45SEmilio Cota // This uses the formula y_{n+1} = y_n * (1.5 - y_n * (0.5 * x) * y_n).
125835553d45SEmilio Cota // It is essential to evaluate the inner term like this because forming
125935553d45SEmilio Cota // y_n^2 may over- or underflow.
126035553d45SEmilio Cota Value inner = builder.create<arith::MulFOp>(negHalf, yApprox);
126135553d45SEmilio Cota Value fma = builder.create<math::FmaOp>(yApprox, inner, cstOnePointFive);
126235553d45SEmilio Cota Value yNewton = builder.create<arith::MulFOp>(yApprox, fma);
126335553d45SEmilio Cota
126435553d45SEmilio Cota // Select the result of the Newton-Raphson step for positive normal arguments.
126535553d45SEmilio Cota // For other arguments, choose the output of the intrinsic. This will
126635553d45SEmilio Cota // return rsqrt(+inf) = 0, rsqrt(x) = NaN if x < 0, and rsqrt(x) = +inf if
126735553d45SEmilio Cota // x is zero or a positive denormalized float (equivalent to flushing positive
126835553d45SEmilio Cota // denormalized inputs to zero).
1269dec8af70SRiver Riddle Value res =
1270dec8af70SRiver Riddle builder.create<arith::SelectOp>(notNormalFiniteMask, yApprox, yNewton);
127135553d45SEmilio Cota rewriter.replaceOp(op, res);
127235553d45SEmilio Cota
127335553d45SEmilio Cota return success();
127435553d45SEmilio Cota }
127535553d45SEmilio Cota
127635553d45SEmilio Cota //----------------------------------------------------------------------------//
1277f99ccf65SEugene Zhulenev
populateMathPolynomialApproximationPatterns(RewritePatternSet & patterns,const MathPolynomialApproximationOptions & options)1278f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns(
127935553d45SEmilio Cota RewritePatternSet &patterns,
128035553d45SEmilio Cota const MathPolynomialApproximationOptions &options) {
12812f9f9afaSRob Suderman patterns.add<AtanApproximation, Atan2Approximation, TanhApproximation,
12822f9f9afaSRob Suderman LogApproximation, Log2Approximation, Log1pApproximation,
12832f9f9afaSRob Suderman ErfPolynomialApproximation, ExpApproximation, ExpM1Approximation,
1284bbddd19eSJacques Pienaar ReuseF32Expansion<math::Atan2Op>,
12852f9f9afaSRob Suderman SinAndCosApproximation<true, math::SinOp>,
12867e2d672aSAhmed S. Taei SinAndCosApproximation<false, math::CosOp>>(
12870edc4bc8SEmilio Cota patterns.getContext());
128835553d45SEmilio Cota if (options.enableAvx2)
128935553d45SEmilio Cota patterns.add<RsqrtApproximation>(patterns.getContext());
1290f99ccf65SEugene Zhulenev }
1291