MLIR  17.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 
15 
27 #include "mlir/IR/BuiltinOps.h"
28 #include "mlir/IR/SymbolTable.h"
29 #include "mlir/Pass/Pass.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/FormatVariadic.h"
34 
35 namespace mlir {
36 #define GEN_PASS_DEF_LOWERHOSTCODETOLLVM
37 #include "mlir/Conversion/Passes.h.inc"
38 } // namespace mlir
39 
40 using namespace mlir;
41 
42 static constexpr const char kSPIRVModule[] = "__spv__";
43 
44 //===----------------------------------------------------------------------===//
45 // Utility functions
46 //===----------------------------------------------------------------------===//
47 
48 /// Returns the string name of the `DescriptorSet` decoration.
49 static std::string descriptorSetName() {
50  return llvm::convertToSnakeFromCamelCase(
51  stringifyDecoration(spirv::Decoration::DescriptorSet));
52 }
53 
54 /// Returns the string name of the `Binding` decoration.
55 static std::string bindingName() {
56  return llvm::convertToSnakeFromCamelCase(
57  stringifyDecoration(spirv::Decoration::Binding));
58 }
59 
60 /// Calculates the index of the kernel's operand that is represented by the
61 /// given global variable with the `bind` attribute. We assume that the index of
62 /// each kernel's operand is mapped to (descriptorSet, binding) by the map:
63 /// i -> (0, i)
64 /// which is implemented under `LowerABIAttributesPass`.
65 static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op) {
66  IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
67  return binding.getInt();
68 }
69 
70 /// Copies the given number of bytes from src to dst pointers.
71 static void copy(Location loc, Value dst, Value src, Value size,
72  OpBuilder &builder) {
73  MLIRContext *context = builder.getContext();
74  auto llvmI1Type = IntegerType::get(context, 1);
75  Value isVolatile = builder.create<LLVM::ConstantOp>(
76  loc, llvmI1Type, builder.getBoolAttr(false));
77  builder.create<LLVM::MemcpyOp>(loc, dst, src, size, isVolatile);
78 }
79 
80 /// Encodes the binding and descriptor set numbers into a new symbolic name.
81 /// The name is specified by
82 /// {kernel_module_name}_{variable_name}_descriptor_set{ds}_binding{b}
83 /// to avoid symbolic conflicts, where 'ds' and 'b' are descriptor set and
84 /// binding numbers.
85 static std::string
86 createGlobalVariableWithBindName(spirv::GlobalVariableOp op,
87  StringRef kernelModuleName) {
88  IntegerAttr descriptorSet =
89  op->getAttrOfType<IntegerAttr>(descriptorSetName());
90  IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
91  return llvm::formatv("{0}_{1}_descriptor_set{2}_binding{3}",
92  kernelModuleName.str(), op.getSymName().str(),
93  std::to_string(descriptorSet.getInt()),
94  std::to_string(binding.getInt()));
95 }
96 
97 /// Returns true if the given global variable has both a descriptor set number
98 /// and a binding number.
99 static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op) {
100  IntegerAttr descriptorSet =
101  op->getAttrOfType<IntegerAttr>(descriptorSetName());
102  IntegerAttr binding = op->getAttrOfType<IntegerAttr>(bindingName());
103  return descriptorSet && binding;
104 }
105 
106 /// Fills `globalVariableMap` with SPIR-V global variables that represent kernel
107 /// arguments from the given SPIR-V module. We assume that the module contains a
108 /// single entry point function. Hence, all `spirv.GlobalVariable`s with a bind
109 /// attribute are kernel arguments.
111  spirv::ModuleOp module,
112  DenseMap<uint32_t, spirv::GlobalVariableOp> &globalVariableMap) {
113  auto entryPoints = module.getOps<spirv::EntryPointOp>();
114  if (!llvm::hasSingleElement(entryPoints)) {
115  return module.emitError(
116  "The module must contain exactly one entry point function");
117  }
118  auto globalVariables = module.getOps<spirv::GlobalVariableOp>();
119  for (auto globalOp : globalVariables) {
120  if (hasDescriptorSetAndBinding(globalOp))
121  globalVariableMap[calculateGlobalIndex(globalOp)] = globalOp;
122  }
123  return success();
124 }
125 
126 /// Encodes the SPIR-V module's symbolic name into the name of the entry point
127 /// function.
128 static LogicalResult encodeKernelName(spirv::ModuleOp module) {
129  StringRef spvModuleName = module.getSymName().value_or(kSPIRVModule);
130  // We already know that the module contains exactly one entry point function
131  // based on `getKernelGlobalVariables()` call. Update this function's name
132  // to:
133  // {spv_module_name}_{function_name}
134  auto entryPoints = module.getOps<spirv::EntryPointOp>();
135  if (!llvm::hasSingleElement(entryPoints)) {
136  return module.emitError(
137  "The module must contain exactly one entry point function");
138  }
139  spirv::EntryPointOp entryPoint = *entryPoints.begin();
140  StringRef funcName = entryPoint.getFn();
141  auto funcOp = module.lookupSymbol<spirv::FuncOp>(entryPoint.getFnAttr());
142  StringAttr newFuncName =
143  StringAttr::get(module->getContext(), spvModuleName + "_" + funcName);
144  if (failed(SymbolTable::replaceAllSymbolUses(funcOp, newFuncName, module)))
145  return failure();
146  SymbolTable::setSymbolName(funcOp, newFuncName);
147  return success();
148 }
149 
150 //===----------------------------------------------------------------------===//
151 // Conversion patterns
152 //===----------------------------------------------------------------------===//
153 
154 namespace {
155 
156 /// Structure to group information about the variables being copied.
157 struct CopyInfo {
158  Value dst;
159  Value src;
160  Value size;
161 };
162 
163 /// This pattern emulates a call to the kernel in LLVM dialect. For that, we
164 /// copy the data to the global variable (emulating device side), call the
165 /// kernel as a normal void LLVM function, and copy the data back (emulating the
166 /// host side).
167 class GPULaunchLowering : public ConvertOpToLLVMPattern<gpu::LaunchFuncOp> {
169 
171  matchAndRewrite(gpu::LaunchFuncOp launchOp, OpAdaptor adaptor,
172  ConversionPatternRewriter &rewriter) const override {
173  auto *op = launchOp.getOperation();
174  MLIRContext *context = rewriter.getContext();
175  auto module = launchOp->getParentOfType<ModuleOp>();
176 
177  // Get the SPIR-V module that represents the gpu kernel module. The module
178  // is named:
179  // __spv__{kernel_module_name}
180  // based on GPU to SPIR-V conversion.
181  StringRef kernelModuleName = launchOp.getKernelModuleName().getValue();
182  std::string spvModuleName = kSPIRVModule + kernelModuleName.str();
183  auto spvModule = module.lookupSymbol<spirv::ModuleOp>(
184  StringAttr::get(context, spvModuleName));
185  if (!spvModule) {
186  return launchOp.emitOpError("SPIR-V kernel module '")
187  << spvModuleName << "' is not found";
188  }
189 
190  // Declare kernel function in the main module so that it later can be linked
191  // with its definition from the kernel module. We know that the kernel
192  // function would have no arguments and the data is passed via global
193  // variables. The name of the kernel will be
194  // {spv_module_name}_{kernel_function_name}
195  // to avoid symbolic name conflicts.
196  StringRef kernelFuncName = launchOp.getKernelName().getValue();
197  std::string newKernelFuncName = spvModuleName + "_" + kernelFuncName.str();
198  auto kernelFunc = module.lookupSymbol<LLVM::LLVMFuncOp>(
199  StringAttr::get(context, newKernelFuncName));
200  if (!kernelFunc) {
201  OpBuilder::InsertionGuard guard(rewriter);
202  rewriter.setInsertionPointToStart(module.getBody());
203  kernelFunc = rewriter.create<LLVM::LLVMFuncOp>(
204  rewriter.getUnknownLoc(), newKernelFuncName,
205  LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(context),
206  ArrayRef<Type>()));
207  rewriter.setInsertionPoint(launchOp);
208  }
209 
210  // Get all global variables associated with the kernel operands.
212  if (failed(getKernelGlobalVariables(spvModule, globalVariableMap)))
213  return failure();
214 
215  // Traverse kernel operands that were converted to MemRefDescriptors. For
216  // each operand, create a global variable and copy data from operand to it.
217  Location loc = launchOp.getLoc();
218  SmallVector<CopyInfo, 4> copyInfo;
219  auto numKernelOperands = launchOp.getNumKernelOperands();
220  auto kernelOperands = adaptor.getOperands().take_back(numKernelOperands);
221  for (const auto &operand : llvm::enumerate(kernelOperands)) {
222  // Check if the kernel's operand is a ranked memref.
223  auto memRefType = launchOp.getKernelOperand(operand.index())
224  .getType()
225  .dyn_cast<MemRefType>();
226  if (!memRefType)
227  return failure();
228 
229  // Calculate the size of the memref and get the pointer to the allocated
230  // buffer.
231  SmallVector<Value, 4> sizes;
232  SmallVector<Value, 4> strides;
233  Value sizeBytes;
234  getMemRefDescriptorSizes(loc, memRefType, {}, rewriter, sizes, strides,
235  sizeBytes);
236  MemRefDescriptor descriptor(operand.value());
237  Value src = descriptor.allocatedPtr(rewriter, loc);
238 
239  // Get the global variable in the SPIR-V module that is associated with
240  // the kernel operand. Construct its new name and create a corresponding
241  // LLVM dialect global variable.
242  spirv::GlobalVariableOp spirvGlobal = globalVariableMap[operand.index()];
243  auto pointeeType =
244  spirvGlobal.getType().cast<spirv::PointerType>().getPointeeType();
245  auto dstGlobalType = typeConverter->convertType(pointeeType);
246  if (!dstGlobalType)
247  return failure();
248  std::string name =
249  createGlobalVariableWithBindName(spirvGlobal, spvModuleName);
250  // Check if this variable has already been created.
251  auto dstGlobal = module.lookupSymbol<LLVM::GlobalOp>(name);
252  if (!dstGlobal) {
253  OpBuilder::InsertionGuard guard(rewriter);
254  rewriter.setInsertionPointToStart(module.getBody());
255  dstGlobal = rewriter.create<LLVM::GlobalOp>(
256  loc, dstGlobalType,
257  /*isConstant=*/false, LLVM::Linkage::Linkonce, name, Attribute(),
258  /*alignment=*/0);
259  rewriter.setInsertionPoint(launchOp);
260  }
261 
262  // Copy the data from src operand pointer to dst global variable. Save
263  // src, dst and size so that we can copy data back after emulating the
264  // kernel call.
265  Value dst = rewriter.create<LLVM::AddressOfOp>(loc, dstGlobal);
266  copy(loc, dst, src, sizeBytes, rewriter);
267 
268  CopyInfo info;
269  info.dst = dst;
270  info.src = src;
271  info.size = sizeBytes;
272  copyInfo.push_back(info);
273  }
274  // Create a call to the kernel and copy the data back.
275  rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, kernelFunc,
276  ArrayRef<Value>());
277  for (CopyInfo info : copyInfo)
278  copy(loc, info.src, info.dst, info.size, rewriter);
279  return success();
280  }
281 };
282 
283 class LowerHostCodeToLLVM
284  : public impl::LowerHostCodeToLLVMBase<LowerHostCodeToLLVM> {
285 public:
286  void runOnOperation() override {
287  ModuleOp module = getOperation();
288 
289  // Erase the GPU module.
290  for (auto gpuModule :
291  llvm::make_early_inc_range(module.getOps<gpu::GPUModuleOp>()))
292  gpuModule.erase();
293 
294  // Request C wrapper emission.
295  for (auto func : module.getOps<func::FuncOp>()) {
296  func->setAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
297  UnitAttr::get(&getContext()));
298  }
299 
300  // Specify options to lower to LLVM and pull in the conversion patterns.
301  LowerToLLVMOptions options(module.getContext());
302  auto *context = module.getContext();
303  RewritePatternSet patterns(context);
304  LLVMTypeConverter typeConverter(context, options);
306  populateFinalizeMemRefToLLVMConversionPatterns(typeConverter, patterns);
307  populateFuncToLLVMConversionPatterns(typeConverter, patterns);
308  patterns.add<GPULaunchLowering>(typeConverter);
309 
310  // Pull in SPIR-V type conversion patterns to convert SPIR-V global
311  // variable's type to LLVM dialect type.
312  populateSPIRVToLLVMTypeConversion(typeConverter);
313 
314  ConversionTarget target(*context);
315  target.addLegalDialect<LLVM::LLVMDialect>();
316  if (failed(applyPartialConversion(module, target, std::move(patterns))))
317  signalPassFailure();
318 
319  // Finally, modify the kernel function in SPIR-V modules to avoid symbolic
320  // conflicts.
321  for (auto spvModule : module.getOps<spirv::ModuleOp>()) {
322  if (failed(encodeKernelName(spvModule))) {
323  signalPassFailure();
324  return;
325  }
326  }
327  }
328 };
329 } // namespace
330 
331 std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
333  return std::make_unique<LowerHostCodeToLLVM>();
334 }
static std::string bindingName()
Returns the string name of the Binding decoration.
static std::string descriptorSetName()
Returns the string name of the DescriptorSet decoration.
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 llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition: Attributes.h:25
BoolAttr getBoolAttr(bool value)
Definition: Builders.cpp:101
MLIRContext * getContext() const
Definition: Builders.h:55
Location getUnknownLoc()
Definition: Builders.cpp:26
This class implements a pattern rewriter for use with ConversionPatterns.
This class describes a specific conversion target.
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition: Pattern.h:135
Conversion from types to the LLVM IR dialect.
Definition: TypeConverter.h:30
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
Options to control the LLVM lowering.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:56
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Definition: MemRefBuilder.h:33
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:301
This class helps build Operations.
Definition: Builders.h:199
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:384
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:351
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:422
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replaces the result op with a new op that is created without verification.
Definition: PatternMatch.h:451
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:93
void populateArithToLLVMConversionPatterns(LLVMTypeConverter &converter, RewritePatternSet &patterns)
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:223
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, ConversionTarget &target, const FrozenRewritePatternSet &patterns, DenseSet< Operation * > *unconvertedOps=nullptr)
Below we define several entry points for operation conversion.
void populateFinalizeMemRefToLLVMConversionPatterns(LLVMTypeConverter &converter, RewritePatternSet &patterns)
Collect a set of patterns to convert memory-related operations from the MemRef dialect to the LLVM di...
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
void populateFuncToLLVMConversionPatterns(LLVMTypeConverter &converter, RewritePatternSet &patterns)
Collect the patterns to convert from the Func dialect to LLVM.
Definition: FuncToLLVM.cpp:715
std::unique_ptr< OperationPass< ModuleOp > > createLowerHostCodeToLLVMPass()
Creates a pass to emulate gpu.launch_func call in LLVM dialect and lower the host module code to LLVM...
void populateSPIRVToLLVMTypeConversion(LLVMTypeConverter &typeConverter)
Populates type conversions with additional SPIR-V types.
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26