29#define GEN_PASS_DEF_CONVERTMATHTONVVM
30#include "mlir/Conversion/Passes.h.inc"
35#define DEBUG_TYPE "math-to-nvvm"
37template <
typename OpTy>
41 StringRef f64Func, StringRef f32ApproxFunc =
"",
42 StringRef f16Func =
"") {
45 f32ApproxFunc, f16Func,
49template <
typename OpTy>
63 return type && type.getWidth() <= 32;
67struct FPowIScalarizeLowering
69 using ScalarizeVectorOpLowering::ScalarizeVectorOpLowering;
72 matchAndRewrite(math::FPowIOp op, OpAdaptor adaptor,
73 ConversionPatternRewriter &rewriter)
const override {
75 return rewriter.notifyMatchFailure(op,
"exponent does not fit in i32");
84 matchAndRewrite(math::FPowIOp op, OpAdaptor adaptor,
85 ConversionPatternRewriter &rewriter)
const override {
87 return rewriter.notifyMatchFailure(op,
"exponent does not fit in i32");
90 if (!op->getParentOfType<FunctionOpInterface>() ||
91 !isa<Float16Type, BFloat16Type, Float32Type, Float64Type>(
92 adaptor.getLhs().getType()))
93 return rewriter.notifyMatchFailure(op,
"cannot be lowered to libdevice");
95 Value exponent = adaptor.getRhs();
97 exponent = LLVM::SExtOp::create(rewriter, op.getLoc(),
98 rewriter.getI32Type(), exponent);
99 Value operands[] = {adaptor.getLhs(), exponent};
101 op, OpAdaptor(
ValueRange(operands), op), rewriter);
112 ConversionPatternRewriter &rewriter)
const override {
114 Value input = adaptor.getOperand();
116 auto convertedInput = maybeExt(input, rewriter);
117 auto computeType = convertedInput.getType();
119 StringRef sincosFunc;
120 if (isa<Float32Type>(computeType)) {
121 const arith::FastMathFlags flag = op.getFastmath();
122 const bool useApprox =
123 mlir::arith::bitEnumContainsAny(flag, arith::FastMathFlags::afn);
124 sincosFunc = useApprox ?
"__nv_fast_sincosf" :
"__nv_sincosf";
125 }
else if (isa<Float64Type>(computeType)) {
126 sincosFunc =
"__nv_sincos";
128 return rewriter.notifyMatchFailure(op,
129 "unsupported operand type for sincos");
132 auto ptrType = LLVM::LLVMPointerType::get(rewriter.getContext());
134 Value sinPtr, cosPtr;
139 assert(scope &&
"Expected op to be inside automatic allocation scope");
140 rewriter.setInsertionPointToStart(&scope->getRegion(0).front());
141 auto one = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(),
142 rewriter.getI32IntegerAttr(1));
144 LLVM::AllocaOp::create(rewriter, loc, ptrType, computeType, one, 0);
146 LLVM::AllocaOp::create(rewriter, loc, ptrType, computeType, one, 0);
149 createSincosCall(rewriter, loc, sincosFunc, convertedInput, sinPtr, cosPtr,
152 auto sinResult = LLVM::LoadOp::create(rewriter, loc, computeType, sinPtr);
153 auto cosResult = LLVM::LoadOp::create(rewriter, loc, computeType, cosPtr);
155 rewriter.replaceOp(op, {maybeTrunc(sinResult, inputType, rewriter),
156 maybeTrunc(cosResult, inputType, rewriter)});
162 if (isa<Float16Type, BFloat16Type>(operand.
getType()))
163 return LLVM::FPExtOp::create(rewriter, operand.
getLoc(),
169 Value maybeTrunc(Value operand, Type type, PatternRewriter &rewriter)
const {
171 return LLVM::FPTruncOp::create(rewriter, operand.
getLoc(), type, operand);
175 void createSincosCall(ConversionPatternRewriter &rewriter, Location loc,
176 StringRef funcName, Value input, Value sinPtr,
177 Value cosPtr, Operation *op)
const {
178 auto voidType = LLVM::LLVMVoidType::get(rewriter.getContext());
179 auto ptrType = sinPtr.
getType();
181 SmallVector<Type> operandTypes = {input.
getType(), ptrType, ptrType};
182 auto funcType = LLVM::LLVMFunctionType::get(voidType, operandTypes);
184 auto funcAttr = StringAttr::get(op->
getContext(), funcName);
190 assert(parentFunc &&
"expected there to be a parent function");
191 OpBuilder
b(parentFunc);
194 funcOp = LLVM::LLVMFuncOp::create(
b, globalloc, funcName, funcType);
197 SmallVector<Value> callOperands = {input, sinPtr, cosPtr};
198 LLVM::CallOp::create(rewriter, loc, funcOp, callOperands);
208 "__nv_fmaxf",
"__nv_fmax");
210 "__nv_fminf",
"__nv_fmin");
234 "__nv_copysignf",
"__nv_copysign");
236 "__nv_cos",
"__nv_fast_cosf");
244 "__nv_exp",
"__nv_fast_expf");
255 "__nv_finitef",
"__nv_isfinited");
261 "__nv_log",
"__nv_fast_logf");
263 "__nv_log10",
"__nv_fast_log10f");
267 "__nv_log2",
"__nv_fast_log2f");
269 "__nv_pow",
"__nv_fast_powf");
270 patterns.
add<FPowIScalarizeLowering>(converter, benefit);
271 patterns.
add<FPowIOpLowering>(converter,
"__nv_powif",
"__nv_powi",
"",
"",
276 "__nv_rintf",
"__nv_rint");
280 "__nv_sin",
"__nv_fast_sinf");
286 "__nv_tan",
"__nv_fast_tanf");
295struct ConvertMathToNVVMPass final
298 ConvertMathToNVVMPass>::ConvertMathToNVVMBase;
300 void runOnOperation()
override;
304void ConvertMathToNVVMPass::runOnOperation() {
305 auto m = getOperation();
306 MLIRContext *ctx = m.getContext();
309 LowerToLLVMOptions
options(ctx, DataLayout(m));
310 LLVMTypeConverter converter(ctx,
options);
316 .addLegalDialect<BuiltinDialect, func::FuncDialect, vector::VectorDialect,
317 LLVM::LLVMDialect, NVVM::NVVMDialect>();
318 target.addIllegalOp<LLVM::CosOp, LLVM::ExpOp, LLVM::Exp2Op, LLVM::FAbsOp,
319 LLVM::FCeilOp, LLVM::FFloorOp, LLVM::FRemOp, LLVM::LogOp,
320 LLVM::Log10Op, LLVM::Log2Op, LLVM::PowOp, LLVM::SinOp,
322 if (
failed(applyPartialConversion(m,
target, std::move(patterns))))
static bool exponentFitsInI32(math::FPowIOp op)
libdevice's __nv_powi and __nv_powif take an i32 exponent, so math.fpowi with a wider or index expone...
static void populateOpPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit, StringRef f32Func, StringRef f64Func, StringRef f32ApproxFunc="", StringRef f16Func="")
static void populateIntOpPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit, StringRef i32Func)
static llvm::ManagedStatic< PassManagerOptions > options
MLIRContext * getContext() const
ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
typename math::SincosOp::Adaptor OpAdaptor
Conversion from types to the LLVM IR dialect.
LocationAttr findInstanceOfOrUnknown()
Return an instance of the given location type if one is nested under the current location else return...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
RAII guard to reset the insertion point of the builder when destroyed.
A trait of region holding operations that define a new scope for automatic allocations,...
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
MLIRContext * getContext()
Return the context this operation is associated with.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isInteger() const
Return true if this is an integer type (with the specified width).
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Location getLoc() const
Return the location of this value.
Include the generated interface declarations.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void populateLibDeviceConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate the given list with patterns that convert from Math to NVVM libdevice calls.
LogicalResult matchAndRewrite(math::SincosOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
Rewriting that replaces SourceOp with a CallOp to f32Func or f64Func or f32ApproxFunc or f16Func or i...
OpToFuncCallLowering(const LLVMTypeConverter &lowering, StringRef f32Func, StringRef f64Func, StringRef f32ApproxFunc, StringRef f16Func, StringRef i32Func="", PatternBenefit benefit=1, LLVM::cconv::CConv cconv=LLVM::cconv::CConv::C)
LogicalResult matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor, ConversionPatternRewriter &rewriter) const override
Methods that operate on the SourceOp type.
Unrolls SourceOp to array/vector elements.
LogicalResult matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor, ConversionPatternRewriter &rewriter) const override
Methods that operate on the SourceOp type.