blob: 0678f14e7db3f3fe1e015f1b53f71f48b927ddc0 [file] [log] [blame]
Peter Collingbournefe883422011-10-06 18:29:37 +00001//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbournefe883422011-10-06 18:29:37 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for CUDA code generation targeting the NVIDIA CUDA
10// runtime library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCUDARuntime.h"
Peter Collingbournefa4d6032011-10-06 18:51:56 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/Decl.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000019#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000022#include "llvm/Support/Format.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000023
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
Yaxun Liu29155b02018-05-18 15:07:56 +000028constexpr unsigned CudaFatMagic = 0x466243b1;
29constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
Peter Collingbournefe883422011-10-06 18:29:37 +000030
31class CGNVCUDARuntime : public CGCUDARuntime {
Peter Collingbournefa4d6032011-10-06 18:51:56 +000032
33private:
John McCall6c9f1fdb2016-11-19 08:17:24 +000034 llvm::IntegerType *IntTy, *SizeTy;
35 llvm::Type *VoidTy;
Artem Belevich52cc4872015-05-07 19:34:16 +000036 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
37
38 /// Convenience reference to LLVM Context
39 llvm::LLVMContext &Context;
40 /// Convenience reference to the current module
41 llvm::Module &TheModule;
42 /// Keeps track of kernel launch stubs emitted in this module
43 llvm::SmallVector<llvm::Function *, 16> EmittedKernels;
Artem Belevich42e19492016-03-02 18:28:50 +000044 llvm::SmallVector<std::pair<llvm::GlobalVariable *, unsigned>, 16> DeviceVars;
Jonas Hahnfelde7681322018-02-28 17:53:46 +000045 /// Keeps track of variable containing handle of GPU binary. Populated by
Artem Belevich52cc4872015-05-07 19:34:16 +000046 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
47 /// ModuleDtorFunction()
Jonas Hahnfelde7681322018-02-28 17:53:46 +000048 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000049 /// Whether we generate relocatable device code.
50 bool RelocatableDeviceCode;
Peter Collingbournefa4d6032011-10-06 18:51:56 +000051
52 llvm::Constant *getSetupArgumentFn() const;
53 llvm::Constant *getLaunchFn() const;
54
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000055 llvm::FunctionType *getRegisterGlobalsFnTy() const;
56 llvm::FunctionType *getCallbackFnTy() const;
57 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
Yaxun Liu887c5692018-04-25 01:10:37 +000058 std::string addPrefixToName(StringRef FuncName) const;
59 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000060
Artem Belevich52cc4872015-05-07 19:34:16 +000061 /// Creates a function to register all kernel stubs generated in this module.
Artem Belevich42e19492016-03-02 18:28:50 +000062 llvm::Function *makeRegisterGlobalsFn();
Artem Belevich52cc4872015-05-07 19:34:16 +000063
64 /// Helper function that generates a constant string and returns a pointer to
65 /// the start of the string. The result of this function can be used anywhere
66 /// where the C code specifies const char*.
67 llvm::Constant *makeConstantString(const std::string &Str,
68 const std::string &Name = "",
Artem Belevich4c093182016-08-12 18:44:01 +000069 const std::string &SectionName = "",
Artem Belevich52cc4872015-05-07 19:34:16 +000070 unsigned Alignment = 0) {
71 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
72 llvm::ConstantInt::get(SizeTy, 0)};
John McCall7f416cc2015-09-08 08:05:57 +000073 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Artem Belevich4c093182016-08-12 18:44:01 +000074 llvm::GlobalVariable *GV =
75 cast<llvm::GlobalVariable>(ConstStr.getPointer());
Jonas Hahnfeld3b9cbba92018-06-08 11:17:08 +000076 if (!SectionName.empty()) {
Artem Belevich4c093182016-08-12 18:44:01 +000077 GV->setSection(SectionName);
Jonas Hahnfeld3b9cbba92018-06-08 11:17:08 +000078 // Mark the address as used which make sure that this section isn't
79 // merged and we will really have it in the object file.
80 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
81 }
Artem Belevich4c093182016-08-12 18:44:01 +000082 if (Alignment)
83 GV->setAlignment(Alignment);
84
John McCall7f416cc2015-09-08 08:05:57 +000085 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
86 ConstStr.getPointer(), Zeros);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000087 }
88
89 /// Helper function that generates an empty dummy function returning void.
90 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
91 assert(FnTy->getReturnType()->isVoidTy() &&
92 "Can only generate dummy functions returning void!");
93 llvm::Function *DummyFunc = llvm::Function::Create(
94 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
95
96 llvm::BasicBlock *DummyBlock =
97 llvm::BasicBlock::Create(Context, "", DummyFunc);
98 CGBuilderTy FuncBuilder(CGM, Context);
99 FuncBuilder.SetInsertPoint(DummyBlock);
100 FuncBuilder.CreateRetVoid();
101
102 return DummyFunc;
103 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000104
105 void emitDeviceStubBody(CodeGenFunction &CGF, FunctionArgList &Args);
106
Peter Collingbournefe883422011-10-06 18:29:37 +0000107public:
108 CGNVCUDARuntime(CodeGenModule &CGM);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000109
Artem Belevich52cc4872015-05-07 19:34:16 +0000110 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
Artem Belevich42e19492016-03-02 18:28:50 +0000111 void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags) override {
112 DeviceVars.push_back(std::make_pair(&Var, Flags));
113 }
114
Artem Belevich52cc4872015-05-07 19:34:16 +0000115 /// Creates module constructor function
116 llvm::Function *makeModuleCtorFunction() override;
117 /// Creates module destructor function
118 llvm::Function *makeModuleDtorFunction() override;
Peter Collingbournefe883422011-10-06 18:29:37 +0000119};
120
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000121}
Peter Collingbournefe883422011-10-06 18:29:37 +0000122
Yaxun Liu887c5692018-04-25 01:10:37 +0000123std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
124 if (CGM.getLangOpts().HIP)
125 return ((Twine("hip") + Twine(FuncName)).str());
126 return ((Twine("cuda") + Twine(FuncName)).str());
127}
128std::string
129CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
130 if (CGM.getLangOpts().HIP)
131 return ((Twine("__hip") + Twine(FuncName)).str());
132 return ((Twine("__cuda") + Twine(FuncName)).str());
133}
134
Artem Belevich52cc4872015-05-07 19:34:16 +0000135CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
136 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000137 TheModule(CGM.getModule()),
Yaxun Liu97670892018-10-02 17:48:54 +0000138 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode) {
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000139 CodeGen::CodeGenTypes &Types = CGM.getTypes();
140 ASTContext &Ctx = CGM.getContext();
141
John McCall6c9f1fdb2016-11-19 08:17:24 +0000142 IntTy = CGM.IntTy;
143 SizeTy = CGM.SizeTy;
144 VoidTy = CGM.VoidTy;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000145
146 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
147 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
Artem Belevich52cc4872015-05-07 19:34:16 +0000148 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000149}
150
151llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn() const {
152 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
Benjamin Kramer30934732016-07-02 11:41:41 +0000153 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
Yaxun Liu887c5692018-04-25 01:10:37 +0000154 return CGM.CreateRuntimeFunction(
155 llvm::FunctionType::get(IntTy, Params, false),
156 addPrefixToName("SetupArgument"));
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000157}
158
159llvm::Constant *CGNVCUDARuntime::getLaunchFn() const {
Yaxun Liu887c5692018-04-25 01:10:37 +0000160 if (CGM.getLangOpts().HIP) {
161 // hipError_t hipLaunchByPtr(char *);
162 return CGM.CreateRuntimeFunction(
163 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
164 } else {
165 // cudaError_t cudaLaunch(char *);
166 return CGM.CreateRuntimeFunction(
167 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
168 }
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000169}
170
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000171llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
172 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
173}
174
175llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
176 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
177}
178
179llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
180 auto CallbackFnTy = getCallbackFnTy();
181 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
182 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
183 VoidPtrTy, CallbackFnTy->getPointerTo()};
184 return llvm::FunctionType::get(VoidTy, Params, false);
185}
186
Artem Belevich52cc4872015-05-07 19:34:16 +0000187void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
188 FunctionArgList &Args) {
189 EmittedKernels.push_back(CGF.CurFn);
190 emitDeviceStubBody(CGF, Args);
191}
192
193void CGNVCUDARuntime::emitDeviceStubBody(CodeGenFunction &CGF,
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000194 FunctionArgList &Args) {
Justin Lebare56360a2016-07-27 22:36:21 +0000195 // Emit a call to cudaSetupArgument for each arg in Args.
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000196 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
Justin Lebare56360a2016-07-27 22:36:21 +0000197 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
198 CharUnits Offset = CharUnits::Zero();
199 for (const VarDecl *A : Args) {
200 CharUnits TyWidth, TyAlign;
201 std::tie(TyWidth, TyAlign) =
202 CGM.getContext().getTypeInfoInChars(A->getType());
203 Offset = Offset.alignTo(TyAlign);
204 llvm::Value *Args[] = {
205 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
206 VoidPtrTy),
207 llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
208 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
209 };
James Y Knight3933add2019-01-30 02:54:28 +0000210 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000211 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
James Y Knight3933add2019-01-30 02:54:28 +0000212 llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
Justin Lebare56360a2016-07-27 22:36:21 +0000213 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
James Y Knight3933add2019-01-30 02:54:28 +0000214 CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000215 CGF.EmitBlock(NextBlock);
Justin Lebare56360a2016-07-27 22:36:21 +0000216 Offset += TyWidth;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000217 }
218
219 // Emit the call to cudaLaunch
220 llvm::Constant *cudaLaunchFn = getLaunchFn();
221 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
John McCall882987f2013-02-28 19:01:20 +0000222 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000223 CGF.EmitBranch(EndBlock);
224
225 CGF.EmitBlock(EndBlock);
Peter Collingbournefe883422011-10-06 18:29:37 +0000226}
227
Artem Belevich42e19492016-03-02 18:28:50 +0000228/// Creates a function that sets up state on the host side for CUDA objects that
229/// have a presence on both the host and device sides. Specifically, registers
230/// the host side of kernel functions and device global variables with the CUDA
231/// runtime.
Artem Belevich52cc4872015-05-07 19:34:16 +0000232/// \code
Artem Belevich42e19492016-03-02 18:28:50 +0000233/// void __cuda_register_globals(void** GpuBinaryHandle) {
Artem Belevich52cc4872015-05-07 19:34:16 +0000234/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
235/// ...
236/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
Artem Belevich42e19492016-03-02 18:28:50 +0000237/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
238/// ...
239/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
Artem Belevich52cc4872015-05-07 19:34:16 +0000240/// }
241/// \endcode
Artem Belevich42e19492016-03-02 18:28:50 +0000242llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000243 // No need to register anything
244 if (EmittedKernels.empty() && DeviceVars.empty())
245 return nullptr;
246
Artem Belevich52cc4872015-05-07 19:34:16 +0000247 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000248 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000249 addUnderscoredPrefixToName("_register_globals"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000250 llvm::BasicBlock *EntryBB =
251 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000252 CGBuilderTy Builder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000253 Builder.SetInsertPoint(EntryBB);
254
255 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
256 // int, uint3*, uint3*, dim3*, dim3*, int*)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000257 llvm::Type *RegisterFuncParams[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000258 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
259 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
260 llvm::Constant *RegisterFunc = CGM.CreateRuntimeFunction(
261 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000262 addUnderscoredPrefixToName("RegisterFunction"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000263
264 // Extract GpuBinaryHandle passed as the first argument passed to
Artem Belevich42e19492016-03-02 18:28:50 +0000265 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
Artem Belevich52cc4872015-05-07 19:34:16 +0000266 // each emitted kernel.
267 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
268 for (llvm::Function *Kernel : EmittedKernels) {
269 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
270 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
Artem Belevich42e19492016-03-02 18:28:50 +0000271 llvm::Value *Args[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000272 &GpuBinaryHandlePtr, Builder.CreateBitCast(Kernel, VoidPtrTy),
273 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
274 NullPtr, NullPtr, NullPtr,
275 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
Artem Belevich42e19492016-03-02 18:28:50 +0000276 Builder.CreateCall(RegisterFunc, Args);
277 }
278
279 // void __cudaRegisterVar(void **, char *, char *, const char *,
280 // int, int, int, int)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000281 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
282 CharPtrTy, IntTy, IntTy,
283 IntTy, IntTy};
Artem Belevich42e19492016-03-02 18:28:50 +0000284 llvm::Constant *RegisterVar = CGM.CreateRuntimeFunction(
285 llvm::FunctionType::get(IntTy, RegisterVarParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000286 addUnderscoredPrefixToName("RegisterVar"));
Artem Belevich42e19492016-03-02 18:28:50 +0000287 for (auto &Pair : DeviceVars) {
288 llvm::GlobalVariable *Var = Pair.first;
289 unsigned Flags = Pair.second;
290 llvm::Constant *VarName = makeConstantString(Var->getName());
291 uint64_t VarSize =
292 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
293 llvm::Value *Args[] = {
294 &GpuBinaryHandlePtr,
295 Builder.CreateBitCast(Var, VoidPtrTy),
296 VarName,
297 VarName,
298 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
299 llvm::ConstantInt::get(IntTy, VarSize),
300 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
301 llvm::ConstantInt::get(IntTy, 0)};
302 Builder.CreateCall(RegisterVar, Args);
Artem Belevich52cc4872015-05-07 19:34:16 +0000303 }
304
305 Builder.CreateRetVoid();
306 return RegisterKernelsFunc;
307}
308
309/// Creates a global constructor function for the module:
Yaxun Liuf99752b2018-07-20 22:45:24 +0000310///
311/// For CUDA:
Artem Belevich52cc4872015-05-07 19:34:16 +0000312/// \code
313/// void __cuda_module_ctor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000314/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
315/// __cuda_register_globals(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000316/// }
317/// \endcode
Yaxun Liuf99752b2018-07-20 22:45:24 +0000318///
319/// For HIP:
320/// \code
321/// void __hip_module_ctor(void*) {
322/// if (__hip_gpubin_handle == 0) {
323/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);
324/// __hip_register_globals(__hip_gpubin_handle);
325/// }
326/// }
327/// \endcode
Artem Belevich52cc4872015-05-07 19:34:16 +0000328llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
Yaxun Liu29155b02018-05-18 15:07:56 +0000329 bool IsHIP = CGM.getLangOpts().HIP;
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000330 // No need to generate ctors/dtors if there is no GPU binary.
Yaxun Liu29155b02018-05-18 15:07:56 +0000331 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
332 if (CudaGpuBinaryFileName.empty() && !IsHIP)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000333 return nullptr;
334
Yaxun Liu29155b02018-05-18 15:07:56 +0000335 // void __{cuda|hip}_register_globals(void* handle);
Artem Belevich42e19492016-03-02 18:28:50 +0000336 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000337 // We always need a function to pass in as callback. Create a dummy
338 // implementation if we don't need to register anything.
339 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
340 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
341
Yaxun Liu29155b02018-05-18 15:07:56 +0000342 // void ** __{cuda|hip}RegisterFatBinary(void *);
Artem Belevich52cc4872015-05-07 19:34:16 +0000343 llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
344 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000345 addUnderscoredPrefixToName("RegisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000346 // struct { int magic, int version, void * gpu_binary, void * dont_care };
347 llvm::StructType *FatbinWrapperTy =
Serge Guelton1d993272017-05-09 19:31:30 +0000348 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
Artem Belevich52cc4872015-05-07 19:34:16 +0000349
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000350 // Register GPU binary with the CUDA runtime, store returned handle in a
351 // global variable and save a reference in GpuBinaryHandle to be cleaned up
352 // in destructor on exit. Then associate all known kernels with the GPU binary
353 // handle so CUDA runtime can figure out what to call on the GPU side.
Yaxun Liu97670892018-10-02 17:48:54 +0000354 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
355 if (!CudaGpuBinaryFileName.empty()) {
Yaxun Liu29155b02018-05-18 15:07:56 +0000356 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
357 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
358 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
359 CGM.getDiags().Report(diag::err_cannot_open_file)
360 << CudaGpuBinaryFileName << EC.message();
361 return nullptr;
362 }
363 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000364 }
365
Artem Belevich52cc4872015-05-07 19:34:16 +0000366 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
367 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000368 llvm::GlobalValue::InternalLinkage,
369 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000370 llvm::BasicBlock *CtorEntryBB =
371 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000372 CGBuilderTy CtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000373
374 CtorBuilder.SetInsertPoint(CtorEntryBB);
375
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000376 const char *FatbinConstantName;
Yaxun Liu29155b02018-05-18 15:07:56 +0000377 const char *FatbinSectionName;
378 const char *ModuleIDSectionName;
379 StringRef ModuleIDPrefix;
380 llvm::Constant *FatBinStr;
381 unsigned FatMagic;
382 if (IsHIP) {
383 FatbinConstantName = ".hip_fatbin";
384 FatbinSectionName = ".hipFatBinSegment";
385
386 ModuleIDSectionName = "__hip_module_id";
387 ModuleIDPrefix = "__hip_";
388
Yaxun Liu97670892018-10-02 17:48:54 +0000389 if (CudaGpuBinary) {
390 // If fatbin is available from early finalization, create a string
391 // literal containing the fat binary loaded from the given file.
392 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
393 FatbinConstantName, 8);
394 } else {
395 // If fatbin is not available, create an external symbol
396 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
397 // to contain the fat binary but will be populated somewhere else,
398 // e.g. by lld through link script.
399 FatBinStr = new llvm::GlobalVariable(
Yaxun Liu29155b02018-05-18 15:07:56 +0000400 CGM.getModule(), CGM.Int8Ty,
401 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
402 "__hip_fatbin", nullptr,
403 llvm::GlobalVariable::NotThreadLocal);
Yaxun Liu97670892018-10-02 17:48:54 +0000404 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
405 }
Yaxun Liu29155b02018-05-18 15:07:56 +0000406
407 FatMagic = HIPFatMagic;
408 } else {
409 if (RelocatableDeviceCode)
Artem Belevich5ce0a082018-06-28 17:15:52 +0000410 FatbinConstantName = CGM.getTriple().isMacOSX()
411 ? "__NV_CUDA,__nv_relfatbin"
412 : "__nv_relfatbin";
Yaxun Liu29155b02018-05-18 15:07:56 +0000413 else
414 FatbinConstantName =
415 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
416 // NVIDIA's cuobjdump looks for fatbins in this section.
417 FatbinSectionName =
418 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
419
Artem Belevich5ce0a082018-06-28 17:15:52 +0000420 ModuleIDSectionName = CGM.getTriple().isMacOSX()
421 ? "__NV_CUDA,__nv_module_id"
422 : "__nv_module_id";
Yaxun Liu29155b02018-05-18 15:07:56 +0000423 ModuleIDPrefix = "__nv_";
424
425 // For CUDA, create a string literal containing the fat binary loaded from
426 // the given file.
427 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
428 FatbinConstantName, 8);
429 FatMagic = CudaFatMagic;
430 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000431
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000432 // Create initialized wrapper structure that points to the loaded GPU binary
433 ConstantInitBuilder Builder(CGM);
434 auto Values = Builder.beginStruct(FatbinWrapperTy);
435 // Fatbin wrapper magic.
Yaxun Liu29155b02018-05-18 15:07:56 +0000436 Values.addInt(IntTy, FatMagic);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000437 // Fatbin version.
438 Values.addInt(IntTy, 1);
439 // Data.
Yaxun Liu29155b02018-05-18 15:07:56 +0000440 Values.add(FatBinStr);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000441 // Unused in fatbin v1.
442 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
443 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
Yaxun Liu887c5692018-04-25 01:10:37 +0000444 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000445 /*constant*/ true);
446 FatbinWrapper->setSection(FatbinSectionName);
Justin Lebard14fe882016-11-18 00:41:31 +0000447
Yaxun Liuf99752b2018-07-20 22:45:24 +0000448 // There is only one HIP fat binary per linked module, however there are
449 // multiple constructor functions. Make sure the fat binary is registered
450 // only once. The constructor functions are executed by the dynamic loader
451 // before the program gains control. The dynamic loader cannot execute the
452 // constructor functions concurrently since doing that would not guarantee
453 // thread safety of the loaded program. Therefore we can assume sequential
454 // execution of constructor functions here.
455 if (IsHIP) {
Yaxun Liu97670892018-10-02 17:48:54 +0000456 auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage :
457 llvm::GlobalValue::LinkOnceAnyLinkage;
Yaxun Liuf99752b2018-07-20 22:45:24 +0000458 llvm::BasicBlock *IfBlock =
459 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
460 llvm::BasicBlock *ExitBlock =
461 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
462 // The name, size, and initialization pattern of this variable is part
463 // of HIP ABI.
464 GpuBinaryHandle = new llvm::GlobalVariable(
465 TheModule, VoidPtrPtrTy, /*isConstant=*/false,
Yaxun Liu97670892018-10-02 17:48:54 +0000466 Linkage,
Yaxun Liuf99752b2018-07-20 22:45:24 +0000467 /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
468 "__hip_gpubin_handle");
469 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
Yaxun Liu94ff57f2018-08-17 17:47:31 +0000470 // Prevent the weak symbol in different shared libraries being merged.
Yaxun Liu97670892018-10-02 17:48:54 +0000471 if (Linkage != llvm::GlobalValue::InternalLinkage)
472 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
Yaxun Liuf99752b2018-07-20 22:45:24 +0000473 Address GpuBinaryAddr(
474 GpuBinaryHandle,
475 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
476 {
477 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
478 llvm::Constant *Zero =
479 llvm::Constant::getNullValue(HandleValue->getType());
480 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
481 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
482 }
483 {
484 CtorBuilder.SetInsertPoint(IfBlock);
485 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
486 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
487 RegisterFatbinFunc,
488 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
489 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
490 CtorBuilder.CreateBr(ExitBlock);
491 }
492 {
493 CtorBuilder.SetInsertPoint(ExitBlock);
494 // Call __hip_register_globals(GpuBinaryHandle);
495 if (RegisterGlobalsFunc) {
496 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
497 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
498 }
499 }
500 } else if (!RelocatableDeviceCode) {
501 // Register binary with CUDA runtime. This is substantially different in
502 // default mode vs. separate compilation!
503 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000504 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
505 RegisterFatbinFunc,
506 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
507 GpuBinaryHandle = new llvm::GlobalVariable(
508 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
Yaxun Liuf99752b2018-07-20 22:45:24 +0000509 llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
510 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000511 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
512 CGM.getPointerAlign());
Artem Belevich52cc4872015-05-07 19:34:16 +0000513
Yaxun Liuf99752b2018-07-20 22:45:24 +0000514 // Call __cuda_register_globals(GpuBinaryHandle);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000515 if (RegisterGlobalsFunc)
516 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
517 } else {
518 // Generate a unique module ID.
Yaxun Liu29155b02018-05-18 15:07:56 +0000519 SmallString<64> ModuleID;
520 llvm::raw_svector_ostream OS(ModuleID);
Artem Belevich93552b32018-10-05 18:39:58 +0000521 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
Yaxun Liu29155b02018-05-18 15:07:56 +0000522 llvm::Constant *ModuleIDConstant =
523 makeConstantString(ModuleID.str(), "", ModuleIDSectionName, 32);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000524
Yaxun Liuf99752b2018-07-20 22:45:24 +0000525 // Create an alias for the FatbinWrapper that nvcc will look for.
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000526 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
Yaxun Liu29155b02018-05-18 15:07:56 +0000527 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000528
Yaxun Liuf99752b2018-07-20 22:45:24 +0000529 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000530 // void *, void (*)(void **))
Yaxun Liuf99752b2018-07-20 22:45:24 +0000531 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
Yaxun Liu29155b02018-05-18 15:07:56 +0000532 RegisterLinkedBinaryName += ModuleID;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000533 llvm::Constant *RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
534 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
535
536 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
537 llvm::Value *Args[] = {RegisterGlobalsFunc,
538 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
Yaxun Liu29155b02018-05-18 15:07:56 +0000539 ModuleIDConstant,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000540 makeDummyFunction(getCallbackFnTy())};
541 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
542 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000543
Artem Belevichc66d2542018-06-27 18:32:51 +0000544 // Create destructor and register it with atexit() the way NVCC does it. Doing
545 // it during regular destructor phase worked in CUDA before 9.2 but results in
546 // double-free in 9.2.
547 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
548 // extern "C" int atexit(void (*f)(void));
549 llvm::FunctionType *AtExitTy =
550 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
551 llvm::Constant *AtExitFunc =
552 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
553 /*Local=*/true);
554 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
555 }
556
Artem Belevich52cc4872015-05-07 19:34:16 +0000557 CtorBuilder.CreateRetVoid();
558 return ModuleCtorFunc;
559}
560
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000561/// Creates a global destructor function that unregisters the GPU code blob
Artem Belevich52cc4872015-05-07 19:34:16 +0000562/// registered by constructor.
Yaxun Liuf99752b2018-07-20 22:45:24 +0000563///
564/// For CUDA:
Artem Belevich52cc4872015-05-07 19:34:16 +0000565/// \code
566/// void __cuda_module_dtor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000567/// __cudaUnregisterFatBinary(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000568/// }
569/// \endcode
Yaxun Liuf99752b2018-07-20 22:45:24 +0000570///
571/// For HIP:
572/// \code
573/// void __hip_module_dtor(void*) {
574/// if (__hip_gpubin_handle) {
575/// __hipUnregisterFatBinary(__hip_gpubin_handle);
576/// __hip_gpubin_handle = 0;
577/// }
578/// }
579/// \endcode
Artem Belevich52cc4872015-05-07 19:34:16 +0000580llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000581 // No need for destructor if we don't have a handle to unregister.
582 if (!GpuBinaryHandle)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000583 return nullptr;
584
Artem Belevich52cc4872015-05-07 19:34:16 +0000585 // void __cudaUnregisterFatBinary(void ** handle);
586 llvm::Constant *UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
587 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000588 addUnderscoredPrefixToName("UnregisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000589
590 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
591 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000592 llvm::GlobalValue::InternalLinkage,
593 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
594
Artem Belevich52cc4872015-05-07 19:34:16 +0000595 llvm::BasicBlock *DtorEntryBB =
596 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000597 CGBuilderTy DtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000598 DtorBuilder.SetInsertPoint(DtorEntryBB);
599
Yaxun Liuf99752b2018-07-20 22:45:24 +0000600 Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
601 GpuBinaryHandle->getAlignment()));
602 auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
603 // There is only one HIP fat binary per linked module, however there are
604 // multiple destructor functions. Make sure the fat binary is unregistered
605 // only once.
606 if (CGM.getLangOpts().HIP) {
607 llvm::BasicBlock *IfBlock =
608 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
609 llvm::BasicBlock *ExitBlock =
610 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
611 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
612 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
613 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
Artem Belevich52cc4872015-05-07 19:34:16 +0000614
Yaxun Liuf99752b2018-07-20 22:45:24 +0000615 DtorBuilder.SetInsertPoint(IfBlock);
616 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
617 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
618 DtorBuilder.CreateBr(ExitBlock);
619
620 DtorBuilder.SetInsertPoint(ExitBlock);
621 } else {
622 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
623 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000624 DtorBuilder.CreateRetVoid();
625 return ModuleDtorFunc;
626}
627
Peter Collingbournefe883422011-10-06 18:29:37 +0000628CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
629 return new CGNVCUDARuntime(CGM);
630}