MLIR 24.0.0git
ConvertLaunchFuncToLLVMCalls.cpp
Go to the documentation of this file.
1//===- ConvertLaunchFuncToLLVMCalls.cpp - MLIR GPU launch to LLVM pass ----===//
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 passes to convert `gpu.launch_func` op into a sequence
10// of LLVM calls that emulate the host and device sides.
11//
12//===----------------------------------------------------------------------===//
13
26#include "mlir/IR/BuiltinOps.h"
27#include "mlir/IR/SymbolTable.h"
28#include "mlir/Pass/Pass.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/FormatVariadic.h"
33
34namespace mlir {
35#define GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS
36#include "mlir/Conversion/Passes.h.inc"
37} // namespace mlir
38
39using namespace mlir;
40
41static constexpr const char kSPIRVModule[] = "__spv__";
42
43//===----------------------------------------------------------------------===//
44// Utility functions
45//===----------------------------------------------------------------------===//
46
47/// Calculates the index of the kernel's operand that is represented by the
48/// given global variable with the `bind` attribute. We assume that the index of
49/// each kernel's operand is mapped to (descriptorSet, binding) by the map:
50/// i -> (0, i)
51/// which is implemented under `LowerABIAttributesPass`.
52static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op) {
53 return *op.getBinding();
54}
55
56/// Copies the given number of bytes from src to dst pointers.
57static void copy(Location loc, Value dst, Value src, Value size,
58 OpBuilder &builder) {
59 LLVM::MemcpyOp::create(builder, loc, dst, src, size, /*isVolatile=*/false);
60}
61
62/// Encodes the binding and descriptor set numbers into a new symbolic name.
63/// The name is specified by
64/// {kernel_module_name}_{variable_name}_descriptor_set{ds}_binding{b}
65/// to avoid symbolic conflicts, where 'ds' and 'b' are descriptor set and
66/// binding numbers.
67static std::string
68createGlobalVariableWithBindName(spirv::GlobalVariableOp op,
69 StringRef kernelModuleName) {
70 return llvm::formatv("{0}_{1}_descriptor_set{2}_binding{3}",
71 kernelModuleName.str(), op.getSymName().str(),
72 std::to_string(*op.getDescriptorSet()),
73 std::to_string(*op.getBinding()));
74}
75
76/// Returns true if the given global variable has both a descriptor set number
77/// and a binding number.
78static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op) {
79 return op.getDescriptorSetAttr() && op.getBindingAttr();
80}
81
82/// Fills `globalVariableMap` with SPIR-V global variables that represent kernel
83/// arguments from the given SPIR-V module. We assume that the module contains a
84/// single entry point function. Hence, all `spirv.GlobalVariable`s with a bind
85/// attribute are kernel arguments.
86static LogicalResult getKernelGlobalVariables(
87 spirv::ModuleOp module,
89 auto entryPoints = module.getOps<spirv::EntryPointOp>();
90 if (!llvm::hasSingleElement(entryPoints)) {
91 return module.emitError(
92 "The module must contain exactly one entry point function");
93 }
94 auto globalVariables = module.getOps<spirv::GlobalVariableOp>();
95 for (auto globalOp : globalVariables) {
96 if (hasDescriptorSetAndBinding(globalOp))
97 globalVariableMap[calculateGlobalIndex(globalOp)] = globalOp;
98 }
99 return success();
100}
101
102/// Encodes the SPIR-V module's symbolic name into the name of the entry point
103/// function.
104static LogicalResult encodeKernelName(spirv::ModuleOp module) {
105 StringRef spvModuleName = module.getSymName().value_or(kSPIRVModule);
106 // We already know that the module contains exactly one entry point function
107 // based on `getKernelGlobalVariables()` call. Update this function's name
108 // to:
109 // {spv_module_name}_{function_name}
110 auto entryPoints = module.getOps<spirv::EntryPointOp>();
111 if (!llvm::hasSingleElement(entryPoints)) {
112 return module.emitError(
113 "The module must contain exactly one entry point function");
114 }
115 spirv::EntryPointOp entryPoint = *entryPoints.begin();
116 StringRef funcName = entryPoint.getFn();
117 auto funcOp = module.lookupSymbol<spirv::FuncOp>(entryPoint.getFnAttr());
118 StringAttr newFuncName =
119 StringAttr::get(module->getContext(), spvModuleName + "_" + funcName);
120 if (failed(SymbolTable::replaceAllSymbolUses(funcOp, newFuncName, module)))
121 return failure();
122 SymbolTable::setSymbolName(funcOp, newFuncName);
123 return success();
124}
125
126//===----------------------------------------------------------------------===//
127// Conversion patterns
128//===----------------------------------------------------------------------===//
129
130namespace {
131
132/// Structure to group information about the variables being copied.
133struct CopyInfo {
134 Value dst;
135 Value src;
136 Value size;
137};
138
139/// This pattern emulates a call to the kernel in LLVM dialect. For that, we
140/// copy the data to the global variable (emulating device side), call the
141/// kernel as a normal void LLVM function, and copy the data back (emulating the
142/// host side).
143class GPULaunchLowering : public ConvertOpToLLVMPattern<gpu::LaunchFuncOp> {
144 using ConvertOpToLLVMPattern<gpu::LaunchFuncOp>::ConvertOpToLLVMPattern;
145
146 LogicalResult
147 matchAndRewrite(gpu::LaunchFuncOp launchOp, OpAdaptor adaptor,
148 ConversionPatternRewriter &rewriter) const override {
149 auto *op = launchOp.getOperation();
150 MLIRContext *context = rewriter.getContext();
151 auto module = launchOp->getParentOfType<ModuleOp>();
152
153 // Get the SPIR-V module that represents the gpu kernel module. The module
154 // is named:
155 // __spv__{kernel_module_name}
156 // based on GPU to SPIR-V conversion.
157 StringRef kernelModuleName = launchOp.getKernelModuleName().getValue();
158 std::string spvModuleName = kSPIRVModule + kernelModuleName.str();
159 auto spvModule = module.lookupSymbol<spirv::ModuleOp>(
160 StringAttr::get(context, spvModuleName));
161 if (!spvModule) {
162 return launchOp.emitOpError("SPIR-V kernel module '")
163 << spvModuleName << "' is not found";
164 }
165
166 // Declare kernel function in the main module so that it later can be linked
167 // with its definition from the kernel module. We know that the kernel
168 // function would have no arguments and the data is passed via global
169 // variables. The name of the kernel will be
170 // {spv_module_name}_{kernel_function_name}
171 // to avoid symbolic name conflicts.
172 StringRef kernelFuncName = launchOp.getKernelName().getValue();
173 std::string newKernelFuncName = spvModuleName + "_" + kernelFuncName.str();
174 auto kernelFunc = module.lookupSymbol<LLVM::LLVMFuncOp>(
175 StringAttr::get(context, newKernelFuncName));
176 if (!kernelFunc) {
177 OpBuilder::InsertionGuard guard(rewriter);
178 rewriter.setInsertionPointToStart(module.getBody());
179 kernelFunc = LLVM::LLVMFuncOp::create(
180 rewriter, rewriter.getUnknownLoc(), newKernelFuncName,
181 LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(context),
182 ArrayRef<Type>()));
183 rewriter.setInsertionPoint(launchOp);
184 }
185
186 // Get all global variables associated with the kernel operands.
187 DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;
188 if (failed(getKernelGlobalVariables(spvModule, globalVariableMap)))
189 return failure();
190
191 // Traverse kernel operands that were converted to MemRefDescriptors. For
192 // each operand, create a global variable and copy data from operand to it.
193 Location loc = launchOp.getLoc();
194 SmallVector<CopyInfo, 4> copyInfo;
195 auto numKernelOperands = launchOp.getNumKernelOperands();
196 auto kernelOperands = adaptor.getOperands().take_back(numKernelOperands);
197 for (const auto &operand : llvm::enumerate(kernelOperands)) {
198 // Check if the kernel's operand is a ranked memref.
199 auto memRefType = dyn_cast<MemRefType>(
200 launchOp.getKernelOperand(operand.index()).getType());
201 if (!memRefType)
202 return failure();
203
204 // Calculate the size of the memref and get the pointer to the allocated
205 // buffer.
206 SmallVector<Value, 4> sizes;
207 SmallVector<Value, 4> strides;
208 Value sizeBytes;
209 getMemRefDescriptorSizes(loc, memRefType, {}, rewriter, sizes, strides,
210 sizeBytes);
211 MemRefDescriptor descriptor(operand.value());
212 Value src = descriptor.allocatedPtr(rewriter, loc);
213
214 // Get the global variable in the SPIR-V module that is associated with
215 // the kernel operand. Construct its new name and create a corresponding
216 // LLVM dialect global variable.
217 spirv::GlobalVariableOp spirvGlobal = globalVariableMap[operand.index()];
218 auto pointeeType =
219 cast<spirv::PointerType>(spirvGlobal.getType()).getPointeeType();
220 auto dstGlobalType = typeConverter->convertType(pointeeType);
221 if (!dstGlobalType)
222 return failure();
223 std::string name =
224 createGlobalVariableWithBindName(spirvGlobal, spvModuleName);
225 // Check if this variable has already been created.
226 auto dstGlobal = module.lookupSymbol<LLVM::GlobalOp>(name);
227 if (!dstGlobal) {
228 OpBuilder::InsertionGuard guard(rewriter);
229 rewriter.setInsertionPointToStart(module.getBody());
230 dstGlobal = LLVM::GlobalOp::create(
231 rewriter, loc, dstGlobalType,
232 /*isConstant=*/false, LLVM::Linkage::Linkonce, name, Attribute(),
233 /*alignment=*/0);
234 rewriter.setInsertionPoint(launchOp);
235 }
236
237 // Copy the data from src operand pointer to dst global variable. Save
238 // src, dst and size so that we can copy data back after emulating the
239 // kernel call.
240 Value dst = LLVM::AddressOfOp::create(
241 rewriter, loc, typeConverter->convertType(spirvGlobal.getType()),
242 dstGlobal.getSymName());
243 copy(loc, dst, src, sizeBytes, rewriter);
244
245 CopyInfo info;
246 info.dst = dst;
247 info.src = src;
248 info.size = sizeBytes;
249 copyInfo.push_back(info);
250 }
251 // Create a call to the kernel and copy the data back.
252 rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, kernelFunc,
253 ArrayRef<Value>());
254 for (CopyInfo info : copyInfo)
255 copy(loc, info.src, info.dst, info.size, rewriter);
256 return success();
257 }
258};
259
260class LowerHostCodeToLLVM
261 : public impl::LowerHostCodeToLLVMPassBase<LowerHostCodeToLLVM> {
262public:
263 using Base::Base;
264
265 void runOnOperation() override {
266 ModuleOp module = getOperation();
267
268 // Erase the GPU module.
269 for (auto gpuModule :
270 llvm::make_early_inc_range(module.getOps<gpu::GPUModuleOp>()))
271 gpuModule.erase();
272
273 // Request C wrapper emission.
274 for (auto func : module.getOps<func::FuncOp>()) {
275 func->setDiscardableAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
276 UnitAttr::get(&getContext()));
277 }
278
279 // Specify options to lower to LLVM and pull in the conversion patterns.
280 LowerToLLVMOptions options(module.getContext());
281
282 auto *context = module.getContext();
283 RewritePatternSet patterns(context);
284 LLVMTypeConverter typeConverter(context, options);
286 populateFinalizeMemRefToLLVMConversionPatterns(typeConverter, patterns);
287 populateFuncToLLVMConversionPatterns(typeConverter, patterns);
288 patterns.add<GPULaunchLowering>(typeConverter);
289
290 // Pull in SPIR-V type conversion patterns to convert SPIR-V global
291 // variable's type to LLVM dialect type.
293
294 ConversionTarget target(*context);
295 target.addLegalDialect<LLVM::LLVMDialect>();
296 if (failed(applyPartialConversion(module, target, std::move(patterns))))
297 signalPassFailure();
298
299 // Finally, modify the kernel function in SPIR-V modules to avoid symbolic
300 // conflicts.
301 for (auto spvModule : module.getOps<spirv::ModuleOp>()) {
302 if (failed(encodeKernelName(spvModule))) {
303 signalPassFailure();
304 return;
305 }
306 }
307 }
308};
309} // namespace
return success()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static constexpr const char kSPIRVModule[]
static std::string createGlobalVariableWithBindName(spirv::GlobalVariableOp op, StringRef kernelModuleName)
Encodes the binding and descriptor set numbers into a new symbolic name.
static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op)
Calculates the index of the kernel's operand that is represented by the given global variable with th...
static LogicalResult encodeKernelName(spirv::ModuleOp module)
Encodes the SPIR-V module's symbolic name into the name of the entry point function.
static LogicalResult getKernelGlobalVariables(spirv::ModuleOp module, DenseMap< uint32_t, spirv::GlobalVariableOp > &globalVariableMap)
Fills globalVariableMap with SPIR-V global variables that represent kernel arguments from the given S...
static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op)
Returns true if the given global variable has both a descriptor set number and a binding number.
static constexpr const char kSPIRVModule[]
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition Pattern.h:227
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
static LogicalResult replaceAllSymbolUses(StringAttr oldSymbol, StringAttr newSymbol, Operation *from)
Attempt to replace all uses of the given symbol 'oldSymbol' with the provided symbol 'newSymbol' that...
static void setSymbolName(Operation *symbol, StringAttr name)
Sets the name of the given symbol operation.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
void populateArithToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
void populateSPIRVToLLVMTypeConversion(LLVMTypeConverter &typeConverter, spirv::ClientAPI clientAPIForAddressSpaceMapping=spirv::ClientAPI::Unknown)
Populates type conversions with additional SPIR-V types.
void populateFuncToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect the patterns to convert from the Func dialect to LLVM.
void populateFinalizeMemRefToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect a set of patterns to convert memory-related operations from the MemRef dialect to the LLVM di...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120