23#include "llvm/Support/FormatVariadic.h"
29#define GEN_PASS_DEF_CONVERTMATHTOXEVM
30#include "mlir/Conversion/Passes.h.inc"
35#define DEBUG_TYPE "math-to-xevm"
38 auto vecType = dyn_cast<VectorType>(type);
39 return vecType && vecType.getShape().size() == 1 &&
40 vecType.getShape()[0] == 1 && vecType.getElementType().isFloat();
46 if (
auto vecType = dyn_cast<VectorType>(type)) {
47 if (!vecType.getElementType().isFloat())
52 if (
shape.size() != 1)
76 std::string mangledFuncName =
79 auto appendFloatToMangledFunc = [&mangledFuncName](
Type type) {
81 mangledFuncName +=
"f";
82 else if (type.isF16())
83 mangledFuncName +=
"Dh";
84 else if (type.isF64())
85 mangledFuncName +=
"d";
88 for (
auto type : operandTypes) {
89 if (
auto vecType = dyn_cast<VectorType>(type)) {
90 mangledFuncName +=
"Dv" + std::to_string(vecType.getShape()[0]) +
"_";
91 appendFloatToMangledFunc(vecType.getElementType());
93 appendFloatToMangledFunc(type);
96 return mangledFuncName;
101 ConversionPatternRewriter &rewriter)
const override {
105 arith::FastMathFlags fastFlags = op.getFastmath();
106 if (!arith::bitEnumContainsAll(fastFlags, arith::FastMathFlags::afn))
107 return rewriter.notifyMatchFailure(op,
"not a fastmath `afn` operation");
118 for (
Value &operand : operands) {
119 Type opTy = operand.getType();
124 return rewriter.notifyMatchFailure(
125 op, llvm::formatv(
"incompatible operand type: '{0}'", opTy));
126 if (unwrapSizeOneVec) {
128 "expected all operands to be size-1 vectors");
129 opTy = cast<VectorType>(opTy).getElementType();
130 operand = vector::ExtractOp::create(rewriter, loc, operand,
133 operandTypes.push_back(opTy);
136 Type resultType = unwrapSizeOneVec
137 ? cast<VectorType>(op.getType()).getElementType()
140 auto moduleOp = op->template getParentWithTrait<OpTrait::SymbolTable>();
143 operandTypes, resultType);
144 assert(!failed(funcOpRes));
145 LLVM::LLVMFuncOp funcOp = funcOpRes.value();
147 auto callOp = LLVM::CallOp::create(rewriter, loc, funcOp, operands);
152 callOp.setFastmathFlagsAttr(
156 if (unwrapSizeOneVec) {
158 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(op, op.getType(),
161 rewriter.replaceOp(op, callOp);
169template <
typename OpTy>
174 std::string prefix =
"__spirv_ocl_";
175 std::string mangledName =
"_Z" +
176 std::to_string(prefix.size() + opName.size()) +
177 prefix + opName.str();
181 converter, mangledName +
"f", mangledName +
"d",
183 "", benefit, LLVM::cconv::CConv::SPIR_FUNC);
243 patterns.
getContext(),
"__spirv_ocl_native_exp", benefit);
245 patterns.
getContext(),
"__spirv_ocl_native_cos", benefit);
247 patterns.
getContext(),
"__spirv_ocl_native_exp2", benefit);
249 patterns.
getContext(),
"__spirv_ocl_native_log", benefit);
251 patterns.
getContext(),
"__spirv_ocl_native_log2", benefit);
253 patterns.
getContext(),
"__spirv_ocl_native_log10", benefit);
255 patterns.
getContext(),
"__spirv_ocl_native_powr", benefit);
257 patterns.
getContext(),
"__spirv_ocl_native_rsqrt", benefit);
259 patterns.
getContext(),
"__spirv_ocl_native_sin", benefit);
261 patterns.
getContext(),
"__spirv_ocl_native_sqrt", benefit);
263 patterns.
getContext(),
"__spirv_ocl_native_tan", benefit);
266 patterns.
getContext(),
"__spirv_ocl_native_divide", benefit);
270struct ConvertMathToXeVMPass
271 :
public impl::ConvertMathToXeVMBase<ConvertMathToXeVMPass> {
273 void runOnOperation()
override;
277void ConvertMathToXeVMPass::runOnOperation() {
278 Operation *op = getOperation();
287 RewritePatternSet simplifications(ctx);
289 FrozenRewritePatternSet frozen(std::move(simplifications));
290 SmallVector<Operation *> candidates;
291 op->
walk([&](Operation *nested) {
292 if (frozen.getOpSpecificNativePatterns().contains(nested->
getName()))
293 candidates.push_back(nested);
295 GreedyRewriteConfig config;
298 return signalPassFailure();
301 const auto &dl = getAnalysis<DataLayoutAnalysis>();
304 LowerToLLVMOptions
options(ctx, dl.getAtOrAbove(op));
305 LLVMTypeConverter converter(ctx,
options);
311 constexpr unsigned oclBenefit = 1;
317 .addIllegalOp<LLVM::CosOp, LLVM::ExpOp, LLVM::Exp2Op, LLVM::LogOp,
318 LLVM::Log10Op, LLVM::Log2Op, LLVM::SinOp, LLVM::SqrtOp>();
320 target.addLegalDialect<BuiltinDialect, LLVM::LLVMDialect>();
324 target.addLegalOp<vector::ExtractOp, vector::BroadcastOp>();
326 applyPartialConversion(getOperation(),
target, std::move(patterns))))
static bool isSizeOneVector(Type type)
static bool isSPIRVCompatibleFloatOrVec(Type type)
static void populateOCLExtSetOpPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit, StringRef opName)
static llvm::ManagedStatic< PassManagerOptions > options
GreedyRewriteConfig & enableFolding(bool enable=true)
Conversion from types to the LLVM IR dialect.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
Location getLoc()
The source location the operation was defined or derived from.
This provides public APIs that all operations should have.
OperationName getName()
The name of an operation is the key identifier for it.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
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...
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isFloat() const
Return true if this is an float type (with the specified width).
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
TargetOp::Properties getProperties() const
ArrayRef< NamedAttribute > getDiscardableAttrs() const
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateFn(OpBuilder &b, Operation *moduleOp, StringRef name, ArrayRef< Type > paramTypes={}, Type resultType={}, bool isVarArg=false, bool isReserved=false, SymbolTableCollection *symbolTables=nullptr)
Create a FuncOp with signature resultType(paramTypes) and name name`.
Include the generated interface declarations.
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
void populateMathAlgebraicSimplificationPatterns(RewritePatternSet &patterns)
void populateMathToScalarOCLExtSetConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate the given list with patterns that convert from Math to OCL LLVM-SPV builtin calls.
void populateMathToXeVMConversionPatterns(RewritePatternSet &patterns, bool convertArith, PatternBenefit benefit=1)
Populate the given list with patterns that convert from Math to XeVM calls.
Convert math ops marked with fast (afn) to native OpenCL intrinsics.
const StringRef nativeFunc
ConvertNativeFuncPattern(MLIRContext *context, StringRef nativeFunc, PatternBenefit benefit=1)
std::string getMangledNativeFuncName(const ArrayRef< Type > operandTypes) const
LogicalResult matchAndRewrite(Op op, typename Op::Adaptor adaptor, ConversionPatternRewriter &rewriter) const override
Rewriting that replaces SourceOp with a CallOp to f32Func or f64Func or f32ApproxFunc or f16Func or i...
Unrolls SourceOp to array/vector elements.