blob: e9e5483e5ac1e64cb526f09cdd24646ef9e70c4a [file] [log] [blame]
Peter Collingbournefe883422011-10-06 18:29:37 +00001//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for CUDA code generation targeting the NVIDIA CUDA
11// runtime library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCUDARuntime.h"
Peter Collingbournefa4d6032011-10-06 18:51:56 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "clang/AST/Decl.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000020#include "llvm/IR/BasicBlock.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000024#include "llvm/Support/Format.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
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());
76 if (!SectionName.empty())
77 GV->setSection(SectionName);
78 if (Alignment)
79 GV->setAlignment(Alignment);
80
John McCall7f416cc2015-09-08 08:05:57 +000081 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
82 ConstStr.getPointer(), Zeros);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000083 }
84
85 /// Helper function that generates an empty dummy function returning void.
86 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
87 assert(FnTy->getReturnType()->isVoidTy() &&
88 "Can only generate dummy functions returning void!");
89 llvm::Function *DummyFunc = llvm::Function::Create(
90 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
91
92 llvm::BasicBlock *DummyBlock =
93 llvm::BasicBlock::Create(Context, "", DummyFunc);
94 CGBuilderTy FuncBuilder(CGM, Context);
95 FuncBuilder.SetInsertPoint(DummyBlock);
96 FuncBuilder.CreateRetVoid();
97
98 return DummyFunc;
99 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000100
101 void emitDeviceStubBody(CodeGenFunction &CGF, FunctionArgList &Args);
102
Peter Collingbournefe883422011-10-06 18:29:37 +0000103public:
104 CGNVCUDARuntime(CodeGenModule &CGM);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000105
Artem Belevich52cc4872015-05-07 19:34:16 +0000106 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
Artem Belevich42e19492016-03-02 18:28:50 +0000107 void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags) override {
108 DeviceVars.push_back(std::make_pair(&Var, Flags));
109 }
110
Artem Belevich52cc4872015-05-07 19:34:16 +0000111 /// Creates module constructor function
112 llvm::Function *makeModuleCtorFunction() override;
113 /// Creates module destructor function
114 llvm::Function *makeModuleDtorFunction() override;
Peter Collingbournefe883422011-10-06 18:29:37 +0000115};
116
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000117}
Peter Collingbournefe883422011-10-06 18:29:37 +0000118
Yaxun Liu887c5692018-04-25 01:10:37 +0000119std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
120 if (CGM.getLangOpts().HIP)
121 return ((Twine("hip") + Twine(FuncName)).str());
122 return ((Twine("cuda") + Twine(FuncName)).str());
123}
124std::string
125CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
126 if (CGM.getLangOpts().HIP)
127 return ((Twine("__hip") + Twine(FuncName)).str());
128 return ((Twine("__cuda") + Twine(FuncName)).str());
129}
130
Artem Belevich52cc4872015-05-07 19:34:16 +0000131CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
132 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000133 TheModule(CGM.getModule()),
134 RelocatableDeviceCode(CGM.getLangOpts().CUDARelocatableDeviceCode) {
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000135 CodeGen::CodeGenTypes &Types = CGM.getTypes();
136 ASTContext &Ctx = CGM.getContext();
137
John McCall6c9f1fdb2016-11-19 08:17:24 +0000138 IntTy = CGM.IntTy;
139 SizeTy = CGM.SizeTy;
140 VoidTy = CGM.VoidTy;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000141
142 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
143 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
Artem Belevich52cc4872015-05-07 19:34:16 +0000144 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000145}
146
147llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn() const {
148 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
Benjamin Kramer30934732016-07-02 11:41:41 +0000149 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
Yaxun Liu887c5692018-04-25 01:10:37 +0000150 return CGM.CreateRuntimeFunction(
151 llvm::FunctionType::get(IntTy, Params, false),
152 addPrefixToName("SetupArgument"));
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000153}
154
155llvm::Constant *CGNVCUDARuntime::getLaunchFn() const {
Yaxun Liu887c5692018-04-25 01:10:37 +0000156 if (CGM.getLangOpts().HIP) {
157 // hipError_t hipLaunchByPtr(char *);
158 return CGM.CreateRuntimeFunction(
159 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
160 } else {
161 // cudaError_t cudaLaunch(char *);
162 return CGM.CreateRuntimeFunction(
163 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
164 }
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000165}
166
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000167llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
168 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
169}
170
171llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
172 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
173}
174
175llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
176 auto CallbackFnTy = getCallbackFnTy();
177 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
178 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
179 VoidPtrTy, CallbackFnTy->getPointerTo()};
180 return llvm::FunctionType::get(VoidTy, Params, false);
181}
182
Artem Belevich52cc4872015-05-07 19:34:16 +0000183void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
184 FunctionArgList &Args) {
185 EmittedKernels.push_back(CGF.CurFn);
186 emitDeviceStubBody(CGF, Args);
187}
188
189void CGNVCUDARuntime::emitDeviceStubBody(CodeGenFunction &CGF,
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000190 FunctionArgList &Args) {
Justin Lebare56360a2016-07-27 22:36:21 +0000191 // Emit a call to cudaSetupArgument for each arg in Args.
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000192 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
Justin Lebare56360a2016-07-27 22:36:21 +0000193 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
194 CharUnits Offset = CharUnits::Zero();
195 for (const VarDecl *A : Args) {
196 CharUnits TyWidth, TyAlign;
197 std::tie(TyWidth, TyAlign) =
198 CGM.getContext().getTypeInfoInChars(A->getType());
199 Offset = Offset.alignTo(TyAlign);
200 llvm::Value *Args[] = {
201 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
202 VoidPtrTy),
203 llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
204 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
205 };
John McCall882987f2013-02-28 19:01:20 +0000206 llvm::CallSite CS = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000207 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
208 llvm::Value *CSZero = CGF.Builder.CreateICmpEQ(CS.getInstruction(), Zero);
Justin Lebare56360a2016-07-27 22:36:21 +0000209 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000210 CGF.Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
211 CGF.EmitBlock(NextBlock);
Justin Lebare56360a2016-07-27 22:36:21 +0000212 Offset += TyWidth;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000213 }
214
215 // Emit the call to cudaLaunch
216 llvm::Constant *cudaLaunchFn = getLaunchFn();
217 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
John McCall882987f2013-02-28 19:01:20 +0000218 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000219 CGF.EmitBranch(EndBlock);
220
221 CGF.EmitBlock(EndBlock);
Peter Collingbournefe883422011-10-06 18:29:37 +0000222}
223
Artem Belevich42e19492016-03-02 18:28:50 +0000224/// Creates a function that sets up state on the host side for CUDA objects that
225/// have a presence on both the host and device sides. Specifically, registers
226/// the host side of kernel functions and device global variables with the CUDA
227/// runtime.
Artem Belevich52cc4872015-05-07 19:34:16 +0000228/// \code
Artem Belevich42e19492016-03-02 18:28:50 +0000229/// void __cuda_register_globals(void** GpuBinaryHandle) {
Artem Belevich52cc4872015-05-07 19:34:16 +0000230/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
231/// ...
232/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
Artem Belevich42e19492016-03-02 18:28:50 +0000233/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
234/// ...
235/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
Artem Belevich52cc4872015-05-07 19:34:16 +0000236/// }
237/// \endcode
Artem Belevich42e19492016-03-02 18:28:50 +0000238llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000239 // No need to register anything
240 if (EmittedKernels.empty() && DeviceVars.empty())
241 return nullptr;
242
Artem Belevich52cc4872015-05-07 19:34:16 +0000243 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000244 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000245 addUnderscoredPrefixToName("_register_globals"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000246 llvm::BasicBlock *EntryBB =
247 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000248 CGBuilderTy Builder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000249 Builder.SetInsertPoint(EntryBB);
250
251 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
252 // int, uint3*, uint3*, dim3*, dim3*, int*)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000253 llvm::Type *RegisterFuncParams[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000254 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
255 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
256 llvm::Constant *RegisterFunc = CGM.CreateRuntimeFunction(
257 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000258 addUnderscoredPrefixToName("RegisterFunction"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000259
260 // Extract GpuBinaryHandle passed as the first argument passed to
Artem Belevich42e19492016-03-02 18:28:50 +0000261 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
Artem Belevich52cc4872015-05-07 19:34:16 +0000262 // each emitted kernel.
263 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
264 for (llvm::Function *Kernel : EmittedKernels) {
265 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
266 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
Artem Belevich42e19492016-03-02 18:28:50 +0000267 llvm::Value *Args[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000268 &GpuBinaryHandlePtr, Builder.CreateBitCast(Kernel, VoidPtrTy),
269 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
270 NullPtr, NullPtr, NullPtr,
271 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
Artem Belevich42e19492016-03-02 18:28:50 +0000272 Builder.CreateCall(RegisterFunc, Args);
273 }
274
275 // void __cudaRegisterVar(void **, char *, char *, const char *,
276 // int, int, int, int)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000277 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
278 CharPtrTy, IntTy, IntTy,
279 IntTy, IntTy};
Artem Belevich42e19492016-03-02 18:28:50 +0000280 llvm::Constant *RegisterVar = CGM.CreateRuntimeFunction(
281 llvm::FunctionType::get(IntTy, RegisterVarParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000282 addUnderscoredPrefixToName("RegisterVar"));
Artem Belevich42e19492016-03-02 18:28:50 +0000283 for (auto &Pair : DeviceVars) {
284 llvm::GlobalVariable *Var = Pair.first;
285 unsigned Flags = Pair.second;
286 llvm::Constant *VarName = makeConstantString(Var->getName());
287 uint64_t VarSize =
288 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
289 llvm::Value *Args[] = {
290 &GpuBinaryHandlePtr,
291 Builder.CreateBitCast(Var, VoidPtrTy),
292 VarName,
293 VarName,
294 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
295 llvm::ConstantInt::get(IntTy, VarSize),
296 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
297 llvm::ConstantInt::get(IntTy, 0)};
298 Builder.CreateCall(RegisterVar, Args);
Artem Belevich52cc4872015-05-07 19:34:16 +0000299 }
300
301 Builder.CreateRetVoid();
302 return RegisterKernelsFunc;
303}
304
305/// Creates a global constructor function for the module:
306/// \code
307/// void __cuda_module_ctor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000308/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
309/// __cuda_register_globals(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000310/// }
311/// \endcode
312llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000313 // No need to generate ctors/dtors if there is no GPU binary.
314 std::string GpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
315 if (GpuBinaryFileName.empty())
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000316 return nullptr;
317
Artem Belevich42e19492016-03-02 18:28:50 +0000318 // void __cuda_register_globals(void* handle);
319 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000320 // We always need a function to pass in as callback. Create a dummy
321 // implementation if we don't need to register anything.
322 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
323 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
324
Artem Belevich52cc4872015-05-07 19:34:16 +0000325 // void ** __cudaRegisterFatBinary(void *);
326 llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
327 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000328 addUnderscoredPrefixToName("RegisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000329 // struct { int magic, int version, void * gpu_binary, void * dont_care };
330 llvm::StructType *FatbinWrapperTy =
Serge Guelton1d993272017-05-09 19:31:30 +0000331 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
Artem Belevich52cc4872015-05-07 19:34:16 +0000332
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000333 // Register GPU binary with the CUDA runtime, store returned handle in a
334 // global variable and save a reference in GpuBinaryHandle to be cleaned up
335 // in destructor on exit. Then associate all known kernels with the GPU binary
336 // handle so CUDA runtime can figure out what to call on the GPU side.
337 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GpuBinaryOrErr =
338 llvm::MemoryBuffer::getFileOrSTDIN(GpuBinaryFileName);
339 if (std::error_code EC = GpuBinaryOrErr.getError()) {
340 CGM.getDiags().Report(diag::err_cannot_open_file)
341 << GpuBinaryFileName << EC.message();
342 return nullptr;
343 }
344
Artem Belevich52cc4872015-05-07 19:34:16 +0000345 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
346 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000347 llvm::GlobalValue::InternalLinkage,
348 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000349 llvm::BasicBlock *CtorEntryBB =
350 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000351 CGBuilderTy CtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000352
353 CtorBuilder.SetInsertPoint(CtorEntryBB);
354
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000355 const char *FatbinConstantName;
356 if (RelocatableDeviceCode)
357 // TODO: Figure out how this is called on mac OS!
358 FatbinConstantName = "__nv_relfatbin";
359 else
360 FatbinConstantName =
361 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000362 // NVIDIA's cuobjdump looks for fatbins in this section.
363 const char *FatbinSectionName =
364 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000365 // TODO: Figure out how this is called on mac OS!
366 const char *NVModuleIDSectionName = "__nv_module_id";
Artem Belevich52cc4872015-05-07 19:34:16 +0000367
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000368 // Create initialized wrapper structure that points to the loaded GPU binary
369 ConstantInitBuilder Builder(CGM);
370 auto Values = Builder.beginStruct(FatbinWrapperTy);
371 // Fatbin wrapper magic.
372 Values.addInt(IntTy, 0x466243b1);
373 // Fatbin version.
374 Values.addInt(IntTy, 1);
375 // Data.
376 Values.add(makeConstantString(GpuBinaryOrErr.get()->getBuffer(), "",
377 FatbinConstantName, 8));
378 // Unused in fatbin v1.
379 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
380 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
Yaxun Liu887c5692018-04-25 01:10:37 +0000381 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000382 /*constant*/ true);
383 FatbinWrapper->setSection(FatbinSectionName);
Justin Lebard14fe882016-11-18 00:41:31 +0000384
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000385 // Register binary with CUDA runtime. This is substantially different in
386 // default mode vs. separate compilation!
387 if (!RelocatableDeviceCode) {
388 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
389 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
390 RegisterFatbinFunc,
391 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
392 GpuBinaryHandle = new llvm::GlobalVariable(
393 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000394 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
395 addUnderscoredPrefixToName("_gpubin_handle"));
396
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000397 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
398 CGM.getPointerAlign());
Artem Belevich52cc4872015-05-07 19:34:16 +0000399
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000400 // Call __cuda_register_globals(GpuBinaryHandle);
401 if (RegisterGlobalsFunc)
402 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
403 } else {
404 // Generate a unique module ID.
405 SmallString<64> NVModuleID;
406 llvm::raw_svector_ostream OS(NVModuleID);
407 OS << "__nv_" << llvm::format("%x", FatbinWrapper->getGUID());
408 llvm::Constant *NVModuleIDConstant =
409 makeConstantString(NVModuleID.str(), "", NVModuleIDSectionName, 32);
410
411 // Create an alias for the FatbinWrapper that nvcc will look for.
412 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
413 Twine("__fatbinwrap") + NVModuleID,
414 FatbinWrapper);
415
416 // void __cudaRegisterLinkedBinary%NVModuleID%(void (*)(void *), void *,
417 // void *, void (*)(void **))
Yaxun Liu887c5692018-04-25 01:10:37 +0000418 SmallString<128> RegisterLinkedBinaryName(
419 addUnderscoredPrefixToName("RegisterLinkedBinary"));
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000420 RegisterLinkedBinaryName += NVModuleID;
421 llvm::Constant *RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
422 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
423
424 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
425 llvm::Value *Args[] = {RegisterGlobalsFunc,
426 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
427 NVModuleIDConstant,
428 makeDummyFunction(getCallbackFnTy())};
429 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
430 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000431
432 CtorBuilder.CreateRetVoid();
433 return ModuleCtorFunc;
434}
435
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000436/// Creates a global destructor function that unregisters the GPU code blob
Artem Belevich52cc4872015-05-07 19:34:16 +0000437/// registered by constructor.
438/// \code
439/// void __cuda_module_dtor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000440/// __cudaUnregisterFatBinary(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000441/// }
442/// \endcode
443llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000444 // No need for destructor if we don't have a handle to unregister.
445 if (!GpuBinaryHandle)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000446 return nullptr;
447
Artem Belevich52cc4872015-05-07 19:34:16 +0000448 // void __cudaUnregisterFatBinary(void ** handle);
449 llvm::Constant *UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
450 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000451 addUnderscoredPrefixToName("UnregisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000452
453 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
454 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000455 llvm::GlobalValue::InternalLinkage,
456 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
457
Artem Belevich52cc4872015-05-07 19:34:16 +0000458 llvm::BasicBlock *DtorEntryBB =
459 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000460 CGBuilderTy DtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000461 DtorBuilder.SetInsertPoint(DtorEntryBB);
462
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000463 auto HandleValue =
John McCall7f416cc2015-09-08 08:05:57 +0000464 DtorBuilder.CreateAlignedLoad(GpuBinaryHandle, CGM.getPointerAlign());
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000465 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
Artem Belevich52cc4872015-05-07 19:34:16 +0000466
467 DtorBuilder.CreateRetVoid();
468 return ModuleDtorFunc;
469}
470
Peter Collingbournefe883422011-10-06 18:29:37 +0000471CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
472 return new CGNVCUDARuntime(CGM);
473}