MLIR 24.0.0git
MathToXeVM.cpp
Go to the documentation of this file.
1//===-- MathToXeVM.cpp - conversion from Math to XeVM ---------------------===//
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
21#include "mlir/Pass/Pass.h"
23#include "llvm/Support/FormatVariadic.h"
24
27
28namespace mlir {
29#define GEN_PASS_DEF_CONVERTMATHTOXEVM
30#include "mlir/Conversion/Passes.h.inc"
31} // namespace mlir
32
33using namespace mlir;
34
35#define DEBUG_TYPE "math-to-xevm"
36
37static bool isSizeOneVector(Type type) {
38 auto vecType = dyn_cast<VectorType>(type);
39 return vecType && vecType.getShape().size() == 1 &&
40 vecType.getShape()[0] == 1 && vecType.getElementType().isFloat();
41}
42
44 if (type.isFloat())
45 return true;
46 if (auto vecType = dyn_cast<VectorType>(type)) {
47 if (!vecType.getElementType().isFloat())
48 return false;
49 // SPIRV distinguishes between vectors and matrices: OpenCL native math
50 // intrsinics are not compatible with matrices.
51 ArrayRef<int64_t> shape = vecType.getShape();
52 if (shape.size() != 1)
53 return false;
54 // SPIRV has no size-1 vector type; such degenerate vectors are handled
55 // by unwrapping to the scalar intrinsic (see matchAndRewrite).
56 if (shape[0] == 1)
57 return true;
58 // SPIRV only allows vectors of size 2, 3, 4, 8, 16.
59 if (shape[0] == 2 || shape[0] == 3 || shape[0] == 4 || shape[0] == 8 ||
60 shape[0] == 16)
61 return true;
62 }
63 return false;
64}
65
66/// Convert math ops marked with `fast` (`afn`) to native OpenCL intrinsics.
67template <typename Op>
68struct ConvertNativeFuncPattern final : public OpConversionPattern<Op> {
69
71 PatternBenefit benefit = 1)
72 : OpConversionPattern<Op>(context, benefit), nativeFunc(nativeFunc) {}
73
74 inline std::string
75 getMangledNativeFuncName(const ArrayRef<Type> operandTypes) const {
76 std::string mangledFuncName =
77 "_Z" + std::to_string(nativeFunc.size()) + nativeFunc.str();
78
79 auto appendFloatToMangledFunc = [&mangledFuncName](Type type) {
80 if (type.isF32())
81 mangledFuncName += "f";
82 else if (type.isF16())
83 mangledFuncName += "Dh";
84 else if (type.isF64())
85 mangledFuncName += "d";
86 };
87
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());
92 } else
93 appendFloatToMangledFunc(type);
94 }
95
96 return mangledFuncName;
97 }
98
99 LogicalResult
100 matchAndRewrite(Op op, typename Op::Adaptor adaptor,
101 ConversionPatternRewriter &rewriter) const override {
102 if (!isSPIRVCompatibleFloatOrVec(op.getType()))
103 return failure();
104
105 arith::FastMathFlags fastFlags = op.getFastmath();
106 if (!arith::bitEnumContainsAll(fastFlags, arith::FastMathFlags::afn))
107 return rewriter.notifyMatchFailure(op, "not a fastmath `afn` operation");
108
109 Location loc = op.getLoc();
110
111 // SPIRV has no size-1 vector type: such vectors are the degenerate result
112 // of distributing/linearizing larger vectors down to a single element (e.g.
113 // by the XeGPU lowering pipeline). They have no OpenCL vector intrinsic, so
114 // unwrap them to the scalar element type and use the scalar intrinsic.
115 SmallVector<Value, 1> operands(adaptor.getOperands());
116 SmallVector<Type, 1> operandTypes;
117 bool unwrapSizeOneVec = isSizeOneVector(op.getType());
118 for (Value &operand : operands) {
119 Type opTy = operand.getType();
120 // This pass only supports operations on vectors that are already in SPIRV
121 // supported vector sizes: Distributing unsupported vector sizes to SPIRV
122 // supported vector sizes are done in other blocking optimization passes.
124 return rewriter.notifyMatchFailure(
125 op, llvm::formatv("incompatible operand type: '{0}'", opTy));
126 if (unwrapSizeOneVec) {
127 assert(isSizeOneVector(opTy) &&
128 "expected all operands to be size-1 vectors");
129 opTy = cast<VectorType>(opTy).getElementType();
130 operand = vector::ExtractOp::create(rewriter, loc, operand,
132 }
133 operandTypes.push_back(opTy);
134 }
135
136 Type resultType = unwrapSizeOneVec
137 ? cast<VectorType>(op.getType()).getElementType()
138 : op.getType();
139
140 auto moduleOp = op->template getParentWithTrait<OpTrait::SymbolTable>();
141 auto funcOpRes = LLVM::lookupOrCreateFn(
142 rewriter, moduleOp, getMangledNativeFuncName(operandTypes),
143 operandTypes, resultType);
144 assert(!failed(funcOpRes));
145 LLVM::LLVMFuncOp funcOp = funcOpRes.value();
146
147 auto callOp = LLVM::CallOp::create(rewriter, loc, funcOp, operands);
148 // Preserve fastmath flags in our MLIR op when converting to llvm function
149 // calls, in order to allow further fastmath optimizations: We thus need to
150 // convert arith fastmath attrs into attrs recognized by llvm.
152 callOp.setFastmathFlagsAttr(
153 fastAttrConverter.getProperties().getFastmathFlags());
154 callOp->setDiscardableAttrs(fastAttrConverter.getDiscardableAttrs());
155
156 if (unwrapSizeOneVec) {
157 // Re-wrap the scalar result back into a size-1 vector to preserve types.
158 rewriter.replaceOpWithNewOp<vector::BroadcastOp>(op, op.getType(),
159 callOp.getResult());
160 } else {
161 rewriter.replaceOp(op, callOp);
162 }
163 return success();
164 }
165
166 const StringRef nativeFunc;
167};
168
169template <typename OpTy>
171 RewritePatternSet &patterns,
172 PatternBenefit benefit,
173 StringRef opName) {
174 std::string prefix = "__spirv_ocl_";
175 std::string mangledName = "_Z" +
176 std::to_string(prefix.size() + opName.size()) +
177 prefix + opName.str();
178
179 patterns.add<ScalarizeVectorOpLowering<OpTy>>(converter, benefit);
181 converter, mangledName + "f", mangledName + "d",
182 /*f32ApproxFunc=*/"", /*f16Func=*/"",
183 /*i32Func=*/"", benefit, LLVM::cconv::CConv::SPIR_FUNC);
184}
185
187 const LLVMTypeConverter &converter, RewritePatternSet &patterns,
188 PatternBenefit benefit) {
189 populateOCLExtSetOpPatterns<math::AcosOp>(converter, patterns, benefit,
190 "acos");
191 populateOCLExtSetOpPatterns<math::AcoshOp>(converter, patterns, benefit,
192 "acosh");
193 populateOCLExtSetOpPatterns<math::AsinOp>(converter, patterns, benefit,
194 "asin");
195 populateOCLExtSetOpPatterns<math::AsinhOp>(converter, patterns, benefit,
196 "asinh");
197 populateOCLExtSetOpPatterns<math::AtanOp>(converter, patterns, benefit,
198 "atan");
199 populateOCLExtSetOpPatterns<math::Atan2Op>(converter, patterns, benefit,
200 "atan2");
201 populateOCLExtSetOpPatterns<math::AtanhOp>(converter, patterns, benefit,
202 "atanh");
203 populateOCLExtSetOpPatterns<math::CbrtOp>(converter, patterns, benefit,
204 "cbrt");
205 populateOCLExtSetOpPatterns<math::CopySignOp>(converter, patterns, benefit,
206 "copysign");
207 populateOCLExtSetOpPatterns<math::CosOp>(converter, patterns, benefit, "cos");
208 populateOCLExtSetOpPatterns<math::CoshOp>(converter, patterns, benefit,
209 "cosh");
210 populateOCLExtSetOpPatterns<math::ErfOp>(converter, patterns, benefit, "erf");
211 populateOCLExtSetOpPatterns<math::ErfcOp>(converter, patterns, benefit,
212 "erfc");
213 populateOCLExtSetOpPatterns<math::ExpOp>(converter, patterns, benefit, "exp");
214 populateOCLExtSetOpPatterns<math::Exp2Op>(converter, patterns, benefit,
215 "exp2");
216 populateOCLExtSetOpPatterns<math::ExpM1Op>(converter, patterns, benefit,
217 "expm1");
218 populateOCLExtSetOpPatterns<math::LogOp>(converter, patterns, benefit, "log");
219 populateOCLExtSetOpPatterns<math::Log10Op>(converter, patterns, benefit,
220 "log10");
221 populateOCLExtSetOpPatterns<math::Log1pOp>(converter, patterns, benefit,
222 "log1p");
223 populateOCLExtSetOpPatterns<math::Log2Op>(converter, patterns, benefit,
224 "log2");
225 populateOCLExtSetOpPatterns<math::PowFOp>(converter, patterns, benefit,
226 "pow");
227 populateOCLExtSetOpPatterns<math::RsqrtOp>(converter, patterns, benefit,
228 "rsqrt");
229 populateOCLExtSetOpPatterns<math::SinOp>(converter, patterns, benefit, "sin");
230 populateOCLExtSetOpPatterns<math::SinhOp>(converter, patterns, benefit,
231 "sinh");
232 populateOCLExtSetOpPatterns<math::SqrtOp>(converter, patterns, benefit,
233 "sqrt");
234 populateOCLExtSetOpPatterns<math::TanOp>(converter, patterns, benefit, "tan");
235 populateOCLExtSetOpPatterns<math::TanhOp>(converter, patterns, benefit,
236 "tanh");
237}
238
240 bool convertArith,
241 PatternBenefit benefit) {
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);
264 if (convertArith)
266 patterns.getContext(), "__spirv_ocl_native_divide", benefit);
267}
268
269namespace {
270struct ConvertMathToXeVMPass
271 : public impl::ConvertMathToXeVMBase<ConvertMathToXeVMPass> {
272 using Base::Base;
273 void runOnOperation() override;
274};
275} // namespace
276
277void ConvertMathToXeVMPass::runOnOperation() {
278 Operation *op = getOperation();
279 MLIRContext *ctx = op->getContext();
280
281 // Simplify first, so the cheaper form is what the conversion below lowers. A
282 // simplification rewrites a whole expression, so it must run before the
283 // lowering turns the parts of that expression into calls. Only the ops these
284 // patterns can match are given to the driver, and folding is off, so nothing
285 // else is touched.
286 {
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);
294 });
295 GreedyRewriteConfig config;
296 config.enableFolding(false);
297 if (failed(applyOpPatternsGreedily(candidates, frozen, config)))
298 return signalPassFailure();
299 }
300
301 const auto &dl = getAnalysis<DataLayoutAnalysis>();
302
303 RewritePatternSet patterns(&getContext());
304 LowerToLLVMOptions options(ctx, dl.getAtOrAbove(op));
305 LLVMTypeConverter converter(ctx, options);
306 ConversionTarget target(getContext());
307
308 // The native (`afn`) patterns must outrank the precise OCL patterns: an op
309 // marked `afn` gets the native intrinsic, and every other op falls through to
310 // the precise OCL intrinsic.
311 constexpr unsigned oclBenefit = 1;
312 populateMathToXeVMConversionPatterns(patterns, convertArith, oclBenefit + 1);
313 if (convertToOCL) {
315 oclBenefit);
316 target
317 .addIllegalOp<LLVM::CosOp, LLVM::ExpOp, LLVM::Exp2Op, LLVM::LogOp,
318 LLVM::Log10Op, LLVM::Log2Op, LLVM::SinOp, LLVM::SqrtOp>();
319 }
320 target.addLegalDialect<BuiltinDialect, LLVM::LLVMDialect>();
321 // The size-1-vector patterns unwrap to the scalar intrinsic via
322 // vector.extract / vector.broadcast; these must be legal for the partial
323 // conversion to succeed.
324 target.addLegalOp<vector::ExtractOp, vector::BroadcastOp>();
325 if (failed(
326 applyPartialConversion(getOperation(), target, std::move(patterns))))
327 signalPassFailure();
328}
return success()
b getContext())
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
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.
Definition Operation.h:115
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),...
Definition Operation.h:851
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
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...
Definition Types.h:74
bool isFloat() const
Return true if this is an float type (with the specified width).
Definition Types.cpp:47
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
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`.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
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.