1 //===- ConvertGPULaunchFuncToVulkanLaunchFunc.cpp - MLIR conversion 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 a pass to convert gpu launch function into a vulkan
10 // launch function. Creates a SPIR-V binary shader from the `spirv::ModuleOp`
11 // using `spirv::serialize` function, attaches binary data and entry point name
12 // as an attributes to vulkan launch call op.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "mlir/Conversion/GPUToVulkan/ConvertGPUToVulkanPass.h"
17 #include "mlir/Dialect/GPU/GPUDialect.h"
18 #include "mlir/Dialect/SPIRV/SPIRVOps.h"
19 #include "mlir/Dialect/SPIRV/Serialization.h"
20 #include "mlir/Dialect/StandardOps/IR/Ops.h"
21 #include "mlir/IR/Attributes.h"
22 #include "mlir/IR/Builders.h"
23 #include "mlir/IR/Function.h"
24 #include "mlir/IR/Module.h"
25 #include "mlir/IR/StandardTypes.h"
26 #include "mlir/Pass/Pass.h"
27 
28 using namespace mlir;
29 
30 static constexpr const char *kSPIRVBlobAttrName = "spirv_blob";
31 static constexpr const char *kSPIRVEntryPointAttrName = "spirv_entry_point";
32 static constexpr const char *kVulkanLaunch = "vulkanLaunch";
33 
34 namespace {
35 
36 /// A pass to convert gpu launch op to vulkan launch call op, by creating a
37 /// SPIR-V binary shader from `spirv::ModuleOp` using `spirv::serialize`
38 /// function and attaching binary data and entry point name as an attributes to
39 /// created vulkan launch call op.
40 class ConvertGpuLaunchFuncToVulkanLaunchFunc
41     : public ModulePass<ConvertGpuLaunchFuncToVulkanLaunchFunc> {
42 public:
43   void runOnModule() override;
44 
45 private:
46   /// Creates a SPIR-V binary shader from the given `module` using
47   /// `spirv::serialize` function.
48   LogicalResult createBinaryShader(ModuleOp module,
49                                    std::vector<char> &binaryShader);
50 
51   /// Converts the given `luanchOp` to vulkan launch call.
52   void convertGpuLaunchFunc(gpu::LaunchFuncOp launchOp);
53 
54   /// Checks where the given type is supported by Vulkan runtime.
55   bool isSupportedType(Type type) {
56     // TODO(denis0x0D): Handle other types.
57     if (auto memRefType = type.dyn_cast_or_null<MemRefType>())
58       return memRefType.hasRank() && memRefType.getRank() == 1;
59     return false;
60   }
61 
62   /// Declares the vulkan launch function. Returns an error if the any type of
63   /// operand is unsupported by Vulkan runtime.
64   LogicalResult declareVulkanLaunchFunc(Location loc,
65                                         gpu::LaunchFuncOp launchOp);
66 
67 };
68 
69 } // anonymous namespace
70 
71 void ConvertGpuLaunchFuncToVulkanLaunchFunc::runOnModule() {
72   bool done = false;
73   getModule().walk([this, &done](gpu::LaunchFuncOp op) {
74     if (done) {
75       op.emitError("should only contain one 'gpu::LaunchFuncOp' op");
76       return signalPassFailure();
77     }
78     done = true;
79     convertGpuLaunchFunc(op);
80   });
81 
82   // Erase `gpu::GPUModuleOp` and `spirv::Module` operations.
83   for (auto gpuModule :
84        llvm::make_early_inc_range(getModule().getOps<gpu::GPUModuleOp>()))
85     gpuModule.erase();
86 
87   for (auto spirvModule :
88        llvm::make_early_inc_range(getModule().getOps<spirv::ModuleOp>()))
89     spirvModule.erase();
90 }
91 
92 LogicalResult ConvertGpuLaunchFuncToVulkanLaunchFunc::declareVulkanLaunchFunc(
93     Location loc, gpu::LaunchFuncOp launchOp) {
94   OpBuilder builder(getModule().getBody()->getTerminator());
95   // TODO: Workgroup size is written into the kernel. So to properly modelling
96   // vulkan launch, we cannot have the local workgroup size configuration here.
97   SmallVector<Type, 8> vulkanLaunchTypes{launchOp.getOperandTypes()};
98 
99   // Check that all operands have supported types except those for the launch
100   // configuration.
101   for (auto type : llvm::drop_begin(vulkanLaunchTypes, 6)) {
102     if (!isSupportedType(type))
103       return launchOp.emitError() << type << " is unsupported to run on Vulkan";
104   }
105 
106   // Declare vulkan launch function.
107   builder.create<FuncOp>(
108       loc, kVulkanLaunch,
109       FunctionType::get(vulkanLaunchTypes, ArrayRef<Type>{}, loc->getContext()),
110       ArrayRef<NamedAttribute>{});
111 
112   return success();
113 }
114 
115 LogicalResult ConvertGpuLaunchFuncToVulkanLaunchFunc::createBinaryShader(
116     ModuleOp module, std::vector<char> &binaryShader) {
117   bool done = false;
118   SmallVector<uint32_t, 0> binary;
119   for (auto spirvModule : module.getOps<spirv::ModuleOp>()) {
120     if (done)
121       return spirvModule.emitError("should only contain one 'spv.module' op");
122     done = true;
123 
124     if (failed(spirv::serialize(spirvModule, binary)))
125       return failure();
126   }
127   binaryShader.resize(binary.size() * sizeof(uint32_t));
128   std::memcpy(binaryShader.data(), reinterpret_cast<char *>(binary.data()),
129               binaryShader.size());
130   return success();
131 }
132 
133 void ConvertGpuLaunchFuncToVulkanLaunchFunc::convertGpuLaunchFunc(
134     gpu::LaunchFuncOp launchOp) {
135   ModuleOp module = getModule();
136   OpBuilder builder(launchOp);
137   Location loc = launchOp.getLoc();
138 
139   // Serialize `spirv::Module` into binary form.
140   std::vector<char> binary;
141   if (failed(createBinaryShader(module, binary)))
142     return signalPassFailure();
143 
144   // Declare vulkan launch function.
145   if (failed(declareVulkanLaunchFunc(loc, launchOp)))
146     return signalPassFailure();
147 
148   // Create vulkan launch call op.
149   auto vulkanLaunchCallOp = builder.create<CallOp>(
150       loc, ArrayRef<Type>{}, builder.getSymbolRefAttr(kVulkanLaunch),
151       launchOp.getOperands());
152 
153   // Set SPIR-V binary shader data as an attribute.
154   vulkanLaunchCallOp.setAttr(
155       kSPIRVBlobAttrName,
156       StringAttr::get({binary.data(), binary.size()}, loc->getContext()));
157 
158   // Set entry point name as an attribute.
159   vulkanLaunchCallOp.setAttr(
160       kSPIRVEntryPointAttrName,
161       StringAttr::get(launchOp.kernel(), loc->getContext()));
162 
163   launchOp.erase();
164 }
165 
166 std::unique_ptr<mlir::OpPassBase<mlir::ModuleOp>>
167 mlir::createConvertGpuLaunchFuncToVulkanLaunchFuncPass() {
168   return std::make_unique<ConvertGpuLaunchFuncToVulkanLaunchFunc>();
169 }
170 
171 static PassRegistration<ConvertGpuLaunchFuncToVulkanLaunchFunc>
172     pass("convert-gpu-launch-to-vulkan-launch",
173          "Convert gpu.launch_func to vulkanLaunch external call");
174