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