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