MLIR  16.0.0git
PolynomialApproximation.cpp
Go to the documentation of this file.
1 //===- PolynomialApproximation.cpp - Approximate math operations ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements expansion of math operations to fast approximations
10 // that do not rely on any of the library functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include <climits>
15 #include <cstddef>
16 
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/BuiltinTypes.h"
28 #include "mlir/IR/OpDefinition.h"
29 #include "mlir/IR/PatternMatch.h"
30 #include "mlir/IR/TypeUtilities.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/STLExtras.h"
35 
36 using namespace mlir;
37 using namespace mlir::math;
38 using namespace mlir::vector;
39 
40 // Returns vector shape if the type is a vector. Returns an empty shape if it is
41 // not a vector.
43  auto vectorType = type.dyn_cast<VectorType>();
44  return vectorType ? vectorType.getShape() : ArrayRef<int64_t>();
45 }
46 
48  return vectorShape(value.getType());
49 }
50 
51 //----------------------------------------------------------------------------//
52 // Broadcast scalar types and values into vector types and values.
53 //----------------------------------------------------------------------------//
54 
55 // Broadcasts scalar type into vector type (iff shape is non-scalar).
56 static Type broadcast(Type type, ArrayRef<int64_t> shape) {
57  assert(!type.isa<VectorType>() && "must be scalar type");
58  return !shape.empty() ? VectorType::get(shape, type) : type;
59 }
60 
61 // Broadcasts scalar value into vector (iff shape is non-scalar).
63  ArrayRef<int64_t> shape) {
64  assert(!value.getType().isa<VectorType>() && "must be scalar value");
65  auto type = broadcast(value.getType(), shape);
66  return !shape.empty() ? builder.create<BroadcastOp>(type, value) : value;
67 }
68 
69 //----------------------------------------------------------------------------//
70 // Helper function to handle n-D vectors with 1-D operations.
71 //----------------------------------------------------------------------------//
72 
73 // Expands and unrolls n-D vector operands into multiple fixed size 1-D vectors
74 // and calls the compute function with 1-D vector operands. Stitches back all
75 // results into the original n-D vector result.
76 //
77 // Examples: vectorWidth = 8
78 // - vector<4x8xf32> unrolled 4 times
79 // - vector<16xf32> expanded to vector<2x8xf32> and unrolled 2 times
80 // - vector<4x16xf32> expanded to vector<4x2x8xf32> and unrolled 4*2 times
81 //
82 // Some math approximations rely on ISA-specific operations that only accept
83 // fixed size 1-D vectors (e.g. AVX expects vectors of width 8).
84 //
85 // It is the caller's responsibility to verify that the inner dimension is
86 // divisible by the vectorWidth, and that all operands have the same vector
87 // shape.
88 static Value
90  ValueRange operands, int64_t vectorWidth,
92  assert(!operands.empty() && "operands must be not empty");
93  assert(vectorWidth > 0 && "vector width must be larger than 0");
94 
95  VectorType inputType = operands[0].getType().cast<VectorType>();
96  ArrayRef<int64_t> inputShape = inputType.getShape();
97 
98  // If input shape matches target vector width, we can just call the
99  // user-provided compute function with the operands.
100  if (inputShape == llvm::makeArrayRef(vectorWidth))
101  return compute(operands);
102 
103  // Check if the inner dimension has to be expanded, or we can directly iterate
104  // over the outer dimensions of the vector.
105  int64_t innerDim = inputShape.back();
106  int64_t expansionDim = innerDim / vectorWidth;
107  assert((innerDim % vectorWidth == 0) && "invalid inner dimension size");
108 
109  // Maybe expand operands to the higher rank vector shape that we'll use to
110  // iterate over and extract one dimensional vectors.
111  SmallVector<int64_t> expandedShape(inputShape.begin(), inputShape.end());
112  SmallVector<Value> expandedOperands(operands);
113 
114  if (expansionDim > 1) {
115  // Expand shape from [..., innerDim] to [..., expansionDim, vectorWidth].
116  expandedShape.insert(expandedShape.end() - 1, expansionDim);
117  expandedShape.back() = vectorWidth;
118 
119  for (unsigned i = 0; i < operands.size(); ++i) {
120  auto operand = operands[i];
121  auto eltType = operand.getType().cast<VectorType>().getElementType();
122  auto expandedType = VectorType::get(expandedShape, eltType);
123  expandedOperands[i] =
124  builder.create<vector::ShapeCastOp>(expandedType, operand);
125  }
126  }
127 
128  // Iterate over all outer dimensions of the compute shape vector type.
129  auto iterationDims = ArrayRef<int64_t>(expandedShape).drop_back();
130  int64_t maxIndex = computeMaxLinearIndex(iterationDims);
131  auto strides = computeStrides(iterationDims);
132 
133  // Compute results for each one dimensional vector.
134  SmallVector<Value> results(maxIndex);
135 
136  for (int64_t i = 0; i < maxIndex; ++i) {
137  auto offsets = delinearize(strides, i);
138 
139  SmallVector<Value> extracted(expandedOperands.size());
140  for (const auto &tuple : llvm::enumerate(expandedOperands))
141  extracted[tuple.index()] =
142  builder.create<vector::ExtractOp>(tuple.value(), offsets);
143 
144  results[i] = compute(extracted);
145  }
146 
147  // Stitch results together into one large vector.
148  Type resultEltType = results[0].getType().cast<VectorType>().getElementType();
149  Type resultExpandedType = VectorType::get(expandedShape, resultEltType);
150  Value result = builder.create<arith::ConstantOp>(
151  resultExpandedType, builder.getZeroAttr(resultExpandedType));
152 
153  for (int64_t i = 0; i < maxIndex; ++i)
154  result = builder.create<vector::InsertOp>(results[i], result,
155  delinearize(strides, i));
156 
157  // Reshape back to the original vector shape.
158  return builder.create<vector::ShapeCastOp>(
159  VectorType::get(inputShape, resultEltType), result);
160 }
161 
162 //----------------------------------------------------------------------------//
163 // Helper functions to create constants.
164 //----------------------------------------------------------------------------//
165 
166 static Value floatCst(ImplicitLocOpBuilder &builder, float value,
167  Type elementType) {
168  assert((elementType.isF16() || elementType.isF32()) &&
169  "x must be f16 or f32 type.");
170  return builder.create<arith::ConstantOp>(
171  builder.getFloatAttr(elementType, value));
172 }
173 
174 static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
175  return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value));
176 }
177 
178 static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
179  return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value));
180 }
181 
182 static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
183  Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
184  return builder.create<arith::BitcastOp>(builder.getF32Type(), i32Value);
185 }
186 
187 //----------------------------------------------------------------------------//
188 // Helper functions to build math functions approximations.
189 //----------------------------------------------------------------------------//
190 
191 // Return the minimum of the two values or NaN if value is NaN
192 static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound) {
193  return builder.create<arith::SelectOp>(
194  builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT, value, bound),
195  value, bound);
196 }
197 
198 // Return the maximum of the two values or NaN if value is NaN
199 static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound) {
200  return builder.create<arith::SelectOp>(
201  builder.create<arith::CmpFOp>(arith::CmpFPredicate::UGT, value, bound),
202  value, bound);
203 }
204 
205 // Return the clamped value or NaN if value is NaN
206 static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
207  Value upperBound) {
208  return max(builder, min(builder, value, upperBound), lowerBound);
209 }
210 
211 // Decomposes given floating point value `arg` into a normalized fraction and
212 // an integral power of two (see std::frexp). Returned values have float type.
213 static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
214  bool isPositive = false) {
215  assert(getElementTypeOrSelf(arg).isF32() && "arg must be f32 type");
216  ArrayRef<int64_t> shape = vectorShape(arg);
217 
218  auto bcast = [&](Value value) -> Value {
219  return broadcast(builder, value, shape);
220  };
221 
222  auto i32 = builder.getIntegerType(32);
223  auto i32Vec = broadcast(i32, shape);
224  auto f32Vec = broadcast(builder.getF32Type(), shape);
225 
226  Value cst126f = f32Cst(builder, 126.0f);
227  Value cstHalf = f32Cst(builder, 0.5f);
228  Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
229 
230  // Bitcast to i32 for bitwise operations.
231  Value i32Half = builder.create<arith::BitcastOp>(i32, cstHalf);
232  Value i32InvMantMask = builder.create<arith::BitcastOp>(i32, cstInvMantMask);
233  Value i32Arg = builder.create<arith::BitcastOp>(i32Vec, arg);
234 
235  // Compute normalized fraction.
236  Value tmp0 = builder.create<arith::AndIOp>(i32Arg, bcast(i32InvMantMask));
237  Value tmp1 = builder.create<arith::OrIOp>(tmp0, bcast(i32Half));
238  Value normalizedFraction = builder.create<arith::BitcastOp>(f32Vec, tmp1);
239 
240  // Compute exponent.
241  Value arg0 = isPositive ? arg : builder.create<math::AbsFOp>(arg);
242  Value biasedExponentBits = builder.create<arith::ShRUIOp>(
243  builder.create<arith::BitcastOp>(i32Vec, arg0),
244  bcast(i32Cst(builder, 23)));
245  Value biasedExponent =
246  builder.create<arith::SIToFPOp>(f32Vec, biasedExponentBits);
247  Value exponent =
248  builder.create<arith::SubFOp>(biasedExponent, bcast(cst126f));
249 
250  return {normalizedFraction, exponent};
251 }
252 
253 // Computes exp2 for an i32 argument.
254 static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
255  assert(getElementTypeOrSelf(arg).isInteger(32) && "arg must be i32 type");
256  ArrayRef<int64_t> shape = vectorShape(arg);
257 
258  auto bcast = [&](Value value) -> Value {
259  return broadcast(builder, value, shape);
260  };
261 
262  auto f32Vec = broadcast(builder.getF32Type(), shape);
263  // The exponent of f32 located at 23-bit.
264  auto exponetBitLocation = bcast(i32Cst(builder, 23));
265  // Set the exponent bias to zero.
266  auto bias = bcast(i32Cst(builder, 127));
267 
268  Value biasedArg = builder.create<arith::AddIOp>(arg, bias);
269  Value exp2ValueInt =
270  builder.create<arith::ShLIOp>(biasedArg, exponetBitLocation);
271  Value exp2ValueF32 = builder.create<arith::BitcastOp>(f32Vec, exp2ValueInt);
272 
273  return exp2ValueF32;
274 }
275 
276 namespace {
277 Value makePolynomialCalculation(ImplicitLocOpBuilder &builder,
278  llvm::ArrayRef<Value> coeffs, Value x) {
279  Type elementType = getElementTypeOrSelf(x);
280  assert((elementType.isF32() || elementType.isF16()) &&
281  "x must be f32 or f16 type");
282  ArrayRef<int64_t> shape = vectorShape(x);
283 
284  if (coeffs.empty())
285  return broadcast(builder, floatCst(builder, 0.0f, elementType), shape);
286 
287  if (coeffs.size() == 1)
288  return coeffs[0];
289 
290  Value res = builder.create<math::FmaOp>(x, coeffs[coeffs.size() - 1],
291  coeffs[coeffs.size() - 2]);
292  for (auto i = ptrdiff_t(coeffs.size()) - 3; i >= 0; --i) {
293  res = builder.create<math::FmaOp>(x, res, coeffs[i]);
294  }
295  return res;
296 }
297 } // namespace
298 
299 //----------------------------------------------------------------------------//
300 // Helper function/pattern to insert casts for reusing F32 bit expansion.
301 //----------------------------------------------------------------------------//
302 
303 template <typename T>
305  // Conservatively only allow where the operand and result types are exactly 1.
306  Type origType = op->getResultTypes().front();
307  for (Type t : llvm::drop_begin(op->getResultTypes()))
308  if (origType != t)
309  return rewriter.notifyMatchFailure(op, "required all types to match");
310  for (Type t : op->getOperandTypes())
311  if (origType != t)
312  return rewriter.notifyMatchFailure(op, "required all types to match");
313 
314  // Skip if already F32 or larger than 32 bits.
315  if (getElementTypeOrSelf(origType).isF32() ||
316  getElementTypeOrSelf(origType).getIntOrFloatBitWidth() > 32)
317  return failure();
318 
319  // Create F32 equivalent type.
320  Type newType;
321  if (auto shaped = origType.dyn_cast<ShapedType>()) {
322  newType = shaped.clone(rewriter.getF32Type());
323  } else if (origType.isa<FloatType>()) {
324  newType = rewriter.getF32Type();
325  } else {
326  return rewriter.notifyMatchFailure(op,
327  "unable to find F32 equivalent type");
328  }
329 
330  Location loc = op->getLoc();
331  SmallVector<Value> operands;
332  for (auto operand : op->getOperands())
333  operands.push_back(rewriter.create<arith::ExtFOp>(loc, newType, operand));
334  auto result = rewriter.create<math::Atan2Op>(loc, newType, operands);
335  rewriter.replaceOpWithNewOp<arith::TruncFOp>(op, origType, result);
336  return success();
337 }
338 
339 namespace {
340 // Pattern to cast to F32 to reuse F32 expansion as fallback for single-result
341 // op.
342 // TODO: Consider revising to avoid adding multiple casts for a subgraph that is
343 // all in lower precision. Currently this is only fallback support and performs
344 // simplistic casting.
345 template <typename T>
346 struct ReuseF32Expansion : public OpRewritePattern<T> {
347 public:
349  LogicalResult matchAndRewrite(T op, PatternRewriter &rewriter) const final {
350  static_assert(
351  T::template hasTrait<mlir::OpTrait::SameOperandsAndResultType>(),
352  "requires same operands and result types");
353  return insertCasts<T>(op, rewriter);
354  }
355 };
356 } // namespace
357 
358 //----------------------------------------------------------------------------//
359 // AtanOp approximation.
360 //----------------------------------------------------------------------------//
361 
362 namespace {
363 struct AtanApproximation : public OpRewritePattern<math::AtanOp> {
364 public:
366 
367  LogicalResult matchAndRewrite(math::AtanOp op,
368  PatternRewriter &rewriter) const final;
369 };
370 } // namespace
371 
373 AtanApproximation::matchAndRewrite(math::AtanOp op,
374  PatternRewriter &rewriter) const {
375  auto operand = op.getOperand();
376  if (!getElementTypeOrSelf(operand).isF32())
377  return rewriter.notifyMatchFailure(op, "unsupported operand type");
378 
379  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
380 
381  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
382  auto one = broadcast(builder, f32Cst(builder, 1.0f), shape);
383 
384  // Remap the problem over [0.0, 1.0] by looking at the absolute value and the
385  // handling symmetry.
386  Value abs = builder.create<math::AbsFOp>(operand);
387  Value reciprocal = builder.create<arith::DivFOp>(one, abs);
388  Value compare =
389  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, abs, reciprocal);
390  Value x = builder.create<arith::SelectOp>(compare, abs, reciprocal);
391 
392  // Perform the Taylor series approximation for atan over the range
393  // [-1.0, 1.0].
394  auto n1 = broadcast(builder, f32Cst(builder, 0.14418283f), shape);
395  auto n2 = broadcast(builder, f32Cst(builder, -0.34999234f), shape);
396  auto n3 = broadcast(builder, f32Cst(builder, -0.01067831f), shape);
397  auto n4 = broadcast(builder, f32Cst(builder, 1.00209986f), shape);
398 
399  Value p = builder.create<math::FmaOp>(x, n1, n2);
400  p = builder.create<math::FmaOp>(x, p, n3);
401  p = builder.create<math::FmaOp>(x, p, n4);
402  p = builder.create<arith::MulFOp>(x, p);
403 
404  // Remap the solution for over [0.0, 1.0] to [0.0, inf]
405  auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape);
406  Value sub = builder.create<arith::SubFOp>(halfPi, p);
407  Value select = builder.create<arith::SelectOp>(compare, p, sub);
408 
409  // Correct for signing of the input.
410  rewriter.replaceOpWithNewOp<math::CopySignOp>(op, select, operand);
411  return success();
412 }
413 
414 //----------------------------------------------------------------------------//
415 // AtanOp approximation.
416 //----------------------------------------------------------------------------//
417 
418 namespace {
419 struct Atan2Approximation : public OpRewritePattern<math::Atan2Op> {
420 public:
422 
423  LogicalResult matchAndRewrite(math::Atan2Op op,
424  PatternRewriter &rewriter) const final;
425 };
426 } // namespace
427 
429 Atan2Approximation::matchAndRewrite(math::Atan2Op op,
430  PatternRewriter &rewriter) const {
431  auto y = op.getOperand(0);
432  auto x = op.getOperand(1);
433  if (!getElementTypeOrSelf(x).isF32())
434  return rewriter.notifyMatchFailure(op, "unsupported operand type");
435 
436  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
437  ArrayRef<int64_t> shape = vectorShape(op.getResult());
438 
439  // Compute atan in the valid range.
440  auto div = builder.create<arith::DivFOp>(y, x);
441  auto atan = builder.create<math::AtanOp>(div);
442 
443  // Determine what the atan would be for a 180 degree rotation.
444  auto zero = broadcast(builder, f32Cst(builder, 0.0f), shape);
445  auto pi = broadcast(builder, f32Cst(builder, 3.14159265359f), shape);
446  auto addPi = builder.create<arith::AddFOp>(atan, pi);
447  auto subPi = builder.create<arith::SubFOp>(atan, pi);
448  auto atanGt =
449  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, atan, zero);
450  auto flippedAtan = builder.create<arith::SelectOp>(atanGt, subPi, addPi);
451 
452  // Determine whether to directly use atan or use the 180 degree flip
453  auto xGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zero);
454  Value result = builder.create<arith::SelectOp>(xGt, atan, flippedAtan);
455 
456  // Handle x = 0, y > 0
457  Value xZero =
458  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, x, zero);
459  Value yGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, y, zero);
460  Value isHalfPi = builder.create<arith::AndIOp>(xZero, yGt);
461  auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape);
462  result = builder.create<arith::SelectOp>(isHalfPi, halfPi, result);
463 
464  // Handle x = 0, y < 0
465  Value yLt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, y, zero);
466  Value isNegativeHalfPiPi = builder.create<arith::AndIOp>(xZero, yLt);
467  auto negativeHalfPiPi =
468  broadcast(builder, f32Cst(builder, -1.57079632679f), shape);
469  result = builder.create<arith::SelectOp>(isNegativeHalfPiPi, negativeHalfPiPi,
470  result);
471 
472  // Handle x = 0, y = 0;
473  Value yZero =
474  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, y, zero);
475  Value isNan = builder.create<arith::AndIOp>(xZero, yZero);
476  Value cstNan = broadcast(builder, f32FromBits(builder, 0x7fc00000), shape);
477  result = builder.create<arith::SelectOp>(isNan, cstNan, result);
478 
479  rewriter.replaceOp(op, result);
480  return success();
481 }
482 
483 //----------------------------------------------------------------------------//
484 // TanhOp approximation.
485 //----------------------------------------------------------------------------//
486 
487 namespace {
488 struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
489 public:
491 
492  LogicalResult matchAndRewrite(math::TanhOp op,
493  PatternRewriter &rewriter) const final;
494 };
495 } // namespace
496 
498 TanhApproximation::matchAndRewrite(math::TanhOp op,
499  PatternRewriter &rewriter) const {
500  if (!getElementTypeOrSelf(op.getOperand()).isF32())
501  return rewriter.notifyMatchFailure(op, "unsupported operand type");
502 
503  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
504 
505  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
506  auto bcast = [&](Value value) -> Value {
507  return broadcast(builder, value, shape);
508  };
509 
510  // Clamp operand into [plusClamp, minusClamp] range.
511  Value minusClamp = bcast(f32Cst(builder, -7.99881172180175781f));
512  Value plusClamp = bcast(f32Cst(builder, 7.99881172180175781f));
513  Value x = clamp(builder, op.getOperand(), minusClamp, plusClamp);
514 
515  // Mask for tiny values that are approximated with `operand`.
516  Value tiny = bcast(f32Cst(builder, 0.0004f));
517  Value tinyMask = builder.create<arith::CmpFOp>(
518  arith::CmpFPredicate::OLT, builder.create<math::AbsFOp>(op.getOperand()),
519  tiny);
520 
521  // The monomial coefficients of the numerator polynomial (odd).
522  Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
523  Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
524  Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
525  Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
526  Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
527  Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
528  Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
529 
530  // The monomial coefficients of the denominator polynomial (even).
531  Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
532  Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
533  Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
534  Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
535 
536  // Since the polynomials are odd/even, we need x^2.
537  Value x2 = builder.create<arith::MulFOp>(x, x);
538 
539  // Evaluate the numerator polynomial p.
540  Value p = builder.create<math::FmaOp>(x2, alpha13, alpha11);
541  p = builder.create<math::FmaOp>(x2, p, alpha9);
542  p = builder.create<math::FmaOp>(x2, p, alpha7);
543  p = builder.create<math::FmaOp>(x2, p, alpha5);
544  p = builder.create<math::FmaOp>(x2, p, alpha3);
545  p = builder.create<math::FmaOp>(x2, p, alpha1);
546  p = builder.create<arith::MulFOp>(x, p);
547 
548  // Evaluate the denominator polynomial q.
549  Value q = builder.create<math::FmaOp>(x2, beta6, beta4);
550  q = builder.create<math::FmaOp>(x2, q, beta2);
551  q = builder.create<math::FmaOp>(x2, q, beta0);
552 
553  // Divide the numerator by the denominator.
554  Value res = builder.create<arith::SelectOp>(
555  tinyMask, x, builder.create<arith::DivFOp>(p, q));
556 
557  rewriter.replaceOp(op, res);
558 
559  return success();
560 }
561 
562 #define LN2_VALUE \
563  0.693147180559945309417232121458176568075500134360255254120680009493393621L
564 #define LOG2E_VALUE \
565  1.442695040888963407359924681001892137426645954152985934135449406931109219L
566 
567 //----------------------------------------------------------------------------//
568 // LogOp and Log2Op approximation.
569 //----------------------------------------------------------------------------//
570 
571 namespace {
572 template <typename Op>
573 struct LogApproximationBase : public OpRewritePattern<Op> {
575 
576  /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise.
577  LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter,
578  bool base2) const;
579 };
580 } // namespace
581 
582 // This approximation comes from Julien Pommier's SSE math library.
583 // Link: http://gruntthepeon.free.fr/ssemath
584 template <typename Op>
586 LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter,
587  bool base2) const {
588  if (!getElementTypeOrSelf(op.getOperand()).isF32())
589  return rewriter.notifyMatchFailure(op, "unsupported operand type");
590 
591  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
592 
593  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
594  auto bcast = [&](Value value) -> Value {
595  return broadcast(builder, value, shape);
596  };
597 
598  Value cstZero = bcast(f32Cst(builder, 0.0f));
599  Value cstOne = bcast(f32Cst(builder, 1.0f));
600  Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
601 
602  // The smallest non denormalized float number.
603  Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
604  Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
605  Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
606  Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
607 
608  // Polynomial coefficients.
609  Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
610  Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
611  Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
612  Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
613  Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
614  Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
615  Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
616  Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
617  Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
618  Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
619 
620  Value x = op.getOperand();
621 
622  // Truncate input values to the minimum positive normal.
623  x = max(builder, x, cstMinNormPos);
624 
625  // Extract significant in the range [0.5,1) and exponent.
626  std::pair<Value, Value> pair = frexp(builder, x, /*isPositive=*/true);
627  x = pair.first;
628  Value e = pair.second;
629 
630  // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
631  // by -1.0. The values are then centered around 0, which improves the
632  // stability of the polynomial evaluation:
633  //
634  // if( x < SQRTHF ) {
635  // e -= 1;
636  // x = x + x - 1.0;
637  // } else { x = x - 1.0; }
638  Value mask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x,
639  cstCephesSQRTHF);
640  Value tmp = builder.create<arith::SelectOp>(mask, x, cstZero);
641 
642  x = builder.create<arith::SubFOp>(x, cstOne);
643  e = builder.create<arith::SubFOp>(
644  e, builder.create<arith::SelectOp>(mask, cstOne, cstZero));
645  x = builder.create<arith::AddFOp>(x, tmp);
646 
647  Value x2 = builder.create<arith::MulFOp>(x, x);
648  Value x3 = builder.create<arith::MulFOp>(x2, x);
649 
650  // Evaluate the polynomial approximant of degree 8 in three parts.
651  Value y0, y1, y2;
652  y0 = builder.create<math::FmaOp>(cstCephesLogP0, x, cstCephesLogP1);
653  y1 = builder.create<math::FmaOp>(cstCephesLogP3, x, cstCephesLogP4);
654  y2 = builder.create<math::FmaOp>(cstCephesLogP6, x, cstCephesLogP7);
655  y0 = builder.create<math::FmaOp>(y0, x, cstCephesLogP2);
656  y1 = builder.create<math::FmaOp>(y1, x, cstCephesLogP5);
657  y2 = builder.create<math::FmaOp>(y2, x, cstCephesLogP8);
658  y0 = builder.create<math::FmaOp>(y0, x3, y1);
659  y0 = builder.create<math::FmaOp>(y0, x3, y2);
660  y0 = builder.create<arith::MulFOp>(y0, x3);
661 
662  y0 = builder.create<math::FmaOp>(cstNegHalf, x2, y0);
663  x = builder.create<arith::AddFOp>(x, y0);
664 
665  if (base2) {
666  Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
667  x = builder.create<math::FmaOp>(x, cstLog2e, e);
668  } else {
669  Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
670  x = builder.create<math::FmaOp>(e, cstLn2, x);
671  }
672 
673  Value invalidMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT,
674  op.getOperand(), cstZero);
675  Value zeroMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
676  op.getOperand(), cstZero);
677  Value posInfMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
678  op.getOperand(), cstPosInf);
679 
680  // Filter out invalid values:
681  // • x == 0 -> -INF
682  // • x < 0 -> NAN
683  // • x == +INF -> +INF
684  Value aproximation = builder.create<arith::SelectOp>(
685  zeroMask, cstMinusInf,
686  builder.create<arith::SelectOp>(
687  invalidMask, cstNan,
688  builder.create<arith::SelectOp>(posInfMask, cstPosInf, x)));
689 
690  rewriter.replaceOp(op, aproximation);
691 
692  return success();
693 }
694 
695 namespace {
696 struct LogApproximation : public LogApproximationBase<math::LogOp> {
697  using LogApproximationBase::LogApproximationBase;
698 
699  LogicalResult matchAndRewrite(math::LogOp op,
700  PatternRewriter &rewriter) const final {
701  return logMatchAndRewrite(op, rewriter, /*base2=*/false);
702  }
703 };
704 } // namespace
705 
706 namespace {
707 struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
708  using LogApproximationBase::LogApproximationBase;
709 
710  LogicalResult matchAndRewrite(math::Log2Op op,
711  PatternRewriter &rewriter) const final {
712  return logMatchAndRewrite(op, rewriter, /*base2=*/true);
713  }
714 };
715 } // namespace
716 
717 //----------------------------------------------------------------------------//
718 // Log1p approximation.
719 //----------------------------------------------------------------------------//
720 
721 namespace {
722 struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> {
723 public:
725 
726  LogicalResult matchAndRewrite(math::Log1pOp op,
727  PatternRewriter &rewriter) const final;
728 };
729 } // namespace
730 
731 // Approximate log(1+x).
733 Log1pApproximation::matchAndRewrite(math::Log1pOp op,
734  PatternRewriter &rewriter) const {
735  if (!getElementTypeOrSelf(op.getOperand()).isF32())
736  return rewriter.notifyMatchFailure(op, "unsupported operand type");
737 
738  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
739 
740  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
741  auto bcast = [&](Value value) -> Value {
742  return broadcast(builder, value, shape);
743  };
744 
745  // Approximate log(1+x) using the following, due to W. Kahan:
746  // u = x + 1.0;
747  // if (u == 1.0 || u == inf) return x;
748  // return x * log(u) / (u - 1.0);
749  // ^^^^^^^^^^^^^^^^^^^^^^
750  // "logLarge" below.
751  Value cstOne = bcast(f32Cst(builder, 1.0f));
752  Value x = op.getOperand();
753  Value u = builder.create<arith::AddFOp>(x, cstOne);
754  Value uSmall =
755  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
756  Value logU = builder.create<math::LogOp>(u);
757  Value uInf =
758  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, logU);
759  Value logLarge = builder.create<arith::MulFOp>(
760  x, builder.create<arith::DivFOp>(
761  logU, builder.create<arith::SubFOp>(u, cstOne)));
762  Value approximation = builder.create<arith::SelectOp>(
763  builder.create<arith::OrIOp>(uSmall, uInf), x, logLarge);
764  rewriter.replaceOp(op, approximation);
765  return success();
766 }
767 
768 //----------------------------------------------------------------------------//
769 // Erf approximation.
770 //----------------------------------------------------------------------------//
771 
772 // Approximates erf(x) with
773 // a - P(x)/Q(x)
774 // where P and Q are polynomials of degree 4.
775 // Different coefficients are chosen based on the value of x.
776 // The approximation error is ~2.5e-07.
777 // Boost's minimax tool that utilizes the Remez method was used to find the
778 // coefficients.
781  PatternRewriter &rewriter) const {
782  Value operand = op.getOperand();
783  Type elementType = getElementTypeOrSelf(operand);
784 
785  if (!(elementType.isF32() || elementType.isF16()))
786  return rewriter.notifyMatchFailure(op,
787  "only f32 and f16 type is supported.");
788  ArrayRef<int64_t> shape = vectorShape(operand);
789 
790  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
791  auto bcast = [&](Value value) -> Value {
792  return broadcast(builder, value, shape);
793  };
794 
795  const int intervalsCount = 3;
796  const int polyDegree = 4;
797 
798  Value zero = bcast(floatCst(builder, 0, elementType));
799  Value one = bcast(floatCst(builder, 1, elementType));
800  Value pp[intervalsCount][polyDegree + 1];
801  pp[0][0] = bcast(floatCst(builder, +0.00000000000000000e+00f, elementType));
802  pp[0][1] = bcast(floatCst(builder, +1.12837916222975858e+00f, elementType));
803  pp[0][2] = bcast(floatCst(builder, -5.23018562988006470e-01f, elementType));
804  pp[0][3] = bcast(floatCst(builder, +2.09741709609267072e-01f, elementType));
805  pp[0][4] = bcast(floatCst(builder, +2.58146801602987875e-02f, elementType));
806  pp[1][0] = bcast(floatCst(builder, +0.00000000000000000e+00f, elementType));
807  pp[1][1] = bcast(floatCst(builder, +1.12750687816789140e+00f, elementType));
808  pp[1][2] = bcast(floatCst(builder, -3.64721408487825775e-01f, elementType));
809  pp[1][3] = bcast(floatCst(builder, +1.18407396425136952e-01f, elementType));
810  pp[1][4] = bcast(floatCst(builder, +3.70645533056476558e-02f, elementType));
811  pp[2][0] = bcast(floatCst(builder, -3.30093071049483172e-03f, elementType));
812  pp[2][1] = bcast(floatCst(builder, +3.51961938357697011e-03f, elementType));
813  pp[2][2] = bcast(floatCst(builder, -1.41373622814988039e-03f, elementType));
814  pp[2][3] = bcast(floatCst(builder, +2.53447094961941348e-04f, elementType));
815  pp[2][4] = bcast(floatCst(builder, -1.71048029455037401e-05f, elementType));
816 
817  Value qq[intervalsCount][polyDegree + 1];
818  qq[0][0] = bcast(floatCst(builder, +1.000000000000000000e+00f, elementType));
819  qq[0][1] = bcast(floatCst(builder, -4.635138185962547255e-01f, elementType));
820  qq[0][2] = bcast(floatCst(builder, +5.192301327279782447e-01f, elementType));
821  qq[0][3] = bcast(floatCst(builder, -1.318089722204810087e-01f, elementType));
822  qq[0][4] = bcast(floatCst(builder, +7.397964654672315005e-02f, elementType));
823  qq[1][0] = bcast(floatCst(builder, +1.00000000000000000e+00f, elementType));
824  qq[1][1] = bcast(floatCst(builder, -3.27607011824493086e-01f, elementType));
825  qq[1][2] = bcast(floatCst(builder, +4.48369090658821977e-01f, elementType));
826  qq[1][3] = bcast(floatCst(builder, -8.83462621207857930e-02f, elementType));
827  qq[1][4] = bcast(floatCst(builder, +5.72442770283176093e-02f, elementType));
828  qq[2][0] = bcast(floatCst(builder, +1.00000000000000000e+00f, elementType));
829  qq[2][1] = bcast(floatCst(builder, -2.06069165953913769e+00f, elementType));
830  qq[2][2] = bcast(floatCst(builder, +1.62705939945477759e+00f, elementType));
831  qq[2][3] = bcast(floatCst(builder, -5.83389859211130017e-01f, elementType));
832  qq[2][4] = bcast(floatCst(builder, +8.21908939856640930e-02f, elementType));
833 
834  Value offsets[intervalsCount];
835  offsets[0] = bcast(floatCst(builder, 0.0f, elementType));
836  offsets[1] = bcast(floatCst(builder, 0.0f, elementType));
837  offsets[2] = bcast(floatCst(builder, 1.0f, elementType));
838 
839  Value bounds[intervalsCount];
840  bounds[0] = bcast(floatCst(builder, 0.8f, elementType));
841  bounds[1] = bcast(floatCst(builder, 2.0f, elementType));
842  bounds[2] = bcast(floatCst(builder, 3.75f, elementType));
843 
844  Value isNegativeArg =
845  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, operand, zero);
846  Value negArg = builder.create<arith::NegFOp>(operand);
847  Value x = builder.create<arith::SelectOp>(isNegativeArg, negArg, operand);
848 
849  Value offset = offsets[0];
850  Value p[polyDegree + 1];
851  Value q[polyDegree + 1];
852  for (int i = 0; i <= polyDegree; ++i) {
853  p[i] = pp[0][i];
854  q[i] = qq[0][i];
855  }
856 
857  // TODO: maybe use vector stacking to reduce the number of selects.
858  Value isLessThanBound[intervalsCount];
859  for (int j = 0; j < intervalsCount - 1; ++j) {
860  isLessThanBound[j] =
861  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x, bounds[j]);
862  for (int i = 0; i <= polyDegree; ++i) {
863  p[i] = builder.create<arith::SelectOp>(isLessThanBound[j], p[i],
864  pp[j + 1][i]);
865  q[i] = builder.create<arith::SelectOp>(isLessThanBound[j], q[i],
866  qq[j + 1][i]);
867  }
868  offset = builder.create<arith::SelectOp>(isLessThanBound[j], offset,
869  offsets[j + 1]);
870  }
871  isLessThanBound[intervalsCount - 1] = builder.create<arith::CmpFOp>(
872  arith::CmpFPredicate::ULT, x, bounds[intervalsCount - 1]);
873 
874  Value pPoly = makePolynomialCalculation(builder, p, x);
875  Value qPoly = makePolynomialCalculation(builder, q, x);
876  Value rationalPoly = builder.create<arith::DivFOp>(pPoly, qPoly);
877  Value formula = builder.create<arith::AddFOp>(offset, rationalPoly);
878  formula = builder.create<arith::SelectOp>(isLessThanBound[intervalsCount - 1],
879  formula, one);
880 
881  // erf is odd function: erf(x) = -erf(-x).
882  Value negFormula = builder.create<arith::NegFOp>(formula);
883  Value res =
884  builder.create<arith::SelectOp>(isNegativeArg, negFormula, formula);
885 
886  rewriter.replaceOp(op, res);
887 
888  return success();
889 }
890 
891 //----------------------------------------------------------------------------//
892 // Exp approximation.
893 //----------------------------------------------------------------------------//
894 
895 namespace {
896 
897 struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
898 public:
900 
901  LogicalResult matchAndRewrite(math::ExpOp op,
902  PatternRewriter &rewriter) const final;
903 };
904 } // namespace
905 
906 // Approximate exp(x) using its reduced range exp(y) where y is in the range
907 // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
908 // = exp(y) * 2^k. exp(y).
910 ExpApproximation::matchAndRewrite(math::ExpOp op,
911  PatternRewriter &rewriter) const {
912  if (!getElementTypeOrSelf(op.getOperand()).isF32())
913  return rewriter.notifyMatchFailure(op, "unsupported operand type");
914 
915  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
916 
917  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
918 
919  // TODO: Consider a common pattern rewriter with all methods below to
920  // write the approximations.
921  auto bcast = [&](Value value) -> Value {
922  return broadcast(builder, value, shape);
923  };
924  auto fmla = [&](Value a, Value b, Value c) {
925  return builder.create<math::FmaOp>(a, b, c);
926  };
927  auto mul = [&](Value a, Value b) -> Value {
928  return builder.create<arith::MulFOp>(a, b);
929  };
930  auto sub = [&](Value a, Value b) -> Value {
931  return builder.create<arith::SubFOp>(a, b);
932  };
933  auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
934 
935  Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
936  Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
937 
938  // Polynomial coefficients.
939  Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
940  Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
941  Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
942  Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
943  Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
944  Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
945 
946  Value x = op.getOperand();
947 
948  Value isNan = builder.create<arith::CmpFOp>(arith::CmpFPredicate::UNO, x, x);
949 
950  // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
951  Value xL2Inv = mul(x, cstLog2E);
952  Value kF32 = floor(xL2Inv);
953  Value kLn2 = mul(kF32, cstLn2);
954  Value y = sub(x, kLn2);
955 
956  // Use Estrin's evaluation scheme with 3 independent parts:
957  // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
958  Value y2 = mul(y, y);
959  Value y4 = mul(y2, y2);
960 
961  Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
962  Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
963  Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
964  Value expY = fmla(q1, y2, q0);
965  expY = fmla(q2, y4, expY);
966 
967  auto i32Vec = broadcast(builder.getI32Type(), shape);
968 
969  // exp2(k)
970  Value k = builder.create<arith::FPToSIOp>(i32Vec, kF32);
971  Value exp2KValue = exp2I32(builder, k);
972 
973  // exp(x) = exp(y) * exp2(k)
974  expY = mul(expY, exp2KValue);
975 
976  // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
977  // partitioned as the following:
978  // exp(x) = 0, x <= -inf
979  // exp(x) = underflow (min_float), x <= -88
980  // exp(x) = inf (min_float), x >= 88
981  // Note: |k| = 127 is the value where the 8-bits exponent saturates.
982  Value zerof32Const = bcast(f32Cst(builder, 0));
983  auto constPosInfinity =
984  bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
985  auto constNegIfinity =
986  bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
987  auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
988 
989  Value kMaxConst = bcast(i32Cst(builder, 127));
990  Value kMaxNegConst = bcast(i32Cst(builder, -127));
991  Value rightBound =
992  builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, k, kMaxConst);
993  Value leftBound =
994  builder.create<arith::CmpIOp>(arith::CmpIPredicate::sge, k, kMaxNegConst);
995 
996  Value isNegInfinityX = builder.create<arith::CmpFOp>(
997  arith::CmpFPredicate::OEQ, x, constNegIfinity);
998  Value isPosInfinityX = builder.create<arith::CmpFOp>(
999  arith::CmpFPredicate::OEQ, x, constPosInfinity);
1000  Value isPostiveX =
1001  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zerof32Const);
1002  Value isComputable = builder.create<arith::AndIOp>(rightBound, leftBound);
1003 
1004  expY = builder.create<arith::SelectOp>(
1005  isNan, x,
1006  builder.create<arith::SelectOp>(
1007  isNegInfinityX, zerof32Const,
1008  builder.create<arith::SelectOp>(
1009  isPosInfinityX, constPosInfinity,
1010  builder.create<arith::SelectOp>(
1011  isComputable, expY,
1012  builder.create<arith::SelectOp>(isPostiveX, constPosInfinity,
1013  underflow)))));
1014 
1015  rewriter.replaceOp(op, expY);
1016 
1017  return success();
1018 }
1019 
1020 //----------------------------------------------------------------------------//
1021 // ExpM1 approximation.
1022 //----------------------------------------------------------------------------//
1023 
1024 namespace {
1025 
1026 struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> {
1027 public:
1029 
1030  LogicalResult matchAndRewrite(math::ExpM1Op op,
1031  PatternRewriter &rewriter) const final;
1032 };
1033 } // namespace
1034 
1036 ExpM1Approximation::matchAndRewrite(math::ExpM1Op op,
1037  PatternRewriter &rewriter) const {
1038  if (!getElementTypeOrSelf(op.getOperand()).isF32())
1039  return rewriter.notifyMatchFailure(op, "unsupported operand type");
1040 
1041  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1042 
1043  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
1044  auto bcast = [&](Value value) -> Value {
1045  return broadcast(builder, value, shape);
1046  };
1047 
1048  // expm1(x) = exp(x) - 1 = u - 1.
1049  // We have to handle it carefully when x is near 0, i.e. u ~= 1,
1050  // and when the input is ~= -inf, i.e. u - 1 ~= -1.
1051  Value cstOne = bcast(f32Cst(builder, 1.0f));
1052  Value cstNegOne = bcast(f32Cst(builder, -1.0f));
1053  Value x = op.getOperand();
1054  Value u = builder.create<math::ExpOp>(x);
1055  Value uEqOneOrNaN =
1056  builder.create<arith::CmpFOp>(arith::CmpFPredicate::UEQ, u, cstOne);
1057  Value uMinusOne = builder.create<arith::SubFOp>(u, cstOne);
1058  Value uMinusOneEqNegOne = builder.create<arith::CmpFOp>(
1059  arith::CmpFPredicate::OEQ, uMinusOne, cstNegOne);
1060  // logU = log(u) ~= x
1061  Value logU = builder.create<math::LogOp>(u);
1062 
1063  // Detect exp(x) = +inf; written this way to avoid having to form +inf.
1064  Value isInf =
1065  builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, logU, u);
1066 
1067  // (u - 1) * (x / ~x)
1068  Value expm1 = builder.create<arith::MulFOp>(
1069  uMinusOne, builder.create<arith::DivFOp>(x, logU));
1070  expm1 = builder.create<arith::SelectOp>(isInf, u, expm1);
1071  Value approximation = builder.create<arith::SelectOp>(
1072  uEqOneOrNaN, x,
1073  builder.create<arith::SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1));
1074  rewriter.replaceOp(op, approximation);
1075  return success();
1076 }
1077 
1078 //----------------------------------------------------------------------------//
1079 // Sin and Cos approximation.
1080 //----------------------------------------------------------------------------//
1081 
1082 namespace {
1083 
1084 template <bool isSine, typename OpTy>
1085 struct SinAndCosApproximation : public OpRewritePattern<OpTy> {
1086 public:
1088 
1089  LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final;
1090 };
1091 } // namespace
1092 
1093 #define TWO_OVER_PI \
1094  0.6366197723675813430755350534900574481378385829618257949906693762L
1095 #define PI_OVER_2 \
1096  1.5707963267948966192313216916397514420985846996875529104874722961L
1097 
1098 // Approximates sin(x) or cos(x) by finding the best approximation polynomial in
1099 // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the
1100 // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y).
1101 template <bool isSine, typename OpTy>
1102 LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite(
1103  OpTy op, PatternRewriter &rewriter) const {
1104  static_assert(
1106  "SinAndCosApproximation pattern expects math::SinOp or math::CosOp");
1107 
1108  if (!getElementTypeOrSelf(op.getOperand()).isF32())
1109  return rewriter.notifyMatchFailure(op, "unsupported operand type");
1110 
1111  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1112 
1113  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
1114  auto bcast = [&](Value value) -> Value {
1115  return broadcast(builder, value, shape);
1116  };
1117  auto mul = [&](Value a, Value b) -> Value {
1118  return builder.create<arith::MulFOp>(a, b);
1119  };
1120  auto sub = [&](Value a, Value b) -> Value {
1121  return builder.create<arith::SubFOp>(a, b);
1122  };
1123  auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
1124 
1125  auto i32Vec = broadcast(builder.getI32Type(), shape);
1126  auto fPToSingedInteger = [&](Value a) -> Value {
1127  return builder.create<arith::FPToSIOp>(i32Vec, a);
1128  };
1129 
1130  auto modulo4 = [&](Value a) -> Value {
1131  return builder.create<arith::AndIOp>(a, bcast(i32Cst(builder, 3)));
1132  };
1133 
1134  auto isEqualTo = [&](Value a, Value b) -> Value {
1135  return builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, a, b);
1136  };
1137 
1138  auto isGreaterThan = [&](Value a, Value b) -> Value {
1139  return builder.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, a, b);
1140  };
1141 
1142  auto select = [&](Value cond, Value t, Value f) -> Value {
1143  return builder.create<arith::SelectOp>(cond, t, f);
1144  };
1145 
1146  auto fmla = [&](Value a, Value b, Value c) {
1147  return builder.create<math::FmaOp>(a, b, c);
1148  };
1149 
1150  auto bitwiseOr = [&](Value a, Value b) {
1151  return builder.create<arith::OrIOp>(a, b);
1152  };
1153 
1154  Value twoOverPi = bcast(f32Cst(builder, (float)TWO_OVER_PI));
1155  Value piOverTwo = bcast(f32Cst(builder, (float)PI_OVER_2));
1156 
1157  Value x = op.getOperand();
1158 
1159  Value k = floor(mul(x, twoOverPi));
1160 
1161  Value y = sub(x, mul(k, piOverTwo));
1162 
1163  Value cstOne = bcast(f32Cst(builder, 1.0));
1164  Value cstNegativeOne = bcast(f32Cst(builder, -1.0));
1165 
1166  Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f));
1167  Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f));
1168  Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f));
1169  Value cstSC8 =
1170  bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f));
1171  Value cstSC10 =
1172  bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f));
1173 
1174  Value cstCC2 = bcast(f32Cst(builder, -0.5f));
1175  Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f));
1176  Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f));
1177  Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f));
1178  Value cstCC10 =
1179  bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f));
1180 
1181  Value kMod4 = modulo4(fPToSingedInteger(k));
1182 
1183  Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0)));
1184  Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1)));
1185  Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2)));
1186  Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3)));
1187 
1188  Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2);
1189  Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1)))
1190  : bitwiseOr(kR1, kR2);
1191 
1192  Value y2 = mul(y, y);
1193 
1194  Value base = select(sinuseCos, cstOne, y);
1195  Value cstC2 = select(sinuseCos, cstCC2, cstSC2);
1196  Value cstC4 = select(sinuseCos, cstCC4, cstSC4);
1197  Value cstC6 = select(sinuseCos, cstCC6, cstSC6);
1198  Value cstC8 = select(sinuseCos, cstCC8, cstSC8);
1199  Value cstC10 = select(sinuseCos, cstCC10, cstSC10);
1200 
1201  Value v1 = fmla(y2, cstC10, cstC8);
1202  Value v2 = fmla(y2, v1, cstC6);
1203  Value v3 = fmla(y2, v2, cstC4);
1204  Value v4 = fmla(y2, v3, cstC2);
1205  Value v5 = fmla(y2, v4, cstOne);
1206  Value v6 = mul(base, v5);
1207 
1208  Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6);
1209 
1210  rewriter.replaceOp(op, approximation);
1211 
1212  return success();
1213 }
1214 
1215 //----------------------------------------------------------------------------//
1216 // Rsqrt approximation.
1217 //----------------------------------------------------------------------------//
1218 
1219 namespace {
1220 struct RsqrtApproximation : public OpRewritePattern<math::RsqrtOp> {
1222 
1223  LogicalResult matchAndRewrite(math::RsqrtOp op,
1224  PatternRewriter &rewriter) const final;
1225 };
1226 } // namespace
1227 
1229 RsqrtApproximation::matchAndRewrite(math::RsqrtOp op,
1230  PatternRewriter &rewriter) const {
1231  if (!getElementTypeOrSelf(op.getOperand()).isF32())
1232  return rewriter.notifyMatchFailure(op, "unsupported operand type");
1233 
1234  ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1235 
1236  // Only support already-vectorized rsqrt's.
1237  if (shape.empty() || shape.back() % 8 != 0)
1238  return rewriter.notifyMatchFailure(op, "unsupported operand type");
1239 
1240  ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
1241  auto bcast = [&](Value value) -> Value {
1242  return broadcast(builder, value, shape);
1243  };
1244 
1245  Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
1246  Value cstOnePointFive = bcast(f32Cst(builder, 1.5f));
1247  Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
1248  Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
1249 
1250  Value negHalf = builder.create<arith::MulFOp>(op.getOperand(), cstNegHalf);
1251 
1252  // Select only the inverse sqrt of positive normals (denormals are
1253  // flushed to zero).
1254  Value ltMinMask = builder.create<arith::CmpFOp>(
1255  arith::CmpFPredicate::OLT, op.getOperand(), cstMinNormPos);
1256  Value infMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
1257  op.getOperand(), cstPosInf);
1258  Value notNormalFiniteMask = builder.create<arith::OrIOp>(ltMinMask, infMask);
1259 
1260  // Compute an approximate result.
1262  builder, op->getOperands(), 8, [&builder](ValueRange operands) -> Value {
1263  return builder.create<x86vector::RsqrtOp>(operands);
1264  });
1265 
1266  // Do a single step of Newton-Raphson iteration to improve the approximation.
1267  // This uses the formula y_{n+1} = y_n * (1.5 - y_n * (0.5 * x) * y_n).
1268  // It is essential to evaluate the inner term like this because forming
1269  // y_n^2 may over- or underflow.
1270  Value inner = builder.create<arith::MulFOp>(negHalf, yApprox);
1271  Value fma = builder.create<math::FmaOp>(yApprox, inner, cstOnePointFive);
1272  Value yNewton = builder.create<arith::MulFOp>(yApprox, fma);
1273 
1274  // Select the result of the Newton-Raphson step for positive normal arguments.
1275  // For other arguments, choose the output of the intrinsic. This will
1276  // return rsqrt(+inf) = 0, rsqrt(x) = NaN if x < 0, and rsqrt(x) = +inf if
1277  // x is zero or a positive denormalized float (equivalent to flushing positive
1278  // denormalized inputs to zero).
1279  Value res =
1280  builder.create<arith::SelectOp>(notNormalFiniteMask, yApprox, yNewton);
1281  rewriter.replaceOp(op, res);
1282 
1283  return success();
1284 }
1285 
1286 //----------------------------------------------------------------------------//
1287 
1289  RewritePatternSet &patterns,
1291  patterns.add<AtanApproximation, Atan2Approximation, TanhApproximation,
1292  LogApproximation, Log2Approximation, Log1pApproximation,
1293  ErfPolynomialApproximation, ExpApproximation, ExpM1Approximation,
1294  ReuseF32Expansion<math::Atan2Op>,
1295  SinAndCosApproximation<true, math::SinOp>,
1296  SinAndCosApproximation<false, math::CosOp>>(
1297  patterns.getContext());
1298  if (options.enableAvx2)
1299  patterns.add<RsqrtApproximation>(patterns.getContext());
1300 }
static constexpr const bool value
static llvm::ManagedStatic< PassManagerOptions > options
static std::pair< Value, Value > frexp(ImplicitLocOpBuilder &builder, Value arg, bool isPositive=false)
#define LN2_VALUE
static Type broadcast(Type type, ArrayRef< int64_t > shape)
static Value f32Cst(ImplicitLocOpBuilder &builder, float value)
static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg)
#define PI_OVER_2
#define TWO_OVER_PI
static ArrayRef< int64_t > vectorShape(Type type)
static Value floatCst(ImplicitLocOpBuilder &builder, float value, Type elementType)
static Value handleMultidimensionalVectors(ImplicitLocOpBuilder &builder, ValueRange operands, int64_t vectorWidth, llvm::function_ref< Value(ValueRange)> compute)
LogicalResult insertCasts(Operation *op, PatternRewriter &rewriter)
static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound)
static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value)
#define LOG2E_VALUE
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition: SPIRVOps.cpp:696
IntegerAttr getI32IntegerAttr(int32_t value)
Definition: Builders.cpp:190
FloatType getF32Type()
Definition: Builders.cpp:48
FloatAttr getFloatAttr(Type type, double value)
Definition: Builders.cpp:235
IntegerType getI32Type()
Definition: Builders.cpp:68
IntegerType getIntegerType(unsigned width)
Definition: Builders.cpp:72
Attribute getZeroAttr(Type type)
Definition: Builders.cpp:306
FloatAttr getF32FloatAttr(float value)
Definition: Builders.cpp:227
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
OpTy create(Args &&...args)
Create an operation of specific op type at the current insertion point and location.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:64
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:422
Location getLoc()
The source location the operation was defined or derived from.
Definition: OpDefinition.h:108
This provides public APIs that all operations should have.
Operation is a basic unit of execution within MLIR.
Definition: Operation.h:31
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:154
operand_type_range getOperandTypes()
Definition: Operation.h:314
result_type_range getResultTypes()
Definition: Operation.h:345
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:295
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:605
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the rewriter that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:517
virtual void replaceOp(Operation *op, ValueRange newValues)
This method replaces the results of the operation with the specified list of values.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replaces the result op with a new op that is created without verification.
Definition: PatternMatch.h:451
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
U dyn_cast() const
Definition: Types.h:270
bool isF32() const
Definition: Types.cpp:25
bool isF16() const
Definition: Types.cpp:24
bool isa() const
Definition: Types.h:260
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:349
type_range getType() const
Type front()
Return first type in the range.
Definition: TypeRange.h:148
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:85
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:230
int compare(const Fraction &x, const Fraction &y)
Three-way comparison between two fractions.
Definition: Fraction.h:59
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt abs(const MPInt &x)
Definition: MPInt.h:370
MPInt floor(const Fraction &f)
Definition: Fraction.h:68
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
Given a set of sizes, compute and return the strides (i.e.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
SmallVector< int64_t > delinearize(ArrayRef< int64_t > strides, int64_t linearIndex)
Given the strides together with a linear index in the dimension space, returns the vector-space offse...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
int64_t computeMaxLinearIndex(ArrayRef< int64_t > basis)
Return the number of elements of basis (i.e.
void populateMathPolynomialApproximationPatterns(RewritePatternSet &patterns, const MathPolynomialApproximationOptions &options={})
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:356
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
Definition: PatternMatch.h:360
LogicalResult matchAndRewrite(math::ErfOp op, PatternRewriter &rewriter) const final
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.