1f99ccf65SEugene Zhulenev //===- PolynomialApproximation.cpp - Approximate math operations ----------===// 2f99ccf65SEugene Zhulenev // 3f99ccf65SEugene Zhulenev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4f99ccf65SEugene Zhulenev // See https://llvm.org/LICENSE.txt for license information. 5f99ccf65SEugene Zhulenev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6f99ccf65SEugene Zhulenev // 7f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===// 8f99ccf65SEugene Zhulenev // 9f99ccf65SEugene Zhulenev // This file implements expansion of math operations to fast approximations 10f99ccf65SEugene Zhulenev // that do not rely on any of the library functions. 11f99ccf65SEugene Zhulenev // 12f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===// 133a506b31SChris Lattner 14ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 15ce976d2dSEugene Zhulenev #include "mlir/Dialect/LLVMIR/LLVMTypes.h" 16f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/IR/Math.h" 17f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/Transforms/Passes.h" 18f99ccf65SEugene Zhulenev #include "mlir/Dialect/Vector/VectorOps.h" 19f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h" 20ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h" 213a506b31SChris Lattner #include "mlir/Transforms/Bufferize.h" 22f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h" 23f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 243a506b31SChris Lattner #include <climits> 25f99ccf65SEugene Zhulenev 26f99ccf65SEugene Zhulenev using namespace mlir; 27f99ccf65SEugene Zhulenev using namespace mlir::vector; 28f99ccf65SEugene Zhulenev 29ce976d2dSEugene Zhulenev using TypePredicate = llvm::function_ref<bool(Type)>; 30ce976d2dSEugene Zhulenev 31ce976d2dSEugene Zhulenev // Returns vector width if the element type is matching the predicate (scalars 32ce976d2dSEugene Zhulenev // that do match the predicate have width equal to `1`). 33ce976d2dSEugene Zhulenev static Optional<int> vectorWidth(Type type, TypePredicate pred) { 34ce976d2dSEugene Zhulenev // If the type matches the predicate then its width is `1`. 35ce976d2dSEugene Zhulenev if (pred(type)) 36ce976d2dSEugene Zhulenev return 1; 37ce976d2dSEugene Zhulenev 38ce976d2dSEugene Zhulenev // Otherwise check if the type is a vector type. 39ce976d2dSEugene Zhulenev auto vectorType = type.dyn_cast<VectorType>(); 40ce976d2dSEugene Zhulenev if (vectorType && pred(vectorType.getElementType())) { 41ce976d2dSEugene Zhulenev assert(vectorType.getRank() == 1 && "only 1d vectors are supported"); 42ce976d2dSEugene Zhulenev return vectorType.getDimSize(0); 43ce976d2dSEugene Zhulenev } 44ce976d2dSEugene Zhulenev 45ce976d2dSEugene Zhulenev return llvm::None; 46ce976d2dSEugene Zhulenev } 47ce976d2dSEugene Zhulenev 48ce976d2dSEugene Zhulenev // Returns vector width of the type. If the type is a scalar returns `1`. 49ce976d2dSEugene Zhulenev static int vectorWidth(Type type) { 50ce976d2dSEugene Zhulenev auto vectorType = type.dyn_cast<VectorType>(); 51ce976d2dSEugene Zhulenev return vectorType ? vectorType.getDimSize(0) : 1; 52ce976d2dSEugene Zhulenev } 53ce976d2dSEugene Zhulenev 54ce976d2dSEugene Zhulenev // Returns vector element type. If the type is a scalar returns the argument. 5539b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static Type elementType(Type type) { 56ce976d2dSEugene Zhulenev auto vectorType = type.dyn_cast<VectorType>(); 57ce976d2dSEugene Zhulenev return vectorType ? vectorType.getElementType() : type; 58f99ccf65SEugene Zhulenev } 59f99ccf65SEugene Zhulenev 6039b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isF32(Type type) { return type.isF32(); } 6139b2cd40SEugene Zhulenev 6239b2cd40SEugene Zhulenev LLVM_ATTRIBUTE_UNUSED static bool isI32(Type type) { 6339b2cd40SEugene Zhulenev return type.isInteger(32); 6439b2cd40SEugene Zhulenev } 6539b2cd40SEugene Zhulenev 66f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 67ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values. 68f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 69f99ccf65SEugene Zhulenev 70ce976d2dSEugene Zhulenev // Broadcasts scalar type into vector type (iff width is greater then 1). 71ce976d2dSEugene Zhulenev static Type broadcast(Type type, int width) { 72ce976d2dSEugene Zhulenev assert(!type.isa<VectorType>() && "must be scalar type"); 73ce976d2dSEugene Zhulenev return width > 1 ? VectorType::get({width}, type) : type; 74ce976d2dSEugene Zhulenev } 75f99ccf65SEugene Zhulenev 76ce976d2dSEugene Zhulenev // Broadcasts scalar value into vector (iff width is greater then 1). 77ce976d2dSEugene Zhulenev static Value broadcast(ImplicitLocOpBuilder &builder, Value value, int width) { 78ce976d2dSEugene Zhulenev assert(!value.getType().isa<VectorType>() && "must be scalar value"); 79ce976d2dSEugene Zhulenev auto type = broadcast(value.getType(), width); 80ce976d2dSEugene Zhulenev return width > 1 ? builder.create<BroadcastOp>(type, value) : value; 81ce976d2dSEugene Zhulenev } 82f99ccf65SEugene Zhulenev 83ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 84ce976d2dSEugene Zhulenev // Helper functions to create constants. 85ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 86f99ccf65SEugene Zhulenev 87ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) { 88ce976d2dSEugene Zhulenev return builder.create<ConstantOp>(builder.getF32Type(), 89ce976d2dSEugene Zhulenev builder.getF32FloatAttr(value)); 90ce976d2dSEugene Zhulenev } 91f99ccf65SEugene Zhulenev 92ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) { 93ce976d2dSEugene Zhulenev return builder.create<ConstantOp>(builder.getI32Type(), 94ce976d2dSEugene Zhulenev builder.getI32IntegerAttr(value)); 95ce976d2dSEugene Zhulenev } 96f99ccf65SEugene Zhulenev 97ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) { 98ce976d2dSEugene Zhulenev Value i32Value = i32Cst(builder, static_cast<int32_t>(bits)); 99ce976d2dSEugene Zhulenev return builder.create<LLVM::BitcastOp>(builder.getF32Type(), i32Value); 100ce976d2dSEugene Zhulenev } 101f99ccf65SEugene Zhulenev 102ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 103ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations. 104ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 105ce976d2dSEugene Zhulenev 106ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) { 107ce976d2dSEugene Zhulenev return builder.create<SelectOp>( 108ce976d2dSEugene Zhulenev builder.create<CmpFOp>(CmpFPredicate::OLT, a, b), a, b); 109ce976d2dSEugene Zhulenev } 110ce976d2dSEugene Zhulenev 111ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) { 112ce976d2dSEugene Zhulenev return builder.create<SelectOp>( 113ce976d2dSEugene Zhulenev builder.create<CmpFOp>(CmpFPredicate::OGT, a, b), a, b); 114ce976d2dSEugene Zhulenev } 115ce976d2dSEugene Zhulenev 116ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, 117ce976d2dSEugene Zhulenev Value upperBound) { 118ce976d2dSEugene Zhulenev return max(builder, min(builder, value, upperBound), lowerBound); 119ce976d2dSEugene Zhulenev } 120ce976d2dSEugene Zhulenev 121ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and 122ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type. 123ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg, 124ce976d2dSEugene Zhulenev bool is_positive = false) { 125ce976d2dSEugene Zhulenev assert(isF32(elementType(arg.getType())) && "argument must be f32 type"); 126ce976d2dSEugene Zhulenev 127ce976d2dSEugene Zhulenev int width = vectorWidth(arg.getType()); 128ce976d2dSEugene Zhulenev 129ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 130ce976d2dSEugene Zhulenev return broadcast(builder, value, width); 131f99ccf65SEugene Zhulenev }; 132f99ccf65SEugene Zhulenev 133ce976d2dSEugene Zhulenev auto i32 = builder.getIntegerType(32); 134ce976d2dSEugene Zhulenev auto i32Vec = broadcast(i32, width); 135ce976d2dSEugene Zhulenev auto f32Vec = broadcast(builder.getF32Type(), width); 136f99ccf65SEugene Zhulenev 137ce976d2dSEugene Zhulenev Value cst126f = f32Cst(builder, 126.0f); 138ce976d2dSEugene Zhulenev Value cstHalf = f32Cst(builder, 0.5f); 139ce976d2dSEugene Zhulenev Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u); 140f99ccf65SEugene Zhulenev 141ce976d2dSEugene Zhulenev // Bitcast to i32 for bitwise operations. 142ce976d2dSEugene Zhulenev Value i32Half = builder.create<LLVM::BitcastOp>(i32, cstHalf); 143ce976d2dSEugene Zhulenev Value i32InvMantMask = builder.create<LLVM::BitcastOp>(i32, cstInvMantMask); 144ce976d2dSEugene Zhulenev Value i32Arg = builder.create<LLVM::BitcastOp>(i32Vec, arg); 145f99ccf65SEugene Zhulenev 146ce976d2dSEugene Zhulenev // Compute normalized fraction. 147ce976d2dSEugene Zhulenev Value tmp0 = builder.create<LLVM::AndOp>(i32Arg, bcast(i32InvMantMask)); 148ce976d2dSEugene Zhulenev Value tmp1 = builder.create<LLVM::OrOp>(tmp0, bcast(i32Half)); 149ce976d2dSEugene Zhulenev Value normalizedFraction = builder.create<LLVM::BitcastOp>(f32Vec, tmp1); 150f99ccf65SEugene Zhulenev 151ce976d2dSEugene Zhulenev // Compute exponent. 152ce976d2dSEugene Zhulenev Value arg0 = is_positive ? arg : builder.create<AbsFOp>(arg); 153ce976d2dSEugene Zhulenev Value biasedExponentBits = builder.create<UnsignedShiftRightOp>( 154ce976d2dSEugene Zhulenev builder.create<LLVM::BitcastOp>(i32Vec, arg0), 155ce976d2dSEugene Zhulenev bcast(i32Cst(builder, 23))); 156ce976d2dSEugene Zhulenev Value biasedExponent = builder.create<SIToFPOp>(f32Vec, biasedExponentBits); 157ce976d2dSEugene Zhulenev Value exponent = builder.create<SubFOp>(biasedExponent, bcast(cst126f)); 158f99ccf65SEugene Zhulenev 159ce976d2dSEugene Zhulenev return {normalizedFraction, exponent}; 160f99ccf65SEugene Zhulenev } 161f99ccf65SEugene Zhulenev 162ea7f211bSAhmed Taei // Computes exp2 for an i32 argument. 163ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) { 164ea7f211bSAhmed Taei assert(isI32(elementType(arg.getType())) && "argument must be i32 type"); 165ea7f211bSAhmed Taei 166ea7f211bSAhmed Taei int width = vectorWidth(arg.getType()); 167ea7f211bSAhmed Taei 168ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value { 169ea7f211bSAhmed Taei return broadcast(builder, value, width); 170ea7f211bSAhmed Taei }; 171ea7f211bSAhmed Taei 172ea7f211bSAhmed Taei auto f32Vec = broadcast(builder.getF32Type(), width); 173ea7f211bSAhmed Taei // The exponent of f32 located at 23-bit. 174ea7f211bSAhmed Taei auto exponetBitLocation = bcast(i32Cst(builder, 23)); 175ea7f211bSAhmed Taei // Set the exponent bias to zero. 176ea7f211bSAhmed Taei auto bias = bcast(i32Cst(builder, 127)); 177ea7f211bSAhmed Taei 178ea7f211bSAhmed Taei Value biasedArg = builder.create<AddIOp>(arg, bias); 179ea7f211bSAhmed Taei Value exp2ValueInt = 180ea7f211bSAhmed Taei builder.create<ShiftLeftOp>(biasedArg, exponetBitLocation); 181ea7f211bSAhmed Taei Value exp2ValueF32 = builder.create<LLVM::BitcastOp>(f32Vec, exp2ValueInt); 182ea7f211bSAhmed Taei 183ea7f211bSAhmed Taei return exp2ValueF32; 184ea7f211bSAhmed Taei } 185ea7f211bSAhmed Taei 186f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 187f99ccf65SEugene Zhulenev // TanhOp approximation. 188f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 189f99ccf65SEugene Zhulenev 190f99ccf65SEugene Zhulenev namespace { 191f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> { 192f99ccf65SEugene Zhulenev public: 193f99ccf65SEugene Zhulenev using OpRewritePattern::OpRewritePattern; 194f99ccf65SEugene Zhulenev 195f99ccf65SEugene Zhulenev LogicalResult matchAndRewrite(math::TanhOp op, 196f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const final; 197f99ccf65SEugene Zhulenev }; 198f99ccf65SEugene Zhulenev } // namespace 199f99ccf65SEugene Zhulenev 200f99ccf65SEugene Zhulenev LogicalResult 201f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op, 202f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const { 203ce976d2dSEugene Zhulenev auto width = vectorWidth(op.operand().getType(), isF32); 204ce976d2dSEugene Zhulenev if (!width.hasValue()) 205f99ccf65SEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type"); 206f99ccf65SEugene Zhulenev 207ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 208ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 209ce976d2dSEugene Zhulenev return broadcast(builder, value, *width); 210ce976d2dSEugene Zhulenev }; 211f99ccf65SEugene Zhulenev 212f99ccf65SEugene Zhulenev // Clamp operand into [plusClamp, minusClamp] range. 213ce976d2dSEugene Zhulenev Value minusClamp = bcast(f32Cst(builder, -7.9053111076354980f)); 214ce976d2dSEugene Zhulenev Value plusClamp = bcast(f32Cst(builder, 7.90531110763549805f)); 215ce976d2dSEugene Zhulenev Value x = clamp(builder, op.operand(), minusClamp, plusClamp); 216f99ccf65SEugene Zhulenev 217f99ccf65SEugene Zhulenev // Mask for tiny values that are approximated with `operand`. 218ce976d2dSEugene Zhulenev Value tiny = bcast(f32Cst(builder, 0.0004f)); 219ce976d2dSEugene Zhulenev Value tinyMask = builder.create<CmpFOp>( 220ce976d2dSEugene Zhulenev CmpFPredicate::OLT, builder.create<AbsFOp>(op.operand()), tiny); 221f99ccf65SEugene Zhulenev 222f99ccf65SEugene Zhulenev // The monomial coefficients of the numerator polynomial (odd). 223ce976d2dSEugene Zhulenev Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f)); 224ce976d2dSEugene Zhulenev Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f)); 225ce976d2dSEugene Zhulenev Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f)); 226ce976d2dSEugene Zhulenev Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f)); 227ce976d2dSEugene Zhulenev Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f)); 228ce976d2dSEugene Zhulenev Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f)); 229ce976d2dSEugene Zhulenev Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f)); 230f99ccf65SEugene Zhulenev 231f99ccf65SEugene Zhulenev // The monomial coefficients of the denominator polynomial (even). 232ce976d2dSEugene Zhulenev Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f)); 233ce976d2dSEugene Zhulenev Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f)); 234ce976d2dSEugene Zhulenev Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f)); 235ce976d2dSEugene Zhulenev Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f)); 236f99ccf65SEugene Zhulenev 237f99ccf65SEugene Zhulenev // Since the polynomials are odd/even, we need x^2. 238ce976d2dSEugene Zhulenev Value x2 = builder.create<MulFOp>(x, x); 239f99ccf65SEugene Zhulenev 240f99ccf65SEugene Zhulenev // Evaluate the numerator polynomial p. 241ce976d2dSEugene Zhulenev Value p = builder.create<FmaFOp>(x2, alpha13, alpha11); 242ce976d2dSEugene Zhulenev p = builder.create<FmaFOp>(x2, p, alpha9); 243ce976d2dSEugene Zhulenev p = builder.create<FmaFOp>(x2, p, alpha7); 244ce976d2dSEugene Zhulenev p = builder.create<FmaFOp>(x2, p, alpha5); 245ce976d2dSEugene Zhulenev p = builder.create<FmaFOp>(x2, p, alpha3); 246ce976d2dSEugene Zhulenev p = builder.create<FmaFOp>(x2, p, alpha1); 247ce976d2dSEugene Zhulenev p = builder.create<MulFOp>(x, p); 248f99ccf65SEugene Zhulenev 249f99ccf65SEugene Zhulenev // Evaluate the denominator polynomial q. 250ce976d2dSEugene Zhulenev Value q = builder.create<FmaFOp>(x2, beta6, beta4); 251ce976d2dSEugene Zhulenev q = builder.create<FmaFOp>(x2, q, beta2); 252ce976d2dSEugene Zhulenev q = builder.create<FmaFOp>(x2, q, beta0); 253f99ccf65SEugene Zhulenev 254f99ccf65SEugene Zhulenev // Divide the numerator by the denominator. 255ce976d2dSEugene Zhulenev Value res = 256ce976d2dSEugene Zhulenev builder.create<SelectOp>(tinyMask, x, builder.create<DivFOp>(p, q)); 257f99ccf65SEugene Zhulenev 258f99ccf65SEugene Zhulenev rewriter.replaceOp(op, res); 259f99ccf65SEugene Zhulenev 260f99ccf65SEugene Zhulenev return success(); 261f99ccf65SEugene Zhulenev } 262f99ccf65SEugene Zhulenev 263ea7f211bSAhmed Taei #define LN2_VALUE \ 264ea7f211bSAhmed Taei 0.693147180559945309417232121458176568075500134360255254120680009493393621L 265c0891706SEmilio Cota #define LOG2E_VALUE \ 266ea7f211bSAhmed Taei 1.442695040888963407359924681001892137426645954152985934135449406931109219L 267ea7f211bSAhmed Taei 268f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 269c0891706SEmilio Cota // LogOp and Log2Op approximation. 270ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 271ce976d2dSEugene Zhulenev 272ce976d2dSEugene Zhulenev namespace { 273c0891706SEmilio Cota template <typename Op> 274c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> { 275c0891706SEmilio Cota using OpRewritePattern<Op>::OpRewritePattern; 276ce976d2dSEugene Zhulenev 277c0891706SEmilio Cota /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise. 278c0891706SEmilio Cota LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter, 279c0891706SEmilio Cota bool base2) const; 280ce976d2dSEugene Zhulenev }; 281ce976d2dSEugene Zhulenev } // namespace 282ce976d2dSEugene Zhulenev 283c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library. 284c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath 285c0891706SEmilio Cota template <typename Op> 286ce976d2dSEugene Zhulenev LogicalResult 287c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter, 288c0891706SEmilio Cota bool base2) const { 289ce976d2dSEugene Zhulenev auto width = vectorWidth(op.operand().getType(), isF32); 290ce976d2dSEugene Zhulenev if (!width.hasValue()) 291ce976d2dSEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type"); 292ce976d2dSEugene Zhulenev 293ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 294ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 295ce976d2dSEugene Zhulenev return broadcast(builder, value, *width); 296ce976d2dSEugene Zhulenev }; 297ce976d2dSEugene Zhulenev 298ce976d2dSEugene Zhulenev Value cstZero = bcast(f32Cst(builder, 0.0f)); 299ce976d2dSEugene Zhulenev Value cstOne = bcast(f32Cst(builder, 1.0f)); 300ce976d2dSEugene Zhulenev Value cstNegHalf = bcast(f32Cst(builder, -0.5f)); 301ce976d2dSEugene Zhulenev 302ce976d2dSEugene Zhulenev // The smallest non denormalized float number. 303ce976d2dSEugene Zhulenev Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u)); 304ce976d2dSEugene Zhulenev Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u)); 305ce976d2dSEugene Zhulenev Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u)); 306ce976d2dSEugene Zhulenev Value cstNan = bcast(f32FromBits(builder, 0x7fc00000)); 307ce976d2dSEugene Zhulenev 308ce976d2dSEugene Zhulenev // Polynomial coefficients. 309ce976d2dSEugene Zhulenev Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f)); 310ce976d2dSEugene Zhulenev Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f)); 311ce976d2dSEugene Zhulenev Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f)); 312ce976d2dSEugene Zhulenev Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f)); 313ce976d2dSEugene Zhulenev Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f)); 314ce976d2dSEugene Zhulenev Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f)); 315ce976d2dSEugene Zhulenev Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f)); 316ce976d2dSEugene Zhulenev Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f)); 317ce976d2dSEugene Zhulenev Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f)); 318ce976d2dSEugene Zhulenev Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f)); 319ce976d2dSEugene Zhulenev 320ce976d2dSEugene Zhulenev Value x = op.operand(); 321ce976d2dSEugene Zhulenev 322ce976d2dSEugene Zhulenev // Truncate input values to the minimum positive normal. 323ce976d2dSEugene Zhulenev x = max(builder, x, cstMinNormPos); 324ce976d2dSEugene Zhulenev 325ce976d2dSEugene Zhulenev // Extract significant in the range [0.5,1) and exponent. 326ce976d2dSEugene Zhulenev std::pair<Value, Value> pair = frexp(builder, x, /*is_positive=*/true); 327ce976d2dSEugene Zhulenev x = pair.first; 328ce976d2dSEugene Zhulenev Value e = pair.second; 329ce976d2dSEugene Zhulenev 330ce976d2dSEugene Zhulenev // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift 331ce976d2dSEugene Zhulenev // by -1.0. The values are then centered around 0, which improves the 332ce976d2dSEugene Zhulenev // stability of the polynomial evaluation: 333ce976d2dSEugene Zhulenev // 334ce976d2dSEugene Zhulenev // if( x < SQRTHF ) { 335ce976d2dSEugene Zhulenev // e -= 1; 336ce976d2dSEugene Zhulenev // x = x + x - 1.0; 337ce976d2dSEugene Zhulenev // } else { x = x - 1.0; } 338ce976d2dSEugene Zhulenev Value mask = builder.create<CmpFOp>(CmpFPredicate::OLT, x, cstCephesSQRTHF); 339ce976d2dSEugene Zhulenev Value tmp = builder.create<SelectOp>(mask, x, cstZero); 340ce976d2dSEugene Zhulenev 341ce976d2dSEugene Zhulenev x = builder.create<SubFOp>(x, cstOne); 342ce976d2dSEugene Zhulenev e = builder.create<SubFOp>(e, 343ce976d2dSEugene Zhulenev builder.create<SelectOp>(mask, cstOne, cstZero)); 344ce976d2dSEugene Zhulenev x = builder.create<AddFOp>(x, tmp); 345ce976d2dSEugene Zhulenev 346ce976d2dSEugene Zhulenev Value x2 = builder.create<MulFOp>(x, x); 347ce976d2dSEugene Zhulenev Value x3 = builder.create<MulFOp>(x2, x); 348ce976d2dSEugene Zhulenev 349ce976d2dSEugene Zhulenev // Evaluate the polynomial approximant of degree 8 in three parts. 350ce976d2dSEugene Zhulenev Value y0, y1, y2; 351ce976d2dSEugene Zhulenev y0 = builder.create<FmaFOp>(cstCephesLogP0, x, cstCephesLogP1); 352ce976d2dSEugene Zhulenev y1 = builder.create<FmaFOp>(cstCephesLogP3, x, cstCephesLogP4); 353ce976d2dSEugene Zhulenev y2 = builder.create<FmaFOp>(cstCephesLogP6, x, cstCephesLogP7); 354ce976d2dSEugene Zhulenev y0 = builder.create<FmaFOp>(y0, x, cstCephesLogP2); 355ce976d2dSEugene Zhulenev y1 = builder.create<FmaFOp>(y1, x, cstCephesLogP5); 356ce976d2dSEugene Zhulenev y2 = builder.create<FmaFOp>(y2, x, cstCephesLogP8); 357ce976d2dSEugene Zhulenev y0 = builder.create<FmaFOp>(y0, x3, y1); 358ce976d2dSEugene Zhulenev y0 = builder.create<FmaFOp>(y0, x3, y2); 359ce976d2dSEugene Zhulenev y0 = builder.create<MulFOp>(y0, x3); 360ce976d2dSEugene Zhulenev 361ce976d2dSEugene Zhulenev y0 = builder.create<FmaFOp>(cstNegHalf, x2, y0); 362ce976d2dSEugene Zhulenev x = builder.create<AddFOp>(x, y0); 363ce976d2dSEugene Zhulenev 364c0891706SEmilio Cota if (base2) { 365c0891706SEmilio Cota Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE))); 366c0891706SEmilio Cota x = builder.create<FmaFOp>(x, cstLog2e, e); 367c0891706SEmilio Cota } else { 368ce976d2dSEugene Zhulenev Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE))); 369ce976d2dSEugene Zhulenev x = builder.create<FmaFOp>(e, cstLn2, x); 370c0891706SEmilio Cota } 371ce976d2dSEugene Zhulenev 372ce976d2dSEugene Zhulenev Value invalidMask = 373ce976d2dSEugene Zhulenev builder.create<CmpFOp>(CmpFPredicate::ULT, op.operand(), cstZero); 374ce976d2dSEugene Zhulenev Value zeroMask = 375ce976d2dSEugene Zhulenev builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstZero); 376ce976d2dSEugene Zhulenev Value posInfMask = 377ce976d2dSEugene Zhulenev builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstPosInf); 378ce976d2dSEugene Zhulenev 379ce976d2dSEugene Zhulenev // Filter out invalid values: 380ce976d2dSEugene Zhulenev // • x == 0 -> -INF 381ce976d2dSEugene Zhulenev // • x < 0 -> NAN 382ce976d2dSEugene Zhulenev // • x == +INF -> +INF 383ce976d2dSEugene Zhulenev Value aproximation = builder.create<SelectOp>( 384ce976d2dSEugene Zhulenev zeroMask, cstMinusInf, 385ce976d2dSEugene Zhulenev builder.create<SelectOp>( 386ce976d2dSEugene Zhulenev invalidMask, cstNan, 387ce976d2dSEugene Zhulenev builder.create<SelectOp>(posInfMask, cstPosInf, x))); 388ce976d2dSEugene Zhulenev 389ce976d2dSEugene Zhulenev rewriter.replaceOp(op, aproximation); 390ce976d2dSEugene Zhulenev 391ce976d2dSEugene Zhulenev return success(); 392ce976d2dSEugene Zhulenev } 393ce976d2dSEugene Zhulenev 394c0891706SEmilio Cota namespace { 395c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> { 396c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase; 397c0891706SEmilio Cota 398c0891706SEmilio Cota LogicalResult matchAndRewrite(math::LogOp op, 399c0891706SEmilio Cota PatternRewriter &rewriter) const final { 400c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/false); 401c0891706SEmilio Cota } 402c0891706SEmilio Cota }; 403c0891706SEmilio Cota } // namespace 404c0891706SEmilio Cota 405c0891706SEmilio Cota namespace { 406c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> { 407c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase; 408c0891706SEmilio Cota 409c0891706SEmilio Cota LogicalResult matchAndRewrite(math::Log2Op op, 410c0891706SEmilio Cota PatternRewriter &rewriter) const final { 411c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/true); 412c0891706SEmilio Cota } 413c0891706SEmilio Cota }; 414c0891706SEmilio Cota } // namespace 415c0891706SEmilio Cota 416ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 4171c0374e7SEmilio Cota // Log1p approximation. 4181c0374e7SEmilio Cota //----------------------------------------------------------------------------// 4191c0374e7SEmilio Cota 4201c0374e7SEmilio Cota namespace { 4211c0374e7SEmilio Cota struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> { 4221c0374e7SEmilio Cota public: 4231c0374e7SEmilio Cota using OpRewritePattern::OpRewritePattern; 4241c0374e7SEmilio Cota 4251c0374e7SEmilio Cota LogicalResult matchAndRewrite(math::Log1pOp op, 4261c0374e7SEmilio Cota PatternRewriter &rewriter) const final; 4271c0374e7SEmilio Cota }; 4281c0374e7SEmilio Cota } // namespace 4291c0374e7SEmilio Cota 4301c0374e7SEmilio Cota // Approximate log(1+x). 4311c0374e7SEmilio Cota LogicalResult 4321c0374e7SEmilio Cota Log1pApproximation::matchAndRewrite(math::Log1pOp op, 4331c0374e7SEmilio Cota PatternRewriter &rewriter) const { 4341c0374e7SEmilio Cota auto width = vectorWidth(op.operand().getType(), isF32); 4351c0374e7SEmilio Cota if (!width.hasValue()) 4361c0374e7SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type"); 4371c0374e7SEmilio Cota 4381c0374e7SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 4391c0374e7SEmilio Cota auto bcast = [&](Value value) -> Value { 4401c0374e7SEmilio Cota return broadcast(builder, value, *width); 4411c0374e7SEmilio Cota }; 4421c0374e7SEmilio Cota 4431c0374e7SEmilio Cota // Approximate log(1+x) using the following, due to W. Kahan: 4441c0374e7SEmilio Cota // u = x + 1.0; 4451c0374e7SEmilio Cota // if (u == 1.0 || u == inf) return x; 4461c0374e7SEmilio Cota // return x * log(u) / (u - 1.0); 4471c0374e7SEmilio Cota // ^^^^^^^^^^^^^^^^^^^^^^ 4481c0374e7SEmilio Cota // "logLarge" below. 4491c0374e7SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f)); 4501c0374e7SEmilio Cota Value x = op.operand(); 4511c0374e7SEmilio Cota Value u = builder.create<AddFOp>(x, cstOne); 4521c0374e7SEmilio Cota Value uSmall = builder.create<CmpFOp>(CmpFPredicate::OEQ, u, cstOne); 4531c0374e7SEmilio Cota Value logU = builder.create<math::LogOp>(u); 4541c0374e7SEmilio Cota Value uInf = builder.create<CmpFOp>(CmpFPredicate::OEQ, u, logU); 4551c0374e7SEmilio Cota Value logLarge = builder.create<MulFOp>( 4561c0374e7SEmilio Cota x, builder.create<DivFOp>(logU, builder.create<SubFOp>(u, cstOne))); 4571c0374e7SEmilio Cota Value approximation = builder.create<SelectOp>( 4581c0374e7SEmilio Cota builder.create<LLVM::OrOp>(uSmall, uInf), x, logLarge); 4591c0374e7SEmilio Cota rewriter.replaceOp(op, approximation); 4601c0374e7SEmilio Cota return success(); 4611c0374e7SEmilio Cota } 4621c0374e7SEmilio Cota 4631c0374e7SEmilio Cota //----------------------------------------------------------------------------// 464ea7f211bSAhmed Taei // Exp approximation. 465ea7f211bSAhmed Taei //----------------------------------------------------------------------------// 466ea7f211bSAhmed Taei 467ea7f211bSAhmed Taei namespace { 468ea7f211bSAhmed Taei 469ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> { 470ea7f211bSAhmed Taei public: 471ea7f211bSAhmed Taei using OpRewritePattern::OpRewritePattern; 472ea7f211bSAhmed Taei 473ea7f211bSAhmed Taei LogicalResult matchAndRewrite(math::ExpOp op, 474ea7f211bSAhmed Taei PatternRewriter &rewriter) const final; 475ea7f211bSAhmed Taei }; 476ea7f211bSAhmed Taei } // namespace 477ea7f211bSAhmed Taei 478ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range 479ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x) 480ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y). 481ea7f211bSAhmed Taei LogicalResult 482ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op, 483ea7f211bSAhmed Taei PatternRewriter &rewriter) const { 484ea7f211bSAhmed Taei auto width = vectorWidth(op.operand().getType(), isF32); 485ea7f211bSAhmed Taei if (!width.hasValue()) 486ea7f211bSAhmed Taei return rewriter.notifyMatchFailure(op, "unsupported operand type"); 487ea7f211bSAhmed Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 488ea7f211bSAhmed Taei 489ea7f211bSAhmed Taei // TODO: Consider a common pattern rewriter with all methods below to 490ea7f211bSAhmed Taei // write the approximations. 491ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value { 492ea7f211bSAhmed Taei return broadcast(builder, value, *width); 493ea7f211bSAhmed Taei }; 494ea7f211bSAhmed Taei auto fmla = [&](Value a, Value b, Value c) { 495ea7f211bSAhmed Taei return builder.create<FmaFOp>(a, b, c); 496ea7f211bSAhmed Taei }; 497ea7f211bSAhmed Taei auto mul = [&](Value a, Value b) -> Value { 498ea7f211bSAhmed Taei return builder.create<MulFOp>(a, b); 499ea7f211bSAhmed Taei }; 500ea7f211bSAhmed Taei auto sub = [&](Value a, Value b) -> Value { 501ea7f211bSAhmed Taei return builder.create<SubFOp>(a, b); 502ea7f211bSAhmed Taei }; 503ea7f211bSAhmed Taei auto floor = [&](Value a) { return builder.create<FloorFOp>(a); }; 504ea7f211bSAhmed Taei 505ea7f211bSAhmed Taei Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE))); 506c0891706SEmilio Cota Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE))); 507ea7f211bSAhmed Taei 508ea7f211bSAhmed Taei // Polynomial coefficients. 509ea7f211bSAhmed Taei Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0)); 510ea7f211bSAhmed Taei Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0)); 511ea7f211bSAhmed Taei Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f)); 512ea7f211bSAhmed Taei Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f)); 513ea7f211bSAhmed Taei Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f)); 514ea7f211bSAhmed Taei Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f)); 515ea7f211bSAhmed Taei 516ea7f211bSAhmed Taei Value x = op.operand(); 517ea7f211bSAhmed Taei 518ea7f211bSAhmed Taei // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2) 519c0891706SEmilio Cota Value xL2Inv = mul(x, cstLog2E); 520ea7f211bSAhmed Taei Value kF32 = floor(xL2Inv); 521ea7f211bSAhmed Taei Value kLn2 = mul(kF32, cstLn2); 522ea7f211bSAhmed Taei Value y = sub(x, kLn2); 523ea7f211bSAhmed Taei 524ea7f211bSAhmed Taei // Use Estrin's evaluation scheme with 3 independent parts: 525ea7f211bSAhmed Taei // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4 526ea7f211bSAhmed Taei Value y2 = mul(y, y); 527ea7f211bSAhmed Taei Value y4 = mul(y2, y2); 528ea7f211bSAhmed Taei 529ea7f211bSAhmed Taei Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0); 530ea7f211bSAhmed Taei Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2); 531ea7f211bSAhmed Taei Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4); 532ea7f211bSAhmed Taei Value expY = fmla(q1, y2, q0); 533ea7f211bSAhmed Taei expY = fmla(q2, y4, expY); 534ea7f211bSAhmed Taei 535ea7f211bSAhmed Taei auto i32Vec = broadcast(builder.getI32Type(), *width); 536ea7f211bSAhmed Taei 537ea7f211bSAhmed Taei // exp2(k) 538ea7f211bSAhmed Taei Value k = builder.create<FPToSIOp>(kF32, i32Vec); 539ea7f211bSAhmed Taei Value exp2KValue = exp2I32(builder, k); 540ea7f211bSAhmed Taei 541ea7f211bSAhmed Taei // exp(x) = exp(y) * exp2(k) 542ea7f211bSAhmed Taei expY = mul(expY, exp2KValue); 543ea7f211bSAhmed Taei 544ea7f211bSAhmed Taei // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its 545ea7f211bSAhmed Taei // partitioned as the following: 546ea7f211bSAhmed Taei // exp(x) = 0, x <= -inf 547ea7f211bSAhmed Taei // exp(x) = underflow (min_float), x <= -88 548ea7f211bSAhmed Taei // exp(x) = inf (min_float), x >= 88 549ea7f211bSAhmed Taei // Note: |k| = 127 is the value where the 8-bits exponent saturates. 550ea7f211bSAhmed Taei Value zerof32Const = bcast(f32Cst(builder, 0)); 551ea7f211bSAhmed Taei auto constPosInfinity = 552ea7f211bSAhmed Taei bcast(f32Cst(builder, std::numeric_limits<float>::infinity())); 553ea7f211bSAhmed Taei auto constNegIfinity = 554ea7f211bSAhmed Taei bcast(f32Cst(builder, -std::numeric_limits<float>::infinity())); 555ea7f211bSAhmed Taei auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min())); 556ea7f211bSAhmed Taei 557ea7f211bSAhmed Taei Value kMaxConst = bcast(i32Cst(builder, 127)); 558ea7f211bSAhmed Taei Value kMaxNegConst = bcast(i32Cst(builder, -127)); 559ea7f211bSAhmed Taei Value rightBound = builder.create<CmpIOp>(CmpIPredicate::sle, k, kMaxConst); 560ea7f211bSAhmed Taei Value leftBound = builder.create<CmpIOp>(CmpIPredicate::sge, k, kMaxNegConst); 561ea7f211bSAhmed Taei 562ea7f211bSAhmed Taei Value isNegInfinityX = 563ea7f211bSAhmed Taei builder.create<CmpFOp>(CmpFPredicate::OEQ, x, constNegIfinity); 564ea7f211bSAhmed Taei Value isPostiveX = 565ea7f211bSAhmed Taei builder.create<CmpFOp>(CmpFPredicate::OGT, x, zerof32Const); 566ea7f211bSAhmed Taei Value isComputable = builder.create<AndOp>(rightBound, leftBound); 567ea7f211bSAhmed Taei 568ea7f211bSAhmed Taei expY = builder.create<SelectOp>( 569ea7f211bSAhmed Taei isComputable, expY, 570ea7f211bSAhmed Taei builder.create<SelectOp>( 571ea7f211bSAhmed Taei isPostiveX, constPosInfinity, 572ea7f211bSAhmed Taei builder.create<SelectOp>(isNegInfinityX, zerof32Const, underflow))); 573ea7f211bSAhmed Taei 574ea7f211bSAhmed Taei rewriter.replaceOp(op, expY); 575ea7f211bSAhmed Taei 576ea7f211bSAhmed Taei return success(); 577ea7f211bSAhmed Taei } 578ea7f211bSAhmed Taei 579ea7f211bSAhmed Taei //----------------------------------------------------------------------------// 5800edc4bc8SEmilio Cota // ExpM1 approximation. 5810edc4bc8SEmilio Cota //----------------------------------------------------------------------------// 5820edc4bc8SEmilio Cota 5830edc4bc8SEmilio Cota namespace { 5840edc4bc8SEmilio Cota 5850edc4bc8SEmilio Cota struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> { 5860edc4bc8SEmilio Cota public: 5870edc4bc8SEmilio Cota using OpRewritePattern::OpRewritePattern; 5880edc4bc8SEmilio Cota 5890edc4bc8SEmilio Cota LogicalResult matchAndRewrite(math::ExpM1Op op, 5900edc4bc8SEmilio Cota PatternRewriter &rewriter) const final; 5910edc4bc8SEmilio Cota }; 5920edc4bc8SEmilio Cota } // namespace 5930edc4bc8SEmilio Cota 5940edc4bc8SEmilio Cota LogicalResult 5950edc4bc8SEmilio Cota ExpM1Approximation::matchAndRewrite(math::ExpM1Op op, 5960edc4bc8SEmilio Cota PatternRewriter &rewriter) const { 5970edc4bc8SEmilio Cota auto width = vectorWidth(op.operand().getType(), isF32); 5980edc4bc8SEmilio Cota if (!width.hasValue()) 5990edc4bc8SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type"); 6000edc4bc8SEmilio Cota 6010edc4bc8SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 6020edc4bc8SEmilio Cota auto bcast = [&](Value value) -> Value { 6030edc4bc8SEmilio Cota return broadcast(builder, value, *width); 6040edc4bc8SEmilio Cota }; 6050edc4bc8SEmilio Cota 6060edc4bc8SEmilio Cota // expm1(x) = exp(x) - 1 = u - 1. 6070edc4bc8SEmilio Cota // We have to handle it carefully when x is near 0, i.e. u ~= 1, 6080edc4bc8SEmilio Cota // and when the input is ~= -inf, i.e. u - 1 ~= -1. 6090edc4bc8SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f)); 6100edc4bc8SEmilio Cota Value cstNegOne = bcast(f32Cst(builder, -1.0f)); 6110edc4bc8SEmilio Cota Value x = op.operand(); 6120edc4bc8SEmilio Cota Value u = builder.create<math::ExpOp>(x); 6130edc4bc8SEmilio Cota Value uEqOne = builder.create<CmpFOp>(CmpFPredicate::OEQ, u, cstOne); 6140edc4bc8SEmilio Cota Value uMinusOne = builder.create<SubFOp>(u, cstOne); 6150edc4bc8SEmilio Cota Value uMinusOneEqNegOne = 6160edc4bc8SEmilio Cota builder.create<CmpFOp>(CmpFPredicate::OEQ, uMinusOne, cstNegOne); 6170edc4bc8SEmilio Cota // logU = log(u) ~= x 6180edc4bc8SEmilio Cota Value logU = builder.create<math::LogOp>(u); 6190edc4bc8SEmilio Cota 6200edc4bc8SEmilio Cota // Detect exp(x) = +inf; written this way to avoid having to form +inf. 6210edc4bc8SEmilio Cota Value isInf = builder.create<CmpFOp>(CmpFPredicate::OEQ, logU, u); 6220edc4bc8SEmilio Cota 6230edc4bc8SEmilio Cota // (u - 1) * (x / ~x) 6240edc4bc8SEmilio Cota Value expm1 = 6250edc4bc8SEmilio Cota builder.create<MulFOp>(uMinusOne, builder.create<DivFOp>(x, logU)); 6260edc4bc8SEmilio Cota expm1 = builder.create<SelectOp>(isInf, u, expm1); 6270edc4bc8SEmilio Cota Value approximation = builder.create<SelectOp>( 6280edc4bc8SEmilio Cota uEqOne, x, builder.create<SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1)); 6290edc4bc8SEmilio Cota rewriter.replaceOp(op, approximation); 6300edc4bc8SEmilio Cota return success(); 6310edc4bc8SEmilio Cota } 6320edc4bc8SEmilio Cota 6330edc4bc8SEmilio Cota //----------------------------------------------------------------------------// 634*7e2d672aSAhmed S. Taei // Sin and Cos approximation. 635*7e2d672aSAhmed S. Taei //----------------------------------------------------------------------------// 636*7e2d672aSAhmed S. Taei 637*7e2d672aSAhmed S. Taei namespace { 638*7e2d672aSAhmed S. Taei 639*7e2d672aSAhmed S. Taei template <bool isSine, typename OpTy> 640*7e2d672aSAhmed S. Taei struct SinAndCosApproximation : public OpRewritePattern<OpTy> { 641*7e2d672aSAhmed S. Taei public: 642*7e2d672aSAhmed S. Taei using OpRewritePattern<OpTy>::OpRewritePattern; 643*7e2d672aSAhmed S. Taei 644*7e2d672aSAhmed S. Taei LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final; 645*7e2d672aSAhmed S. Taei }; 646*7e2d672aSAhmed S. Taei } // namespace 647*7e2d672aSAhmed S. Taei 648*7e2d672aSAhmed S. Taei #define TWO_OVER_PI \ 649*7e2d672aSAhmed S. Taei 0.6366197723675813430755350534900574481378385829618257949906693762L 650*7e2d672aSAhmed S. Taei #define PI_OVER_2 \ 651*7e2d672aSAhmed S. Taei 1.5707963267948966192313216916397514420985846996875529104874722961L 652*7e2d672aSAhmed S. Taei 653*7e2d672aSAhmed S. Taei // Approximates sin(x) or cos(x) by finding the best approximation polynomial in 654*7e2d672aSAhmed S. Taei // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the 655*7e2d672aSAhmed S. Taei // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y). 656*7e2d672aSAhmed S. Taei template <bool isSine, typename OpTy> 657*7e2d672aSAhmed S. Taei LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite( 658*7e2d672aSAhmed S. Taei OpTy op, PatternRewriter &rewriter) const { 659*7e2d672aSAhmed S. Taei static_assert( 660*7e2d672aSAhmed S. Taei llvm::is_one_of<OpTy, math::SinOp, math::CosOp>::value, 661*7e2d672aSAhmed S. Taei "SinAndCosApproximation pattern expects math::SinOp or math::CosOp"); 662*7e2d672aSAhmed S. Taei auto width = vectorWidth(op.operand().getType(), isF32); 663*7e2d672aSAhmed S. Taei if (!width.hasValue()) 664*7e2d672aSAhmed S. Taei return rewriter.notifyMatchFailure(op, "unsupported operand type"); 665*7e2d672aSAhmed S. Taei 666*7e2d672aSAhmed S. Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 667*7e2d672aSAhmed S. Taei auto bcast = [&](Value value) -> Value { 668*7e2d672aSAhmed S. Taei return broadcast(builder, value, *width); 669*7e2d672aSAhmed S. Taei }; 670*7e2d672aSAhmed S. Taei auto mul = [&](Value a, Value b) -> Value { 671*7e2d672aSAhmed S. Taei return builder.create<MulFOp>(a, b); 672*7e2d672aSAhmed S. Taei }; 673*7e2d672aSAhmed S. Taei auto sub = [&](Value a, Value b) -> Value { 674*7e2d672aSAhmed S. Taei return builder.create<SubFOp>(a, b); 675*7e2d672aSAhmed S. Taei }; 676*7e2d672aSAhmed S. Taei auto floor = [&](Value a) { return builder.create<FloorFOp>(a); }; 677*7e2d672aSAhmed S. Taei 678*7e2d672aSAhmed S. Taei auto i32Vec = broadcast(builder.getI32Type(), *width); 679*7e2d672aSAhmed S. Taei auto fPToSingedInteger = [&](Value a) -> Value { 680*7e2d672aSAhmed S. Taei return builder.create<FPToSIOp>(a, i32Vec); 681*7e2d672aSAhmed S. Taei }; 682*7e2d672aSAhmed S. Taei 683*7e2d672aSAhmed S. Taei auto modulo4 = [&](Value a) -> Value { 684*7e2d672aSAhmed S. Taei return builder.create<AndOp>(a, bcast(i32Cst(builder, 3))); 685*7e2d672aSAhmed S. Taei }; 686*7e2d672aSAhmed S. Taei 687*7e2d672aSAhmed S. Taei auto isEqualTo = [&](Value a, Value b) -> Value { 688*7e2d672aSAhmed S. Taei return builder.create<CmpIOp>(CmpIPredicate::eq, a, b); 689*7e2d672aSAhmed S. Taei }; 690*7e2d672aSAhmed S. Taei 691*7e2d672aSAhmed S. Taei auto isGreaterThan = [&](Value a, Value b) -> Value { 692*7e2d672aSAhmed S. Taei return builder.create<CmpIOp>(CmpIPredicate::sgt, a, b); 693*7e2d672aSAhmed S. Taei }; 694*7e2d672aSAhmed S. Taei 695*7e2d672aSAhmed S. Taei auto select = [&](Value cond, Value t, Value f) -> Value { 696*7e2d672aSAhmed S. Taei return builder.create<SelectOp>(cond, t, f); 697*7e2d672aSAhmed S. Taei }; 698*7e2d672aSAhmed S. Taei 699*7e2d672aSAhmed S. Taei auto fmla = [&](Value a, Value b, Value c) { 700*7e2d672aSAhmed S. Taei return builder.create<FmaFOp>(a, b, c); 701*7e2d672aSAhmed S. Taei }; 702*7e2d672aSAhmed S. Taei 703*7e2d672aSAhmed S. Taei auto bitwiseOr = [&](Value a, Value b) { return builder.create<OrOp>(a, b); }; 704*7e2d672aSAhmed S. Taei 705*7e2d672aSAhmed S. Taei Value twoOverPi = bcast(f32Cst(builder, TWO_OVER_PI)); 706*7e2d672aSAhmed S. Taei Value piOverTwo = bcast(f32Cst(builder, PI_OVER_2)); 707*7e2d672aSAhmed S. Taei 708*7e2d672aSAhmed S. Taei Value x = op.operand(); 709*7e2d672aSAhmed S. Taei 710*7e2d672aSAhmed S. Taei Value k = floor(mul(x, twoOverPi)); 711*7e2d672aSAhmed S. Taei 712*7e2d672aSAhmed S. Taei Value y = sub(x, mul(k, piOverTwo)); 713*7e2d672aSAhmed S. Taei 714*7e2d672aSAhmed S. Taei Value cstOne = bcast(f32Cst(builder, 1.0)); 715*7e2d672aSAhmed S. Taei Value cstNegativeOne = bcast(f32Cst(builder, -1.0)); 716*7e2d672aSAhmed S. Taei 717*7e2d672aSAhmed S. Taei Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f)); 718*7e2d672aSAhmed S. Taei Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f)); 719*7e2d672aSAhmed S. Taei Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f)); 720*7e2d672aSAhmed S. Taei Value cstSC8 = 721*7e2d672aSAhmed S. Taei bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f)); 722*7e2d672aSAhmed S. Taei Value cstSC10 = 723*7e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f)); 724*7e2d672aSAhmed S. Taei 725*7e2d672aSAhmed S. Taei Value cstCC2 = bcast(f32Cst(builder, -0.5f)); 726*7e2d672aSAhmed S. Taei Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f)); 727*7e2d672aSAhmed S. Taei Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f)); 728*7e2d672aSAhmed S. Taei Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f)); 729*7e2d672aSAhmed S. Taei Value cstCC10 = 730*7e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f)); 731*7e2d672aSAhmed S. Taei 732*7e2d672aSAhmed S. Taei Value kMod4 = modulo4(fPToSingedInteger(k)); 733*7e2d672aSAhmed S. Taei 734*7e2d672aSAhmed S. Taei Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0))); 735*7e2d672aSAhmed S. Taei Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1))); 736*7e2d672aSAhmed S. Taei Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2))); 737*7e2d672aSAhmed S. Taei Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3))); 738*7e2d672aSAhmed S. Taei 739*7e2d672aSAhmed S. Taei Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2); 740*7e2d672aSAhmed S. Taei Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1))) 741*7e2d672aSAhmed S. Taei : bitwiseOr(kR1, kR2); 742*7e2d672aSAhmed S. Taei 743*7e2d672aSAhmed S. Taei Value y2 = mul(y, y); 744*7e2d672aSAhmed S. Taei 745*7e2d672aSAhmed S. Taei Value base = select(sinuseCos, cstOne, y); 746*7e2d672aSAhmed S. Taei Value cstC2 = select(sinuseCos, cstCC2, cstSC2); 747*7e2d672aSAhmed S. Taei Value cstC4 = select(sinuseCos, cstCC4, cstSC4); 748*7e2d672aSAhmed S. Taei Value cstC6 = select(sinuseCos, cstCC6, cstSC6); 749*7e2d672aSAhmed S. Taei Value cstC8 = select(sinuseCos, cstCC8, cstSC8); 750*7e2d672aSAhmed S. Taei Value cstC10 = select(sinuseCos, cstCC10, cstSC10); 751*7e2d672aSAhmed S. Taei 752*7e2d672aSAhmed S. Taei Value v1 = fmla(y2, cstC10, cstC8); 753*7e2d672aSAhmed S. Taei Value v2 = fmla(y2, v1, cstC6); 754*7e2d672aSAhmed S. Taei Value v3 = fmla(y2, v2, cstC4); 755*7e2d672aSAhmed S. Taei Value v4 = fmla(y2, v3, cstC2); 756*7e2d672aSAhmed S. Taei Value v5 = fmla(y2, v4, cstOne); 757*7e2d672aSAhmed S. Taei Value v6 = mul(base, v5); 758*7e2d672aSAhmed S. Taei 759*7e2d672aSAhmed S. Taei Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6); 760*7e2d672aSAhmed S. Taei 761*7e2d672aSAhmed S. Taei rewriter.replaceOp(op, approximation); 762*7e2d672aSAhmed S. Taei 763*7e2d672aSAhmed S. Taei return success(); 764*7e2d672aSAhmed S. Taei } 765*7e2d672aSAhmed S. Taei 766*7e2d672aSAhmed S. Taei //----------------------------------------------------------------------------// 767f99ccf65SEugene Zhulenev 768f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns( 769dc4e913bSChris Lattner RewritePatternSet &patterns) { 770dc4e913bSChris Lattner patterns.add<TanhApproximation, LogApproximation, Log2Approximation, 771*7e2d672aSAhmed S. Taei Log1pApproximation, ExpApproximation, ExpM1Approximation, 772*7e2d672aSAhmed S. Taei SinAndCosApproximation<true, math::SinOp>, 773*7e2d672aSAhmed S. Taei SinAndCosApproximation<false, math::CosOp>>( 7740edc4bc8SEmilio Cota patterns.getContext()); 775f99ccf65SEugene Zhulenev } 776