1a5f9cda1SChristian Sigg //===- ConvertLaunchFuncToGpuRuntimeCalls.cpp - MLIR GPU lowering passes --===//
2a5f9cda1SChristian Sigg //
3a5f9cda1SChristian Sigg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a5f9cda1SChristian Sigg // See https://llvm.org/LICENSE.txt for license information.
5a5f9cda1SChristian Sigg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a5f9cda1SChristian Sigg //
7a5f9cda1SChristian Sigg //===----------------------------------------------------------------------===//
8a5f9cda1SChristian Sigg //
9a5f9cda1SChristian Sigg // This file implements a pass to convert gpu.launch_func op into a sequence of
10a5f9cda1SChristian Sigg // GPU runtime calls. As most of GPU runtimes does not have a stable published
11a5f9cda1SChristian Sigg // ABI, this pass uses a slim runtime layer that builds on top of the public
12a5f9cda1SChristian Sigg // API from GPU runtime headers.
13a5f9cda1SChristian Sigg //
14a5f9cda1SChristian Sigg //===----------------------------------------------------------------------===//
15a5f9cda1SChristian Sigg 
16a5f9cda1SChristian Sigg #include "mlir/Conversion/GPUCommon/GPUCommonPass.h"
17a5f9cda1SChristian Sigg 
18a5f9cda1SChristian Sigg #include "../PassDetail.h"
19a5f9cda1SChristian Sigg #include "mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h"
20*684dfe8aSAlex Zinenko #include "mlir/Conversion/LLVMCommon/Pattern.h"
21a5f9cda1SChristian Sigg #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
22*684dfe8aSAlex Zinenko #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
23a5f9cda1SChristian Sigg #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
24a5f9cda1SChristian Sigg #include "mlir/Dialect/Async/IR/Async.h"
25a5f9cda1SChristian Sigg #include "mlir/Dialect/GPU/GPUDialect.h"
26a5f9cda1SChristian Sigg #include "mlir/Dialect/GPU/Passes.h"
27a5f9cda1SChristian Sigg #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
28a5f9cda1SChristian Sigg #include "mlir/IR/Attributes.h"
29a5f9cda1SChristian Sigg #include "mlir/IR/Builders.h"
30a5f9cda1SChristian Sigg #include "mlir/IR/BuiltinOps.h"
31a5f9cda1SChristian Sigg #include "mlir/IR/BuiltinTypes.h"
32a5f9cda1SChristian Sigg 
33a5f9cda1SChristian Sigg #include "llvm/ADT/STLExtras.h"
34a5f9cda1SChristian Sigg #include "llvm/Support/Error.h"
35a5f9cda1SChristian Sigg #include "llvm/Support/FormatVariadic.h"
36a5f9cda1SChristian Sigg 
37a5f9cda1SChristian Sigg using namespace mlir;
38a5f9cda1SChristian Sigg 
39a5f9cda1SChristian Sigg static constexpr const char *kGpuBinaryStorageSuffix = "_gpubin_cst";
40a5f9cda1SChristian Sigg 
41a5f9cda1SChristian Sigg namespace {
42a5f9cda1SChristian Sigg 
43a5f9cda1SChristian Sigg class GpuToLLVMConversionPass
44a5f9cda1SChristian Sigg     : public GpuToLLVMConversionPassBase<GpuToLLVMConversionPass> {
45a5f9cda1SChristian Sigg public:
46a5f9cda1SChristian Sigg   GpuToLLVMConversionPass() = default;
47a5f9cda1SChristian Sigg 
48a5f9cda1SChristian Sigg   GpuToLLVMConversionPass(const GpuToLLVMConversionPass &other)
49a5f9cda1SChristian Sigg       : GpuToLLVMConversionPassBase(other) {}
50a5f9cda1SChristian Sigg 
51a5f9cda1SChristian Sigg   // Run the dialect converter on the module.
52a5f9cda1SChristian Sigg   void runOnOperation() override;
53a5f9cda1SChristian Sigg 
54a5f9cda1SChristian Sigg private:
55a5f9cda1SChristian Sigg   Option<std::string> gpuBinaryAnnotation{
56a5f9cda1SChristian Sigg       *this, "gpu-binary-annotation",
57a5f9cda1SChristian Sigg       llvm::cl::desc("Annotation attribute string for GPU binary"),
58a5f9cda1SChristian Sigg       llvm::cl::init(gpu::getDefaultGpuBinaryAnnotation())};
59a5f9cda1SChristian Sigg };
60a5f9cda1SChristian Sigg 
61a5f9cda1SChristian Sigg struct FunctionCallBuilder {
62a5f9cda1SChristian Sigg   FunctionCallBuilder(StringRef functionName, Type returnType,
63a5f9cda1SChristian Sigg                       ArrayRef<Type> argumentTypes)
64a5f9cda1SChristian Sigg       : functionName(functionName),
65a5f9cda1SChristian Sigg         functionType(LLVM::LLVMFunctionType::get(returnType, argumentTypes)) {}
66a5f9cda1SChristian Sigg   LLVM::CallOp create(Location loc, OpBuilder &builder,
67a5f9cda1SChristian Sigg                       ArrayRef<Value> arguments) const;
68a5f9cda1SChristian Sigg 
69a5f9cda1SChristian Sigg   StringRef functionName;
70a5f9cda1SChristian Sigg   LLVM::LLVMFunctionType functionType;
71a5f9cda1SChristian Sigg };
72a5f9cda1SChristian Sigg 
73a5f9cda1SChristian Sigg template <typename OpTy>
74a5f9cda1SChristian Sigg class ConvertOpToGpuRuntimeCallPattern : public ConvertOpToLLVMPattern<OpTy> {
75a5f9cda1SChristian Sigg public:
76a5f9cda1SChristian Sigg   explicit ConvertOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
77a5f9cda1SChristian Sigg       : ConvertOpToLLVMPattern<OpTy>(typeConverter) {}
78a5f9cda1SChristian Sigg 
79a5f9cda1SChristian Sigg protected:
80a5f9cda1SChristian Sigg   MLIRContext *context = &this->getTypeConverter()->getContext();
81a5f9cda1SChristian Sigg 
82a5f9cda1SChristian Sigg   Type llvmVoidType = LLVM::LLVMVoidType::get(context);
83a5f9cda1SChristian Sigg   Type llvmPointerType =
84a5f9cda1SChristian Sigg       LLVM::LLVMPointerType::get(IntegerType::get(context, 8));
85a5f9cda1SChristian Sigg   Type llvmPointerPointerType = LLVM::LLVMPointerType::get(llvmPointerType);
86a5f9cda1SChristian Sigg   Type llvmInt8Type = IntegerType::get(context, 8);
87a5f9cda1SChristian Sigg   Type llvmInt32Type = IntegerType::get(context, 32);
88a5f9cda1SChristian Sigg   Type llvmInt64Type = IntegerType::get(context, 64);
89a5f9cda1SChristian Sigg   Type llvmIntPtrType = IntegerType::get(
90a5f9cda1SChristian Sigg       context, this->getTypeConverter()->getPointerBitwidth(0));
91a5f9cda1SChristian Sigg 
92a5f9cda1SChristian Sigg   FunctionCallBuilder moduleLoadCallBuilder = {
93a5f9cda1SChristian Sigg       "mgpuModuleLoad",
94a5f9cda1SChristian Sigg       llvmPointerType /* void *module */,
95a5f9cda1SChristian Sigg       {llvmPointerType /* void *cubin */}};
96a5f9cda1SChristian Sigg   FunctionCallBuilder moduleUnloadCallBuilder = {
97a5f9cda1SChristian Sigg       "mgpuModuleUnload", llvmVoidType, {llvmPointerType /* void *module */}};
98a5f9cda1SChristian Sigg   FunctionCallBuilder moduleGetFunctionCallBuilder = {
99a5f9cda1SChristian Sigg       "mgpuModuleGetFunction",
100a5f9cda1SChristian Sigg       llvmPointerType /* void *function */,
101a5f9cda1SChristian Sigg       {
102a5f9cda1SChristian Sigg           llvmPointerType, /* void *module */
103a5f9cda1SChristian Sigg           llvmPointerType  /* char *name   */
104a5f9cda1SChristian Sigg       }};
105a5f9cda1SChristian Sigg   FunctionCallBuilder launchKernelCallBuilder = {
106a5f9cda1SChristian Sigg       "mgpuLaunchKernel",
107a5f9cda1SChristian Sigg       llvmVoidType,
108a5f9cda1SChristian Sigg       {
109a5f9cda1SChristian Sigg           llvmPointerType,        /* void* f */
110a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t gridXDim */
111a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t gridyDim */
112a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t gridZDim */
113a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t blockXDim */
114a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t blockYDim */
115a5f9cda1SChristian Sigg           llvmIntPtrType,         /* intptr_t blockZDim */
116a5f9cda1SChristian Sigg           llvmInt32Type,          /* unsigned int sharedMemBytes */
117a5f9cda1SChristian Sigg           llvmPointerType,        /* void *hstream */
118a5f9cda1SChristian Sigg           llvmPointerPointerType, /* void **kernelParams */
119a5f9cda1SChristian Sigg           llvmPointerPointerType  /* void **extra */
120a5f9cda1SChristian Sigg       }};
121a5f9cda1SChristian Sigg   FunctionCallBuilder streamCreateCallBuilder = {
122a5f9cda1SChristian Sigg       "mgpuStreamCreate", llvmPointerType /* void *stream */, {}};
123a5f9cda1SChristian Sigg   FunctionCallBuilder streamDestroyCallBuilder = {
124a5f9cda1SChristian Sigg       "mgpuStreamDestroy", llvmVoidType, {llvmPointerType /* void *stream */}};
125a5f9cda1SChristian Sigg   FunctionCallBuilder streamSynchronizeCallBuilder = {
126a5f9cda1SChristian Sigg       "mgpuStreamSynchronize",
127a5f9cda1SChristian Sigg       llvmVoidType,
128a5f9cda1SChristian Sigg       {llvmPointerType /* void *stream */}};
129a5f9cda1SChristian Sigg   FunctionCallBuilder streamWaitEventCallBuilder = {
130a5f9cda1SChristian Sigg       "mgpuStreamWaitEvent",
131a5f9cda1SChristian Sigg       llvmVoidType,
132a5f9cda1SChristian Sigg       {llvmPointerType /* void *stream */, llvmPointerType /* void *event */}};
133a5f9cda1SChristian Sigg   FunctionCallBuilder eventCreateCallBuilder = {
134a5f9cda1SChristian Sigg       "mgpuEventCreate", llvmPointerType /* void *event */, {}};
135a5f9cda1SChristian Sigg   FunctionCallBuilder eventDestroyCallBuilder = {
136a5f9cda1SChristian Sigg       "mgpuEventDestroy", llvmVoidType, {llvmPointerType /* void *event */}};
137a5f9cda1SChristian Sigg   FunctionCallBuilder eventSynchronizeCallBuilder = {
138a5f9cda1SChristian Sigg       "mgpuEventSynchronize",
139a5f9cda1SChristian Sigg       llvmVoidType,
140a5f9cda1SChristian Sigg       {llvmPointerType /* void *event */}};
141a5f9cda1SChristian Sigg   FunctionCallBuilder eventRecordCallBuilder = {
142a5f9cda1SChristian Sigg       "mgpuEventRecord",
143a5f9cda1SChristian Sigg       llvmVoidType,
144a5f9cda1SChristian Sigg       {llvmPointerType /* void *event */, llvmPointerType /* void *stream */}};
145a5f9cda1SChristian Sigg   FunctionCallBuilder hostRegisterCallBuilder = {
146a5f9cda1SChristian Sigg       "mgpuMemHostRegisterMemRef",
147a5f9cda1SChristian Sigg       llvmVoidType,
148a5f9cda1SChristian Sigg       {llvmIntPtrType /* intptr_t rank */,
149a5f9cda1SChristian Sigg        llvmPointerType /* void *memrefDesc */,
150a5f9cda1SChristian Sigg        llvmIntPtrType /* intptr_t elementSizeBytes */}};
151a5f9cda1SChristian Sigg   FunctionCallBuilder allocCallBuilder = {
152a5f9cda1SChristian Sigg       "mgpuMemAlloc",
153a5f9cda1SChristian Sigg       llvmPointerType /* void * */,
154a5f9cda1SChristian Sigg       {llvmIntPtrType /* intptr_t sizeBytes */,
155a5f9cda1SChristian Sigg        llvmPointerType /* void *stream */}};
156a5f9cda1SChristian Sigg   FunctionCallBuilder deallocCallBuilder = {
157a5f9cda1SChristian Sigg       "mgpuMemFree",
158a5f9cda1SChristian Sigg       llvmVoidType,
159a5f9cda1SChristian Sigg       {llvmPointerType /* void *ptr */, llvmPointerType /* void *stream */}};
160a5f9cda1SChristian Sigg   FunctionCallBuilder memcpyCallBuilder = {
161a5f9cda1SChristian Sigg       "mgpuMemcpy",
162a5f9cda1SChristian Sigg       llvmVoidType,
163a5f9cda1SChristian Sigg       {llvmPointerType /* void *dst */, llvmPointerType /* void *src */,
164a5f9cda1SChristian Sigg        llvmIntPtrType /* intptr_t sizeBytes */,
165a5f9cda1SChristian Sigg        llvmPointerType /* void *stream */}};
166a5f9cda1SChristian Sigg };
167a5f9cda1SChristian Sigg 
168a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.host_register operations into a GPU runtime
169a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
170a5f9cda1SChristian Sigg class ConvertHostRegisterOpToGpuRuntimeCallPattern
171a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::HostRegisterOp> {
172a5f9cda1SChristian Sigg public:
173a5f9cda1SChristian Sigg   ConvertHostRegisterOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
174a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::HostRegisterOp>(typeConverter) {}
175a5f9cda1SChristian Sigg 
176a5f9cda1SChristian Sigg private:
177a5f9cda1SChristian Sigg   LogicalResult
178a5f9cda1SChristian Sigg   matchAndRewrite(gpu::HostRegisterOp hostRegisterOp, ArrayRef<Value> operands,
179a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
180a5f9cda1SChristian Sigg };
181a5f9cda1SChristian Sigg 
182a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.alloc operations into a GPU runtime
183a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
184a5f9cda1SChristian Sigg class ConvertAllocOpToGpuRuntimeCallPattern
185a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::AllocOp> {
186a5f9cda1SChristian Sigg public:
187a5f9cda1SChristian Sigg   ConvertAllocOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
188a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::AllocOp>(typeConverter) {}
189a5f9cda1SChristian Sigg 
190a5f9cda1SChristian Sigg private:
191a5f9cda1SChristian Sigg   LogicalResult
192a5f9cda1SChristian Sigg   matchAndRewrite(gpu::AllocOp allocOp, ArrayRef<Value> operands,
193a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
194a5f9cda1SChristian Sigg };
195a5f9cda1SChristian Sigg 
196a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.dealloc operations into a GPU runtime
197a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
198a5f9cda1SChristian Sigg class ConvertDeallocOpToGpuRuntimeCallPattern
199a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::DeallocOp> {
200a5f9cda1SChristian Sigg public:
201a5f9cda1SChristian Sigg   ConvertDeallocOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
202a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::DeallocOp>(typeConverter) {}
203a5f9cda1SChristian Sigg 
204a5f9cda1SChristian Sigg private:
205a5f9cda1SChristian Sigg   LogicalResult
206a5f9cda1SChristian Sigg   matchAndRewrite(gpu::DeallocOp deallocOp, ArrayRef<Value> operands,
207a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
208a5f9cda1SChristian Sigg };
209a5f9cda1SChristian Sigg 
210a5f9cda1SChristian Sigg class ConvertAsyncYieldToGpuRuntimeCallPattern
211a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<async::YieldOp> {
212a5f9cda1SChristian Sigg public:
213a5f9cda1SChristian Sigg   ConvertAsyncYieldToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
214a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<async::YieldOp>(typeConverter) {}
215a5f9cda1SChristian Sigg 
216a5f9cda1SChristian Sigg private:
217a5f9cda1SChristian Sigg   LogicalResult
218a5f9cda1SChristian Sigg   matchAndRewrite(async::YieldOp yieldOp, ArrayRef<Value> operands,
219a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
220a5f9cda1SChristian Sigg };
221a5f9cda1SChristian Sigg 
222a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.wait operations into a GPU runtime
223a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
224a5f9cda1SChristian Sigg class ConvertWaitOpToGpuRuntimeCallPattern
225a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::WaitOp> {
226a5f9cda1SChristian Sigg public:
227a5f9cda1SChristian Sigg   ConvertWaitOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
228a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::WaitOp>(typeConverter) {}
229a5f9cda1SChristian Sigg 
230a5f9cda1SChristian Sigg private:
231a5f9cda1SChristian Sigg   LogicalResult
232a5f9cda1SChristian Sigg   matchAndRewrite(gpu::WaitOp waitOp, ArrayRef<Value> operands,
233a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
234a5f9cda1SChristian Sigg };
235a5f9cda1SChristian Sigg 
236a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.wait async operations into a GPU runtime
237a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
238a5f9cda1SChristian Sigg class ConvertWaitAsyncOpToGpuRuntimeCallPattern
239a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::WaitOp> {
240a5f9cda1SChristian Sigg public:
241a5f9cda1SChristian Sigg   ConvertWaitAsyncOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
242a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::WaitOp>(typeConverter) {}
243a5f9cda1SChristian Sigg 
244a5f9cda1SChristian Sigg private:
245a5f9cda1SChristian Sigg   LogicalResult
246a5f9cda1SChristian Sigg   matchAndRewrite(gpu::WaitOp waitOp, ArrayRef<Value> operands,
247a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
248a5f9cda1SChristian Sigg };
249a5f9cda1SChristian Sigg 
250a5f9cda1SChristian Sigg /// A rewrite patter to convert gpu.launch_func operations into a sequence of
251a5f9cda1SChristian Sigg /// GPU runtime calls. Currently it supports CUDA and ROCm (HIP).
252a5f9cda1SChristian Sigg ///
253a5f9cda1SChristian Sigg /// In essence, a gpu.launch_func operations gets compiled into the following
254a5f9cda1SChristian Sigg /// sequence of runtime calls:
255a5f9cda1SChristian Sigg ///
256a5f9cda1SChristian Sigg /// * moduleLoad        -- loads the module given the cubin / hsaco data
257a5f9cda1SChristian Sigg /// * moduleGetFunction -- gets a handle to the actual kernel function
258a5f9cda1SChristian Sigg /// * getStreamHelper   -- initializes a new compute stream on GPU
259a5f9cda1SChristian Sigg /// * launchKernel      -- launches the kernel on a stream
260a5f9cda1SChristian Sigg /// * streamSynchronize -- waits for operations on the stream to finish
261a5f9cda1SChristian Sigg ///
262a5f9cda1SChristian Sigg /// Intermediate data structures are allocated on the stack.
263a5f9cda1SChristian Sigg class ConvertLaunchFuncOpToGpuRuntimeCallPattern
264a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::LaunchFuncOp> {
265a5f9cda1SChristian Sigg public:
266a5f9cda1SChristian Sigg   ConvertLaunchFuncOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter,
267a5f9cda1SChristian Sigg                                              StringRef gpuBinaryAnnotation)
268a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::LaunchFuncOp>(typeConverter),
269a5f9cda1SChristian Sigg         gpuBinaryAnnotation(gpuBinaryAnnotation) {}
270a5f9cda1SChristian Sigg 
271a5f9cda1SChristian Sigg private:
272a5f9cda1SChristian Sigg   Value generateParamsArray(gpu::LaunchFuncOp launchOp,
273a5f9cda1SChristian Sigg                             ArrayRef<Value> operands, OpBuilder &builder) const;
274a5f9cda1SChristian Sigg   Value generateKernelNameConstant(StringRef moduleName, StringRef name,
275a5f9cda1SChristian Sigg                                    Location loc, OpBuilder &builder) const;
276a5f9cda1SChristian Sigg 
277a5f9cda1SChristian Sigg   LogicalResult
278a5f9cda1SChristian Sigg   matchAndRewrite(gpu::LaunchFuncOp launchOp, ArrayRef<Value> operands,
279a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
280a5f9cda1SChristian Sigg 
281a5f9cda1SChristian Sigg   llvm::SmallString<32> gpuBinaryAnnotation;
282a5f9cda1SChristian Sigg };
283a5f9cda1SChristian Sigg 
284a5f9cda1SChristian Sigg class EraseGpuModuleOpPattern : public OpRewritePattern<gpu::GPUModuleOp> {
285a5f9cda1SChristian Sigg   using OpRewritePattern<gpu::GPUModuleOp>::OpRewritePattern;
286a5f9cda1SChristian Sigg 
287a5f9cda1SChristian Sigg   LogicalResult matchAndRewrite(gpu::GPUModuleOp op,
288a5f9cda1SChristian Sigg                                 PatternRewriter &rewriter) const override {
289a5f9cda1SChristian Sigg     // GPU kernel modules are no longer necessary since we have a global
290a5f9cda1SChristian Sigg     // constant with the CUBIN, or HSACO data.
291a5f9cda1SChristian Sigg     rewriter.eraseOp(op);
292a5f9cda1SChristian Sigg     return success();
293a5f9cda1SChristian Sigg   }
294a5f9cda1SChristian Sigg };
295a5f9cda1SChristian Sigg 
296a5f9cda1SChristian Sigg /// A rewrite pattern to convert gpu.memcpy operations into a GPU runtime
297a5f9cda1SChristian Sigg /// call. Currently it supports CUDA and ROCm (HIP).
298a5f9cda1SChristian Sigg class ConvertMemcpyOpToGpuRuntimeCallPattern
299a5f9cda1SChristian Sigg     : public ConvertOpToGpuRuntimeCallPattern<gpu::MemcpyOp> {
300a5f9cda1SChristian Sigg public:
301a5f9cda1SChristian Sigg   ConvertMemcpyOpToGpuRuntimeCallPattern(LLVMTypeConverter &typeConverter)
302a5f9cda1SChristian Sigg       : ConvertOpToGpuRuntimeCallPattern<gpu::MemcpyOp>(typeConverter) {}
303a5f9cda1SChristian Sigg 
304a5f9cda1SChristian Sigg private:
305a5f9cda1SChristian Sigg   LogicalResult
306a5f9cda1SChristian Sigg   matchAndRewrite(gpu::MemcpyOp memcpyOp, ArrayRef<Value> operands,
307a5f9cda1SChristian Sigg                   ConversionPatternRewriter &rewriter) const override;
308a5f9cda1SChristian Sigg };
309a5f9cda1SChristian Sigg } // namespace
310a5f9cda1SChristian Sigg 
311a5f9cda1SChristian Sigg void GpuToLLVMConversionPass::runOnOperation() {
312a5f9cda1SChristian Sigg   LLVMTypeConverter converter(&getContext());
313dc4e913bSChris Lattner   RewritePatternSet patterns(&getContext());
314a5f9cda1SChristian Sigg   LLVMConversionTarget target(getContext());
315a5f9cda1SChristian Sigg 
316abe501f2SChristian Sigg   target.addIllegalDialect<gpu::GPUDialect>();
317abe501f2SChristian Sigg 
318a5f9cda1SChristian Sigg   populateVectorToLLVMConversionPatterns(converter, patterns);
319a5f9cda1SChristian Sigg   populateStdToLLVMConversionPatterns(converter, patterns);
3203a506b31SChris Lattner   populateAsyncStructuralTypeConversionsAndLegality(converter, patterns,
3213a506b31SChris Lattner                                                     target);
322a5f9cda1SChristian Sigg 
323a5f9cda1SChristian Sigg   converter.addConversion(
324a5f9cda1SChristian Sigg       [context = &converter.getContext()](gpu::AsyncTokenType type) -> Type {
325a5f9cda1SChristian Sigg         return LLVM::LLVMPointerType::get(IntegerType::get(context, 8));
326a5f9cda1SChristian Sigg       });
327dc4e913bSChris Lattner   patterns.add<ConvertAllocOpToGpuRuntimeCallPattern,
328a5f9cda1SChristian Sigg                ConvertDeallocOpToGpuRuntimeCallPattern,
329a5f9cda1SChristian Sigg                ConvertHostRegisterOpToGpuRuntimeCallPattern,
330a5f9cda1SChristian Sigg                ConvertMemcpyOpToGpuRuntimeCallPattern,
331a5f9cda1SChristian Sigg                ConvertWaitAsyncOpToGpuRuntimeCallPattern,
332a5f9cda1SChristian Sigg                ConvertWaitOpToGpuRuntimeCallPattern,
333a5f9cda1SChristian Sigg                ConvertAsyncYieldToGpuRuntimeCallPattern>(converter);
334dc4e913bSChris Lattner   patterns.add<ConvertLaunchFuncOpToGpuRuntimeCallPattern>(converter,
335dc4e913bSChris Lattner                                                            gpuBinaryAnnotation);
336dc4e913bSChris Lattner   patterns.add<EraseGpuModuleOpPattern>(&converter.getContext());
337a5f9cda1SChristian Sigg 
338a5f9cda1SChristian Sigg   if (failed(
339a5f9cda1SChristian Sigg           applyPartialConversion(getOperation(), target, std::move(patterns))))
340a5f9cda1SChristian Sigg     signalPassFailure();
341a5f9cda1SChristian Sigg }
342a5f9cda1SChristian Sigg 
343a5f9cda1SChristian Sigg LLVM::CallOp FunctionCallBuilder::create(Location loc, OpBuilder &builder,
344a5f9cda1SChristian Sigg                                          ArrayRef<Value> arguments) const {
345a5f9cda1SChristian Sigg   auto module = builder.getBlock()->getParent()->getParentOfType<ModuleOp>();
346a5f9cda1SChristian Sigg   auto function = [&] {
347a5f9cda1SChristian Sigg     if (auto function = module.lookupSymbol<LLVM::LLVMFuncOp>(functionName))
348a5f9cda1SChristian Sigg       return function;
349973ddb7dSMehdi Amini     return OpBuilder::atBlockEnd(module.getBody())
350a5f9cda1SChristian Sigg         .create<LLVM::LLVMFuncOp>(loc, functionName, functionType);
351a5f9cda1SChristian Sigg   }();
352a5f9cda1SChristian Sigg   return builder.create<LLVM::CallOp>(
353a5f9cda1SChristian Sigg       loc, const_cast<LLVM::LLVMFunctionType &>(functionType).getReturnType(),
354a5f9cda1SChristian Sigg       builder.getSymbolRefAttr(function), arguments);
355a5f9cda1SChristian Sigg }
356a5f9cda1SChristian Sigg 
357a5f9cda1SChristian Sigg // Returns whether all operands are of LLVM type.
358a5f9cda1SChristian Sigg static LogicalResult areAllLLVMTypes(Operation *op, ValueRange operands,
359a5f9cda1SChristian Sigg                                      ConversionPatternRewriter &rewriter) {
360a5f9cda1SChristian Sigg   if (!llvm::all_of(operands, [](Value value) {
361a5f9cda1SChristian Sigg         return LLVM::isCompatibleType(value.getType());
362a5f9cda1SChristian Sigg       }))
363a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(
364a5f9cda1SChristian Sigg         op, "Cannot convert if operands aren't of LLVM type.");
365a5f9cda1SChristian Sigg   return success();
366a5f9cda1SChristian Sigg }
367a5f9cda1SChristian Sigg 
368a5f9cda1SChristian Sigg static LogicalResult
369a5f9cda1SChristian Sigg isAsyncWithOneDependency(ConversionPatternRewriter &rewriter,
370a5f9cda1SChristian Sigg                          gpu::AsyncOpInterface op) {
371a5f9cda1SChristian Sigg   if (op.getAsyncDependencies().size() != 1)
372a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(
373a5f9cda1SChristian Sigg         op, "Can only convert with exactly one async dependency.");
374a5f9cda1SChristian Sigg 
375a5f9cda1SChristian Sigg   if (!op.getAsyncToken())
376a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(op, "Can convert only async version.");
377a5f9cda1SChristian Sigg 
378a5f9cda1SChristian Sigg   return success();
379a5f9cda1SChristian Sigg }
380a5f9cda1SChristian Sigg 
381a5f9cda1SChristian Sigg LogicalResult ConvertHostRegisterOpToGpuRuntimeCallPattern::matchAndRewrite(
382a5f9cda1SChristian Sigg     gpu::HostRegisterOp hostRegisterOp, ArrayRef<Value> operands,
383a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
384a5f9cda1SChristian Sigg   auto *op = hostRegisterOp.getOperation();
385a5f9cda1SChristian Sigg   if (failed(areAllLLVMTypes(op, operands, rewriter)))
386a5f9cda1SChristian Sigg     return failure();
387a5f9cda1SChristian Sigg 
388a5f9cda1SChristian Sigg   Location loc = op->getLoc();
389a5f9cda1SChristian Sigg 
390a5f9cda1SChristian Sigg   auto memRefType = hostRegisterOp.value().getType();
391a5f9cda1SChristian Sigg   auto elementType = memRefType.cast<UnrankedMemRefType>().getElementType();
392a5f9cda1SChristian Sigg   auto elementSize = getSizeInBytes(loc, elementType, rewriter);
393a5f9cda1SChristian Sigg 
394a5f9cda1SChristian Sigg   auto arguments = getTypeConverter()->promoteOperands(loc, op->getOperands(),
395a5f9cda1SChristian Sigg                                                        operands, rewriter);
396a5f9cda1SChristian Sigg   arguments.push_back(elementSize);
397a5f9cda1SChristian Sigg   hostRegisterCallBuilder.create(loc, rewriter, arguments);
398a5f9cda1SChristian Sigg 
399a5f9cda1SChristian Sigg   rewriter.eraseOp(op);
400a5f9cda1SChristian Sigg   return success();
401a5f9cda1SChristian Sigg }
402a5f9cda1SChristian Sigg 
403a5f9cda1SChristian Sigg LogicalResult ConvertAllocOpToGpuRuntimeCallPattern::matchAndRewrite(
404a5f9cda1SChristian Sigg     gpu::AllocOp allocOp, ArrayRef<Value> operands,
405a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
406a5f9cda1SChristian Sigg   MemRefType memRefType = allocOp.getType();
407a5f9cda1SChristian Sigg 
408a5f9cda1SChristian Sigg   if (failed(areAllLLVMTypes(allocOp, operands, rewriter)) ||
409a5f9cda1SChristian Sigg       !isConvertibleAndHasIdentityMaps(memRefType) ||
410a5f9cda1SChristian Sigg       failed(isAsyncWithOneDependency(rewriter, allocOp)))
411a5f9cda1SChristian Sigg     return failure();
412a5f9cda1SChristian Sigg 
413a5f9cda1SChristian Sigg   auto loc = allocOp.getLoc();
414a5f9cda1SChristian Sigg   auto adaptor = gpu::AllocOpAdaptor(operands, allocOp->getAttrDictionary());
415a5f9cda1SChristian Sigg 
416a5f9cda1SChristian Sigg   // Get shape of the memref as values: static sizes are constant
417a5f9cda1SChristian Sigg   // values and dynamic sizes are passed to 'alloc' as operands.
418a5f9cda1SChristian Sigg   SmallVector<Value, 4> shape;
419a5f9cda1SChristian Sigg   SmallVector<Value, 4> strides;
420a5f9cda1SChristian Sigg   Value sizeBytes;
421a5f9cda1SChristian Sigg   getMemRefDescriptorSizes(loc, memRefType, adaptor.dynamicSizes(), rewriter,
422a5f9cda1SChristian Sigg                            shape, strides, sizeBytes);
423a5f9cda1SChristian Sigg 
424a5f9cda1SChristian Sigg   // Allocate the underlying buffer and store a pointer to it in the MemRef
425a5f9cda1SChristian Sigg   // descriptor.
426a5f9cda1SChristian Sigg   Type elementPtrType = this->getElementPtrType(memRefType);
427a5f9cda1SChristian Sigg   auto stream = adaptor.asyncDependencies().front();
428a5f9cda1SChristian Sigg   Value allocatedPtr =
429a5f9cda1SChristian Sigg       allocCallBuilder.create(loc, rewriter, {sizeBytes, stream}).getResult(0);
430a5f9cda1SChristian Sigg   allocatedPtr =
431a5f9cda1SChristian Sigg       rewriter.create<LLVM::BitcastOp>(loc, elementPtrType, allocatedPtr);
432a5f9cda1SChristian Sigg 
433a5f9cda1SChristian Sigg   // No alignment.
434a5f9cda1SChristian Sigg   Value alignedPtr = allocatedPtr;
435a5f9cda1SChristian Sigg 
436a5f9cda1SChristian Sigg   // Create the MemRef descriptor.
437a5f9cda1SChristian Sigg   auto memRefDescriptor = this->createMemRefDescriptor(
438a5f9cda1SChristian Sigg       loc, memRefType, allocatedPtr, alignedPtr, shape, strides, rewriter);
439a5f9cda1SChristian Sigg 
440a5f9cda1SChristian Sigg   rewriter.replaceOp(allocOp, {memRefDescriptor, stream});
441a5f9cda1SChristian Sigg 
442a5f9cda1SChristian Sigg   return success();
443a5f9cda1SChristian Sigg }
444a5f9cda1SChristian Sigg 
445a5f9cda1SChristian Sigg LogicalResult ConvertDeallocOpToGpuRuntimeCallPattern::matchAndRewrite(
446a5f9cda1SChristian Sigg     gpu::DeallocOp deallocOp, ArrayRef<Value> operands,
447a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
448a5f9cda1SChristian Sigg   if (failed(areAllLLVMTypes(deallocOp, operands, rewriter)) ||
449a5f9cda1SChristian Sigg       failed(isAsyncWithOneDependency(rewriter, deallocOp)))
450a5f9cda1SChristian Sigg     return failure();
451a5f9cda1SChristian Sigg 
452a5f9cda1SChristian Sigg   Location loc = deallocOp.getLoc();
453a5f9cda1SChristian Sigg 
454a5f9cda1SChristian Sigg   auto adaptor =
455a5f9cda1SChristian Sigg       gpu::DeallocOpAdaptor(operands, deallocOp->getAttrDictionary());
456a5f9cda1SChristian Sigg   Value pointer =
457a5f9cda1SChristian Sigg       MemRefDescriptor(adaptor.memref()).allocatedPtr(rewriter, loc);
458a5f9cda1SChristian Sigg   auto casted = rewriter.create<LLVM::BitcastOp>(loc, llvmPointerType, pointer);
459a5f9cda1SChristian Sigg   Value stream = adaptor.asyncDependencies().front();
460a5f9cda1SChristian Sigg   deallocCallBuilder.create(loc, rewriter, {casted, stream});
461a5f9cda1SChristian Sigg 
462a5f9cda1SChristian Sigg   rewriter.replaceOp(deallocOp, {stream});
463a5f9cda1SChristian Sigg   return success();
464a5f9cda1SChristian Sigg }
465a5f9cda1SChristian Sigg 
466a5f9cda1SChristian Sigg static bool isGpuAsyncTokenType(Value value) {
467a5f9cda1SChristian Sigg   return value.getType().isa<gpu::AsyncTokenType>();
468a5f9cda1SChristian Sigg }
469a5f9cda1SChristian Sigg 
470a5f9cda1SChristian Sigg // Converts !gpu.async.token operands of `async.yield` to runtime calls. The
471a5f9cda1SChristian Sigg // !gpu.async.token are lowered to stream within the async.execute region, but
472a5f9cda1SChristian Sigg // are passed as events between them. For each !gpu.async.token operand, we
473a5f9cda1SChristian Sigg // create an event and record it on the stream.
474a5f9cda1SChristian Sigg LogicalResult ConvertAsyncYieldToGpuRuntimeCallPattern::matchAndRewrite(
475a5f9cda1SChristian Sigg     async::YieldOp yieldOp, ArrayRef<Value> operands,
476a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
477a5f9cda1SChristian Sigg   if (llvm::none_of(yieldOp.operands(), isGpuAsyncTokenType))
478a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(yieldOp, "no gpu async token operand");
479a5f9cda1SChristian Sigg 
480a5f9cda1SChristian Sigg   Location loc = yieldOp.getLoc();
481a5f9cda1SChristian Sigg   SmallVector<Value, 4> newOperands(operands.begin(), operands.end());
482a5f9cda1SChristian Sigg   llvm::SmallDenseSet<Value> streams;
483a5f9cda1SChristian Sigg   for (auto &operand : yieldOp->getOpOperands()) {
484a5f9cda1SChristian Sigg     if (!isGpuAsyncTokenType(operand.get()))
485a5f9cda1SChristian Sigg       continue;
486a5f9cda1SChristian Sigg     auto idx = operand.getOperandNumber();
487a5f9cda1SChristian Sigg     auto stream = operands[idx];
488a5f9cda1SChristian Sigg     auto event = eventCreateCallBuilder.create(loc, rewriter, {}).getResult(0);
489a5f9cda1SChristian Sigg     eventRecordCallBuilder.create(loc, rewriter, {event, stream});
490a5f9cda1SChristian Sigg     newOperands[idx] = event;
491a5f9cda1SChristian Sigg     streams.insert(stream);
492a5f9cda1SChristian Sigg   }
493a5f9cda1SChristian Sigg   for (auto stream : streams)
494a5f9cda1SChristian Sigg     streamDestroyCallBuilder.create(loc, rewriter, {stream});
495a5f9cda1SChristian Sigg 
496a5f9cda1SChristian Sigg   rewriter.updateRootInPlace(yieldOp,
497a5f9cda1SChristian Sigg                              [&] { yieldOp->setOperands(newOperands); });
498a5f9cda1SChristian Sigg   return success();
499a5f9cda1SChristian Sigg }
500a5f9cda1SChristian Sigg 
501a5f9cda1SChristian Sigg // Returns whether `value` is the result of an LLVM::CallOp to `functionName`.
502a5f9cda1SChristian Sigg static bool isDefinedByCallTo(Value value, StringRef functionName) {
503a5f9cda1SChristian Sigg   assert(value.getType().isa<LLVM::LLVMPointerType>());
504a5f9cda1SChristian Sigg   if (auto defOp = value.getDefiningOp<LLVM::CallOp>())
505a5f9cda1SChristian Sigg     return defOp.callee()->equals(functionName);
506a5f9cda1SChristian Sigg   return false;
507a5f9cda1SChristian Sigg }
508a5f9cda1SChristian Sigg 
509a5f9cda1SChristian Sigg // Converts `gpu.wait` to runtime calls. The converted op synchronizes the host
510a5f9cda1SChristian Sigg // with the stream/event operands. The operands are destroyed. That is, it
511a5f9cda1SChristian Sigg // assumes that it is not used afterwards or elsewhere. Otherwise we will get a
512a5f9cda1SChristian Sigg // runtime error. Eventually, we should guarantee this property.
513a5f9cda1SChristian Sigg LogicalResult ConvertWaitOpToGpuRuntimeCallPattern::matchAndRewrite(
514a5f9cda1SChristian Sigg     gpu::WaitOp waitOp, ArrayRef<Value> operands,
515a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
516a5f9cda1SChristian Sigg   if (waitOp.asyncToken())
517a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(waitOp, "Cannot convert async op.");
518a5f9cda1SChristian Sigg 
519a5f9cda1SChristian Sigg   Location loc = waitOp.getLoc();
520a5f9cda1SChristian Sigg 
521a5f9cda1SChristian Sigg   for (auto operand : operands) {
522a5f9cda1SChristian Sigg     if (isDefinedByCallTo(operand, streamCreateCallBuilder.functionName)) {
523a5f9cda1SChristian Sigg       // The converted operand's definition created a stream.
524a5f9cda1SChristian Sigg       streamSynchronizeCallBuilder.create(loc, rewriter, {operand});
525a5f9cda1SChristian Sigg       streamDestroyCallBuilder.create(loc, rewriter, {operand});
526a5f9cda1SChristian Sigg     } else {
527a5f9cda1SChristian Sigg       // Otherwise the converted operand is an event. This assumes that we use
528a5f9cda1SChristian Sigg       // events in control flow code as well.
529a5f9cda1SChristian Sigg       eventSynchronizeCallBuilder.create(loc, rewriter, {operand});
530a5f9cda1SChristian Sigg       eventDestroyCallBuilder.create(loc, rewriter, {operand});
531a5f9cda1SChristian Sigg     }
532a5f9cda1SChristian Sigg   }
533a5f9cda1SChristian Sigg 
534a5f9cda1SChristian Sigg   rewriter.eraseOp(waitOp);
535a5f9cda1SChristian Sigg   return success();
536a5f9cda1SChristian Sigg }
537a5f9cda1SChristian Sigg 
538a5f9cda1SChristian Sigg // Converts `gpu.wait async` to runtime calls. The converted op creates a new
539a5f9cda1SChristian Sigg // stream that is synchronized with stream/event operands. The operands are
540a5f9cda1SChristian Sigg // destroyed. That is, it assumes that it is not used afterwards or elsewhere.
541a5f9cda1SChristian Sigg // Otherwise we will get a runtime error. Eventually, we should guarantee this
542a5f9cda1SChristian Sigg // property.
543a5f9cda1SChristian Sigg LogicalResult ConvertWaitAsyncOpToGpuRuntimeCallPattern::matchAndRewrite(
544a5f9cda1SChristian Sigg     gpu::WaitOp waitOp, ArrayRef<Value> operands,
545a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
546a5f9cda1SChristian Sigg   if (!waitOp.asyncToken())
547a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(waitOp, "Can only convert async op.");
548a5f9cda1SChristian Sigg 
549a5f9cda1SChristian Sigg   Location loc = waitOp.getLoc();
550a5f9cda1SChristian Sigg 
551a5f9cda1SChristian Sigg   auto insertionPoint = rewriter.saveInsertionPoint();
552a5f9cda1SChristian Sigg   SmallVector<Value, 1> events;
553a5f9cda1SChristian Sigg   for (auto pair : llvm::zip(waitOp.asyncDependencies(), operands)) {
554a5f9cda1SChristian Sigg     auto operand = std::get<1>(pair);
555a5f9cda1SChristian Sigg     if (isDefinedByCallTo(operand, streamCreateCallBuilder.functionName)) {
556a5f9cda1SChristian Sigg       // The converted operand's definition created a stream. Insert an event
557a5f9cda1SChristian Sigg       // into the stream just after the last use of the original token operand.
558a5f9cda1SChristian Sigg       auto *defOp = std::get<0>(pair).getDefiningOp();
559a5f9cda1SChristian Sigg       rewriter.setInsertionPointAfter(defOp);
560a5f9cda1SChristian Sigg       auto event =
561a5f9cda1SChristian Sigg           eventCreateCallBuilder.create(loc, rewriter, {}).getResult(0);
562a5f9cda1SChristian Sigg       eventRecordCallBuilder.create(loc, rewriter, {event, operand});
563a5f9cda1SChristian Sigg       events.push_back(event);
564a5f9cda1SChristian Sigg     } else {
565a5f9cda1SChristian Sigg       // Otherwise the converted operand is an event. This assumes that we use
566a5f9cda1SChristian Sigg       // events in control flow code as well.
567a5f9cda1SChristian Sigg       events.push_back(operand);
568a5f9cda1SChristian Sigg     }
569a5f9cda1SChristian Sigg   }
570a5f9cda1SChristian Sigg   rewriter.restoreInsertionPoint(insertionPoint);
571a5f9cda1SChristian Sigg   auto stream = streamCreateCallBuilder.create(loc, rewriter, {}).getResult(0);
572a5f9cda1SChristian Sigg   for (auto event : events)
573a5f9cda1SChristian Sigg     streamWaitEventCallBuilder.create(loc, rewriter, {stream, event});
574a5f9cda1SChristian Sigg   for (auto event : events)
575a5f9cda1SChristian Sigg     eventDestroyCallBuilder.create(loc, rewriter, {event});
576a5f9cda1SChristian Sigg   rewriter.replaceOp(waitOp, {stream});
577a5f9cda1SChristian Sigg 
578a5f9cda1SChristian Sigg   return success();
579a5f9cda1SChristian Sigg }
580a5f9cda1SChristian Sigg 
581a5f9cda1SChristian Sigg // Creates a struct containing all kernel parameters on the stack and returns
582a5f9cda1SChristian Sigg // an array of type-erased pointers to the fields of the struct. The array can
583a5f9cda1SChristian Sigg // then be passed to the CUDA / ROCm (HIP) kernel launch calls.
584a5f9cda1SChristian Sigg // The generated code is essentially as follows:
585a5f9cda1SChristian Sigg //
586a5f9cda1SChristian Sigg // %struct = alloca(sizeof(struct { Parameters... }))
587a5f9cda1SChristian Sigg // %array = alloca(NumParameters * sizeof(void *))
588a5f9cda1SChristian Sigg // for (i : [0, NumParameters))
589a5f9cda1SChristian Sigg //   %fieldPtr = llvm.getelementptr %struct[0, i]
590a5f9cda1SChristian Sigg //   llvm.store parameters[i], %fieldPtr
591a5f9cda1SChristian Sigg //   %elementPtr = llvm.getelementptr %array[i]
592a5f9cda1SChristian Sigg //   llvm.store %fieldPtr, %elementPtr
593a5f9cda1SChristian Sigg // return %array
594a5f9cda1SChristian Sigg Value ConvertLaunchFuncOpToGpuRuntimeCallPattern::generateParamsArray(
595a5f9cda1SChristian Sigg     gpu::LaunchFuncOp launchOp, ArrayRef<Value> operands,
596a5f9cda1SChristian Sigg     OpBuilder &builder) const {
597a5f9cda1SChristian Sigg   auto loc = launchOp.getLoc();
598a5f9cda1SChristian Sigg   auto numKernelOperands = launchOp.getNumKernelOperands();
599a5f9cda1SChristian Sigg   auto arguments = getTypeConverter()->promoteOperands(
600a5f9cda1SChristian Sigg       loc, launchOp.getOperands().take_back(numKernelOperands),
601a5f9cda1SChristian Sigg       operands.take_back(numKernelOperands), builder);
602a5f9cda1SChristian Sigg   auto numArguments = arguments.size();
603a5f9cda1SChristian Sigg   SmallVector<Type, 4> argumentTypes;
604a5f9cda1SChristian Sigg   argumentTypes.reserve(numArguments);
605a5f9cda1SChristian Sigg   for (auto argument : arguments)
606a5f9cda1SChristian Sigg     argumentTypes.push_back(argument.getType());
607a5f9cda1SChristian Sigg   auto structType = LLVM::LLVMStructType::getNewIdentified(context, StringRef(),
608a5f9cda1SChristian Sigg                                                            argumentTypes);
609a5f9cda1SChristian Sigg   auto one = builder.create<LLVM::ConstantOp>(loc, llvmInt32Type,
610a5f9cda1SChristian Sigg                                               builder.getI32IntegerAttr(1));
611a5f9cda1SChristian Sigg   auto structPtr = builder.create<LLVM::AllocaOp>(
612a5f9cda1SChristian Sigg       loc, LLVM::LLVMPointerType::get(structType), one, /*alignment=*/0);
613a5f9cda1SChristian Sigg   auto arraySize = builder.create<LLVM::ConstantOp>(
614a5f9cda1SChristian Sigg       loc, llvmInt32Type, builder.getI32IntegerAttr(numArguments));
615a5f9cda1SChristian Sigg   auto arrayPtr = builder.create<LLVM::AllocaOp>(loc, llvmPointerPointerType,
616a5f9cda1SChristian Sigg                                                  arraySize, /*alignment=*/0);
617a5f9cda1SChristian Sigg   auto zero = builder.create<LLVM::ConstantOp>(loc, llvmInt32Type,
618a5f9cda1SChristian Sigg                                                builder.getI32IntegerAttr(0));
619a5f9cda1SChristian Sigg   for (auto en : llvm::enumerate(arguments)) {
620a5f9cda1SChristian Sigg     auto index = builder.create<LLVM::ConstantOp>(
621a5f9cda1SChristian Sigg         loc, llvmInt32Type, builder.getI32IntegerAttr(en.index()));
622a5f9cda1SChristian Sigg     auto fieldPtr = builder.create<LLVM::GEPOp>(
623a5f9cda1SChristian Sigg         loc, LLVM::LLVMPointerType::get(argumentTypes[en.index()]), structPtr,
624a5f9cda1SChristian Sigg         ArrayRef<Value>{zero, index.getResult()});
625a5f9cda1SChristian Sigg     builder.create<LLVM::StoreOp>(loc, en.value(), fieldPtr);
626a5f9cda1SChristian Sigg     auto elementPtr = builder.create<LLVM::GEPOp>(loc, llvmPointerPointerType,
627a5f9cda1SChristian Sigg                                                   arrayPtr, index.getResult());
628a5f9cda1SChristian Sigg     auto casted =
629a5f9cda1SChristian Sigg         builder.create<LLVM::BitcastOp>(loc, llvmPointerType, fieldPtr);
630a5f9cda1SChristian Sigg     builder.create<LLVM::StoreOp>(loc, casted, elementPtr);
631a5f9cda1SChristian Sigg   }
632a5f9cda1SChristian Sigg   return arrayPtr;
633a5f9cda1SChristian Sigg }
634a5f9cda1SChristian Sigg 
635a5f9cda1SChristian Sigg // Generates an LLVM IR dialect global that contains the name of the given
636a5f9cda1SChristian Sigg // kernel function as a C string, and returns a pointer to its beginning.
637a5f9cda1SChristian Sigg // The code is essentially:
638a5f9cda1SChristian Sigg //
639a5f9cda1SChristian Sigg // llvm.global constant @kernel_name("function_name\00")
640a5f9cda1SChristian Sigg // func(...) {
641a5f9cda1SChristian Sigg //   %0 = llvm.addressof @kernel_name
642a5f9cda1SChristian Sigg //   %1 = llvm.constant (0 : index)
643a5f9cda1SChristian Sigg //   %2 = llvm.getelementptr %0[%1, %1] : !llvm<"i8*">
644a5f9cda1SChristian Sigg // }
645a5f9cda1SChristian Sigg Value ConvertLaunchFuncOpToGpuRuntimeCallPattern::generateKernelNameConstant(
646a5f9cda1SChristian Sigg     StringRef moduleName, StringRef name, Location loc,
647a5f9cda1SChristian Sigg     OpBuilder &builder) const {
648a5f9cda1SChristian Sigg   // Make sure the trailing zero is included in the constant.
649a5f9cda1SChristian Sigg   std::vector<char> kernelName(name.begin(), name.end());
650a5f9cda1SChristian Sigg   kernelName.push_back('\0');
651a5f9cda1SChristian Sigg 
652a5f9cda1SChristian Sigg   std::string globalName =
653a5f9cda1SChristian Sigg       std::string(llvm::formatv("{0}_{1}_kernel_name", moduleName, name));
654a5f9cda1SChristian Sigg   return LLVM::createGlobalString(
655a5f9cda1SChristian Sigg       loc, builder, globalName, StringRef(kernelName.data(), kernelName.size()),
656a5f9cda1SChristian Sigg       LLVM::Linkage::Internal);
657a5f9cda1SChristian Sigg }
658a5f9cda1SChristian Sigg 
659a5f9cda1SChristian Sigg // Emits LLVM IR to launch a kernel function. Expects the module that contains
660a5f9cda1SChristian Sigg // the compiled kernel function as a cubin in the 'nvvm.cubin' attribute, or a
661a5f9cda1SChristian Sigg // hsaco in the 'rocdl.hsaco' attribute of the kernel function in the IR.
662a5f9cda1SChristian Sigg //
663a5f9cda1SChristian Sigg // %0 = call %binarygetter
664a5f9cda1SChristian Sigg // %1 = call %moduleLoad(%0)
665a5f9cda1SChristian Sigg // %2 = <see generateKernelNameConstant>
666a5f9cda1SChristian Sigg // %3 = call %moduleGetFunction(%1, %2)
667a5f9cda1SChristian Sigg // %4 = call %streamCreate()
668a5f9cda1SChristian Sigg // %5 = <see generateParamsArray>
669a5f9cda1SChristian Sigg // call %launchKernel(%3, <launchOp operands 0..5>, 0, %4, %5, nullptr)
670a5f9cda1SChristian Sigg // call %streamSynchronize(%4)
671a5f9cda1SChristian Sigg // call %streamDestroy(%4)
672a5f9cda1SChristian Sigg // call %moduleUnload(%1)
673a5f9cda1SChristian Sigg //
674a5f9cda1SChristian Sigg // If the op is async, the stream corresponds to the (single) async dependency
675a5f9cda1SChristian Sigg // as well as the async token the op produces.
676a5f9cda1SChristian Sigg LogicalResult ConvertLaunchFuncOpToGpuRuntimeCallPattern::matchAndRewrite(
677a5f9cda1SChristian Sigg     gpu::LaunchFuncOp launchOp, ArrayRef<Value> operands,
678a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
679a5f9cda1SChristian Sigg   if (failed(areAllLLVMTypes(launchOp, operands, rewriter)))
680a5f9cda1SChristian Sigg     return failure();
681a5f9cda1SChristian Sigg 
682a5f9cda1SChristian Sigg   if (launchOp.asyncDependencies().size() > 1)
683a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(
684a5f9cda1SChristian Sigg         launchOp, "Cannot convert with more than one async dependency.");
685a5f9cda1SChristian Sigg 
686a5f9cda1SChristian Sigg   // Fail when the synchronous version of the op has async dependencies. The
687a5f9cda1SChristian Sigg   // lowering destroys the stream, and we do not want to check that there is no
688a5f9cda1SChristian Sigg   // use of the stream after this op.
689a5f9cda1SChristian Sigg   if (!launchOp.asyncToken() && !launchOp.asyncDependencies().empty())
690a5f9cda1SChristian Sigg     return rewriter.notifyMatchFailure(
691a5f9cda1SChristian Sigg         launchOp, "Cannot convert non-async op with async dependencies.");
692a5f9cda1SChristian Sigg 
693a5f9cda1SChristian Sigg   Location loc = launchOp.getLoc();
694a5f9cda1SChristian Sigg 
695a5f9cda1SChristian Sigg   // Create an LLVM global with CUBIN extracted from the kernel annotation and
696a5f9cda1SChristian Sigg   // obtain a pointer to the first byte in it.
697a5f9cda1SChristian Sigg   auto kernelModule = SymbolTable::lookupNearestSymbolFrom<gpu::GPUModuleOp>(
698a5f9cda1SChristian Sigg       launchOp, launchOp.getKernelModuleName());
699a5f9cda1SChristian Sigg   assert(kernelModule && "expected a kernel module");
700a5f9cda1SChristian Sigg 
701a5f9cda1SChristian Sigg   auto binaryAttr =
702a5f9cda1SChristian Sigg       kernelModule->getAttrOfType<StringAttr>(gpuBinaryAnnotation);
703a5f9cda1SChristian Sigg   if (!binaryAttr) {
704a5f9cda1SChristian Sigg     kernelModule.emitOpError()
705a5f9cda1SChristian Sigg         << "missing " << gpuBinaryAnnotation << " attribute";
706a5f9cda1SChristian Sigg     return failure();
707a5f9cda1SChristian Sigg   }
708a5f9cda1SChristian Sigg 
709a5f9cda1SChristian Sigg   SmallString<128> nameBuffer(kernelModule.getName());
710a5f9cda1SChristian Sigg   nameBuffer.append(kGpuBinaryStorageSuffix);
711a5f9cda1SChristian Sigg   Value data =
712a5f9cda1SChristian Sigg       LLVM::createGlobalString(loc, rewriter, nameBuffer.str(),
713a5f9cda1SChristian Sigg                                binaryAttr.getValue(), LLVM::Linkage::Internal);
714a5f9cda1SChristian Sigg 
715a5f9cda1SChristian Sigg   auto module = moduleLoadCallBuilder.create(loc, rewriter, data);
716a5f9cda1SChristian Sigg   // Get the function from the module. The name corresponds to the name of
717a5f9cda1SChristian Sigg   // the kernel function.
718a5f9cda1SChristian Sigg   auto kernelName = generateKernelNameConstant(
719a5f9cda1SChristian Sigg       launchOp.getKernelModuleName(), launchOp.getKernelName(), loc, rewriter);
720a5f9cda1SChristian Sigg   auto function = moduleGetFunctionCallBuilder.create(
721a5f9cda1SChristian Sigg       loc, rewriter, {module.getResult(0), kernelName});
722a5f9cda1SChristian Sigg   auto zero = rewriter.create<LLVM::ConstantOp>(loc, llvmInt32Type,
723a5f9cda1SChristian Sigg                                                 rewriter.getI32IntegerAttr(0));
724a5f9cda1SChristian Sigg   auto adaptor =
725a5f9cda1SChristian Sigg       gpu::LaunchFuncOpAdaptor(operands, launchOp->getAttrDictionary());
726a5f9cda1SChristian Sigg   Value stream =
727a5f9cda1SChristian Sigg       adaptor.asyncDependencies().empty()
728a5f9cda1SChristian Sigg           ? streamCreateCallBuilder.create(loc, rewriter, {}).getResult(0)
729a5f9cda1SChristian Sigg           : adaptor.asyncDependencies().front();
730a5f9cda1SChristian Sigg   // Create array of pointers to kernel arguments.
731a5f9cda1SChristian Sigg   auto kernelParams = generateParamsArray(launchOp, operands, rewriter);
732a5f9cda1SChristian Sigg   auto nullpointer = rewriter.create<LLVM::NullOp>(loc, llvmPointerPointerType);
733a5f9cda1SChristian Sigg   launchKernelCallBuilder.create(loc, rewriter,
734a5f9cda1SChristian Sigg                                  {function.getResult(0), launchOp.gridSizeX(),
735a5f9cda1SChristian Sigg                                   launchOp.gridSizeY(), launchOp.gridSizeZ(),
736a5f9cda1SChristian Sigg                                   launchOp.blockSizeX(), launchOp.blockSizeY(),
737a5f9cda1SChristian Sigg                                   launchOp.blockSizeZ(),
738a5f9cda1SChristian Sigg                                   /*sharedMemBytes=*/zero, stream, kernelParams,
739a5f9cda1SChristian Sigg                                   /*extra=*/nullpointer});
740a5f9cda1SChristian Sigg 
741a5f9cda1SChristian Sigg   if (launchOp.asyncToken()) {
742a5f9cda1SChristian Sigg     // Async launch: make dependent ops use the same stream.
743a5f9cda1SChristian Sigg     rewriter.replaceOp(launchOp, {stream});
744a5f9cda1SChristian Sigg   } else {
745a5f9cda1SChristian Sigg     // Synchronize with host and destroy stream. This must be the stream created
746a5f9cda1SChristian Sigg     // above (with no other uses) because we check that the synchronous version
747a5f9cda1SChristian Sigg     // does not have any async dependencies.
748a5f9cda1SChristian Sigg     streamSynchronizeCallBuilder.create(loc, rewriter, stream);
749a5f9cda1SChristian Sigg     streamDestroyCallBuilder.create(loc, rewriter, stream);
750a5f9cda1SChristian Sigg     rewriter.eraseOp(launchOp);
751a5f9cda1SChristian Sigg   }
752a5f9cda1SChristian Sigg   moduleUnloadCallBuilder.create(loc, rewriter, module.getResult(0));
753a5f9cda1SChristian Sigg 
754a5f9cda1SChristian Sigg   return success();
755a5f9cda1SChristian Sigg }
756a5f9cda1SChristian Sigg 
757a5f9cda1SChristian Sigg LogicalResult ConvertMemcpyOpToGpuRuntimeCallPattern::matchAndRewrite(
758a5f9cda1SChristian Sigg     gpu::MemcpyOp memcpyOp, ArrayRef<Value> operands,
759a5f9cda1SChristian Sigg     ConversionPatternRewriter &rewriter) const {
760a5f9cda1SChristian Sigg   auto memRefType = memcpyOp.src().getType().cast<MemRefType>();
761a5f9cda1SChristian Sigg 
762a5f9cda1SChristian Sigg   if (failed(areAllLLVMTypes(memcpyOp, operands, rewriter)) ||
763a5f9cda1SChristian Sigg       !isConvertibleAndHasIdentityMaps(memRefType) ||
764a5f9cda1SChristian Sigg       failed(isAsyncWithOneDependency(rewriter, memcpyOp)))
765a5f9cda1SChristian Sigg     return failure();
766a5f9cda1SChristian Sigg 
767a5f9cda1SChristian Sigg   auto loc = memcpyOp.getLoc();
768a5f9cda1SChristian Sigg   auto adaptor = gpu::MemcpyOpAdaptor(operands, memcpyOp->getAttrDictionary());
769a5f9cda1SChristian Sigg 
770a5f9cda1SChristian Sigg   MemRefDescriptor srcDesc(adaptor.src());
771a5f9cda1SChristian Sigg 
772a5f9cda1SChristian Sigg   Value numElements =
773a5f9cda1SChristian Sigg       memRefType.hasStaticShape()
774a5f9cda1SChristian Sigg           ? createIndexConstant(rewriter, loc, memRefType.getNumElements())
775a5f9cda1SChristian Sigg           // For identity layouts (verified above), the number of elements is
776a5f9cda1SChristian Sigg           // stride[0] * size[0].
777a5f9cda1SChristian Sigg           : rewriter.create<LLVM::MulOp>(loc, srcDesc.stride(rewriter, loc, 0),
778a5f9cda1SChristian Sigg                                          srcDesc.size(rewriter, loc, 0));
779a5f9cda1SChristian Sigg 
780a5f9cda1SChristian Sigg   Type elementPtrType = getElementPtrType(memRefType);
781a5f9cda1SChristian Sigg   Value nullPtr = rewriter.create<LLVM::NullOp>(loc, elementPtrType);
782a5f9cda1SChristian Sigg   Value gepPtr = rewriter.create<LLVM::GEPOp>(
783a5f9cda1SChristian Sigg       loc, elementPtrType, ArrayRef<Value>{nullPtr, numElements});
784a5f9cda1SChristian Sigg   auto sizeBytes =
785a5f9cda1SChristian Sigg       rewriter.create<LLVM::PtrToIntOp>(loc, getIndexType(), gepPtr);
786a5f9cda1SChristian Sigg 
787a5f9cda1SChristian Sigg   auto src = rewriter.create<LLVM::BitcastOp>(
788a5f9cda1SChristian Sigg       loc, llvmPointerType, srcDesc.alignedPtr(rewriter, loc));
789a5f9cda1SChristian Sigg   auto dst = rewriter.create<LLVM::BitcastOp>(
790a5f9cda1SChristian Sigg       loc, llvmPointerType,
791a5f9cda1SChristian Sigg       MemRefDescriptor(adaptor.dst()).alignedPtr(rewriter, loc));
792a5f9cda1SChristian Sigg 
793a5f9cda1SChristian Sigg   auto stream = adaptor.asyncDependencies().front();
794a5f9cda1SChristian Sigg   memcpyCallBuilder.create(loc, rewriter, {dst, src, sizeBytes, stream});
795a5f9cda1SChristian Sigg 
796a5f9cda1SChristian Sigg   rewriter.replaceOp(memcpyOp, {stream});
797a5f9cda1SChristian Sigg 
798a5f9cda1SChristian Sigg   return success();
799a5f9cda1SChristian Sigg }
800a5f9cda1SChristian Sigg 
801a5f9cda1SChristian Sigg std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
802a5f9cda1SChristian Sigg mlir::createGpuToLLVMConversionPass() {
803a5f9cda1SChristian Sigg   return std::make_unique<GpuToLLVMConversionPass>();
804a5f9cda1SChristian Sigg }
805