blob: 4c2e10b65cc810b62c10e95014d8032364c4121e [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 {
Yaxun Liu29155b02018-05-18 15:07:56 +000030constexpr unsigned CudaFatMagic = 0x466243b1;
31constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
Peter Collingbournefe883422011-10-06 18:29:37 +000032
33class CGNVCUDARuntime : public CGCUDARuntime {
Peter Collingbournefa4d6032011-10-06 18:51:56 +000034
35private:
John McCall6c9f1fdb2016-11-19 08:17:24 +000036 llvm::IntegerType *IntTy, *SizeTy;
37 llvm::Type *VoidTy;
Artem Belevich52cc4872015-05-07 19:34:16 +000038 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
39
40 /// Convenience reference to LLVM Context
41 llvm::LLVMContext &Context;
42 /// Convenience reference to the current module
43 llvm::Module &TheModule;
44 /// Keeps track of kernel launch stubs emitted in this module
45 llvm::SmallVector<llvm::Function *, 16> EmittedKernels;
Artem Belevich42e19492016-03-02 18:28:50 +000046 llvm::SmallVector<std::pair<llvm::GlobalVariable *, unsigned>, 16> DeviceVars;
Jonas Hahnfelde7681322018-02-28 17:53:46 +000047 /// Keeps track of variable containing handle of GPU binary. Populated by
Artem Belevich52cc4872015-05-07 19:34:16 +000048 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
49 /// ModuleDtorFunction()
Jonas Hahnfelde7681322018-02-28 17:53:46 +000050 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000051 /// Whether we generate relocatable device code.
52 bool RelocatableDeviceCode;
Peter Collingbournefa4d6032011-10-06 18:51:56 +000053
54 llvm::Constant *getSetupArgumentFn() const;
55 llvm::Constant *getLaunchFn() const;
56
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000057 llvm::FunctionType *getRegisterGlobalsFnTy() const;
58 llvm::FunctionType *getCallbackFnTy() const;
59 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
Yaxun Liu887c5692018-04-25 01:10:37 +000060 std::string addPrefixToName(StringRef FuncName) const;
61 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000062
Artem Belevich52cc4872015-05-07 19:34:16 +000063 /// Creates a function to register all kernel stubs generated in this module.
Artem Belevich42e19492016-03-02 18:28:50 +000064 llvm::Function *makeRegisterGlobalsFn();
Artem Belevich52cc4872015-05-07 19:34:16 +000065
66 /// Helper function that generates a constant string and returns a pointer to
67 /// the start of the string. The result of this function can be used anywhere
68 /// where the C code specifies const char*.
69 llvm::Constant *makeConstantString(const std::string &Str,
70 const std::string &Name = "",
Artem Belevich4c093182016-08-12 18:44:01 +000071 const std::string &SectionName = "",
Artem Belevich52cc4872015-05-07 19:34:16 +000072 unsigned Alignment = 0) {
73 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
74 llvm::ConstantInt::get(SizeTy, 0)};
John McCall7f416cc2015-09-08 08:05:57 +000075 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
Artem Belevich4c093182016-08-12 18:44:01 +000076 llvm::GlobalVariable *GV =
77 cast<llvm::GlobalVariable>(ConstStr.getPointer());
78 if (!SectionName.empty())
79 GV->setSection(SectionName);
80 if (Alignment)
81 GV->setAlignment(Alignment);
82
John McCall7f416cc2015-09-08 08:05:57 +000083 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
84 ConstStr.getPointer(), Zeros);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +000085 }
86
87 /// Helper function that generates an empty dummy function returning void.
88 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
89 assert(FnTy->getReturnType()->isVoidTy() &&
90 "Can only generate dummy functions returning void!");
91 llvm::Function *DummyFunc = llvm::Function::Create(
92 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
93
94 llvm::BasicBlock *DummyBlock =
95 llvm::BasicBlock::Create(Context, "", DummyFunc);
96 CGBuilderTy FuncBuilder(CGM, Context);
97 FuncBuilder.SetInsertPoint(DummyBlock);
98 FuncBuilder.CreateRetVoid();
99
100 return DummyFunc;
101 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000102
103 void emitDeviceStubBody(CodeGenFunction &CGF, FunctionArgList &Args);
104
Peter Collingbournefe883422011-10-06 18:29:37 +0000105public:
106 CGNVCUDARuntime(CodeGenModule &CGM);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000107
Artem Belevich52cc4872015-05-07 19:34:16 +0000108 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
Artem Belevich42e19492016-03-02 18:28:50 +0000109 void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags) override {
110 DeviceVars.push_back(std::make_pair(&Var, Flags));
111 }
112
Artem Belevich52cc4872015-05-07 19:34:16 +0000113 /// Creates module constructor function
114 llvm::Function *makeModuleCtorFunction() override;
115 /// Creates module destructor function
116 llvm::Function *makeModuleDtorFunction() override;
Peter Collingbournefe883422011-10-06 18:29:37 +0000117};
118
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000119}
Peter Collingbournefe883422011-10-06 18:29:37 +0000120
Yaxun Liu887c5692018-04-25 01:10:37 +0000121std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
122 if (CGM.getLangOpts().HIP)
123 return ((Twine("hip") + Twine(FuncName)).str());
124 return ((Twine("cuda") + Twine(FuncName)).str());
125}
126std::string
127CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
128 if (CGM.getLangOpts().HIP)
129 return ((Twine("__hip") + Twine(FuncName)).str());
130 return ((Twine("__cuda") + Twine(FuncName)).str());
131}
132
Artem Belevich52cc4872015-05-07 19:34:16 +0000133CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
134 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000135 TheModule(CGM.getModule()),
136 RelocatableDeviceCode(CGM.getLangOpts().CUDARelocatableDeviceCode) {
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000137 CodeGen::CodeGenTypes &Types = CGM.getTypes();
138 ASTContext &Ctx = CGM.getContext();
139
John McCall6c9f1fdb2016-11-19 08:17:24 +0000140 IntTy = CGM.IntTy;
141 SizeTy = CGM.SizeTy;
142 VoidTy = CGM.VoidTy;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000143
144 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
145 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
Artem Belevich52cc4872015-05-07 19:34:16 +0000146 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000147}
148
149llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn() const {
150 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
Benjamin Kramer30934732016-07-02 11:41:41 +0000151 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
Yaxun Liu887c5692018-04-25 01:10:37 +0000152 return CGM.CreateRuntimeFunction(
153 llvm::FunctionType::get(IntTy, Params, false),
154 addPrefixToName("SetupArgument"));
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000155}
156
157llvm::Constant *CGNVCUDARuntime::getLaunchFn() const {
Yaxun Liu887c5692018-04-25 01:10:37 +0000158 if (CGM.getLangOpts().HIP) {
159 // hipError_t hipLaunchByPtr(char *);
160 return CGM.CreateRuntimeFunction(
161 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
162 } else {
163 // cudaError_t cudaLaunch(char *);
164 return CGM.CreateRuntimeFunction(
165 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
166 }
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000167}
168
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000169llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
170 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
171}
172
173llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
174 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
175}
176
177llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
178 auto CallbackFnTy = getCallbackFnTy();
179 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
180 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
181 VoidPtrTy, CallbackFnTy->getPointerTo()};
182 return llvm::FunctionType::get(VoidTy, Params, false);
183}
184
Artem Belevich52cc4872015-05-07 19:34:16 +0000185void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
186 FunctionArgList &Args) {
187 EmittedKernels.push_back(CGF.CurFn);
188 emitDeviceStubBody(CGF, Args);
189}
190
191void CGNVCUDARuntime::emitDeviceStubBody(CodeGenFunction &CGF,
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000192 FunctionArgList &Args) {
Justin Lebare56360a2016-07-27 22:36:21 +0000193 // Emit a call to cudaSetupArgument for each arg in Args.
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000194 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
Justin Lebare56360a2016-07-27 22:36:21 +0000195 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
196 CharUnits Offset = CharUnits::Zero();
197 for (const VarDecl *A : Args) {
198 CharUnits TyWidth, TyAlign;
199 std::tie(TyWidth, TyAlign) =
200 CGM.getContext().getTypeInfoInChars(A->getType());
201 Offset = Offset.alignTo(TyAlign);
202 llvm::Value *Args[] = {
203 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
204 VoidPtrTy),
205 llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
206 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
207 };
John McCall882987f2013-02-28 19:01:20 +0000208 llvm::CallSite CS = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000209 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
210 llvm::Value *CSZero = CGF.Builder.CreateICmpEQ(CS.getInstruction(), Zero);
Justin Lebare56360a2016-07-27 22:36:21 +0000211 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000212 CGF.Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
213 CGF.EmitBlock(NextBlock);
Justin Lebare56360a2016-07-27 22:36:21 +0000214 Offset += TyWidth;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000215 }
216
217 // Emit the call to cudaLaunch
218 llvm::Constant *cudaLaunchFn = getLaunchFn();
219 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
John McCall882987f2013-02-28 19:01:20 +0000220 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000221 CGF.EmitBranch(EndBlock);
222
223 CGF.EmitBlock(EndBlock);
Peter Collingbournefe883422011-10-06 18:29:37 +0000224}
225
Artem Belevich42e19492016-03-02 18:28:50 +0000226/// Creates a function that sets up state on the host side for CUDA objects that
227/// have a presence on both the host and device sides. Specifically, registers
228/// the host side of kernel functions and device global variables with the CUDA
229/// runtime.
Artem Belevich52cc4872015-05-07 19:34:16 +0000230/// \code
Artem Belevich42e19492016-03-02 18:28:50 +0000231/// void __cuda_register_globals(void** GpuBinaryHandle) {
Artem Belevich52cc4872015-05-07 19:34:16 +0000232/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
233/// ...
234/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
Artem Belevich42e19492016-03-02 18:28:50 +0000235/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
236/// ...
237/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
Artem Belevich52cc4872015-05-07 19:34:16 +0000238/// }
239/// \endcode
Artem Belevich42e19492016-03-02 18:28:50 +0000240llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000241 // No need to register anything
242 if (EmittedKernels.empty() && DeviceVars.empty())
243 return nullptr;
244
Artem Belevich52cc4872015-05-07 19:34:16 +0000245 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000246 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000247 addUnderscoredPrefixToName("_register_globals"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000248 llvm::BasicBlock *EntryBB =
249 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000250 CGBuilderTy Builder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000251 Builder.SetInsertPoint(EntryBB);
252
253 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
254 // int, uint3*, uint3*, dim3*, dim3*, int*)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000255 llvm::Type *RegisterFuncParams[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000256 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
257 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
258 llvm::Constant *RegisterFunc = CGM.CreateRuntimeFunction(
259 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000260 addUnderscoredPrefixToName("RegisterFunction"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000261
262 // Extract GpuBinaryHandle passed as the first argument passed to
Artem Belevich42e19492016-03-02 18:28:50 +0000263 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
Artem Belevich52cc4872015-05-07 19:34:16 +0000264 // each emitted kernel.
265 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
266 for (llvm::Function *Kernel : EmittedKernels) {
267 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
268 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
Artem Belevich42e19492016-03-02 18:28:50 +0000269 llvm::Value *Args[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000270 &GpuBinaryHandlePtr, Builder.CreateBitCast(Kernel, VoidPtrTy),
271 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
272 NullPtr, NullPtr, NullPtr,
273 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
Artem Belevich42e19492016-03-02 18:28:50 +0000274 Builder.CreateCall(RegisterFunc, Args);
275 }
276
277 // void __cudaRegisterVar(void **, char *, char *, const char *,
278 // int, int, int, int)
Benjamin Kramer6d1c10b2016-07-02 12:03:57 +0000279 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
280 CharPtrTy, IntTy, IntTy,
281 IntTy, IntTy};
Artem Belevich42e19492016-03-02 18:28:50 +0000282 llvm::Constant *RegisterVar = CGM.CreateRuntimeFunction(
283 llvm::FunctionType::get(IntTy, RegisterVarParams, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000284 addUnderscoredPrefixToName("RegisterVar"));
Artem Belevich42e19492016-03-02 18:28:50 +0000285 for (auto &Pair : DeviceVars) {
286 llvm::GlobalVariable *Var = Pair.first;
287 unsigned Flags = Pair.second;
288 llvm::Constant *VarName = makeConstantString(Var->getName());
289 uint64_t VarSize =
290 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
291 llvm::Value *Args[] = {
292 &GpuBinaryHandlePtr,
293 Builder.CreateBitCast(Var, VoidPtrTy),
294 VarName,
295 VarName,
296 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
297 llvm::ConstantInt::get(IntTy, VarSize),
298 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
299 llvm::ConstantInt::get(IntTy, 0)};
300 Builder.CreateCall(RegisterVar, Args);
Artem Belevich52cc4872015-05-07 19:34:16 +0000301 }
302
303 Builder.CreateRetVoid();
304 return RegisterKernelsFunc;
305}
306
307/// Creates a global constructor function for the module:
308/// \code
309/// void __cuda_module_ctor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000310/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
311/// __cuda_register_globals(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000312/// }
313/// \endcode
314llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
Yaxun Liu29155b02018-05-18 15:07:56 +0000315 bool IsHIP = CGM.getLangOpts().HIP;
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000316 // No need to generate ctors/dtors if there is no GPU binary.
Yaxun Liu29155b02018-05-18 15:07:56 +0000317 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
318 if (CudaGpuBinaryFileName.empty() && !IsHIP)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000319 return nullptr;
320
Yaxun Liu29155b02018-05-18 15:07:56 +0000321 // void __{cuda|hip}_register_globals(void* handle);
Artem Belevich42e19492016-03-02 18:28:50 +0000322 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000323 // We always need a function to pass in as callback. Create a dummy
324 // implementation if we don't need to register anything.
325 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
326 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
327
Yaxun Liu29155b02018-05-18 15:07:56 +0000328 // void ** __{cuda|hip}RegisterFatBinary(void *);
Artem Belevich52cc4872015-05-07 19:34:16 +0000329 llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
330 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000331 addUnderscoredPrefixToName("RegisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000332 // struct { int magic, int version, void * gpu_binary, void * dont_care };
333 llvm::StructType *FatbinWrapperTy =
Serge Guelton1d993272017-05-09 19:31:30 +0000334 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
Artem Belevich52cc4872015-05-07 19:34:16 +0000335
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000336 // Register GPU binary with the CUDA runtime, store returned handle in a
337 // global variable and save a reference in GpuBinaryHandle to be cleaned up
338 // in destructor on exit. Then associate all known kernels with the GPU binary
339 // handle so CUDA runtime can figure out what to call on the GPU side.
Yaxun Liu29155b02018-05-18 15:07:56 +0000340 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary;
341 if (!IsHIP) {
342 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
343 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
344 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
345 CGM.getDiags().Report(diag::err_cannot_open_file)
346 << CudaGpuBinaryFileName << EC.message();
347 return nullptr;
348 }
349 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000350 }
351
Artem Belevich52cc4872015-05-07 19:34:16 +0000352 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
353 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000354 llvm::GlobalValue::InternalLinkage,
355 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000356 llvm::BasicBlock *CtorEntryBB =
357 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000358 CGBuilderTy CtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000359
360 CtorBuilder.SetInsertPoint(CtorEntryBB);
361
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000362 const char *FatbinConstantName;
Yaxun Liu29155b02018-05-18 15:07:56 +0000363 const char *FatbinSectionName;
364 const char *ModuleIDSectionName;
365 StringRef ModuleIDPrefix;
366 llvm::Constant *FatBinStr;
367 unsigned FatMagic;
368 if (IsHIP) {
369 FatbinConstantName = ".hip_fatbin";
370 FatbinSectionName = ".hipFatBinSegment";
371
372 ModuleIDSectionName = "__hip_module_id";
373 ModuleIDPrefix = "__hip_";
374
375 // For HIP, create an external symbol __hip_fatbin in section .hip_fatbin.
376 // The external symbol is supposed to contain the fat binary but will be
377 // populated somewhere else, e.g. by lld through link script.
378 FatBinStr = new llvm::GlobalVariable(
379 CGM.getModule(), CGM.Int8Ty,
380 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
381 "__hip_fatbin", nullptr,
382 llvm::GlobalVariable::NotThreadLocal);
383 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
384
385 FatMagic = HIPFatMagic;
386 } else {
387 if (RelocatableDeviceCode)
388 // TODO: Figure out how this is called on mac OS!
389 FatbinConstantName = "__nv_relfatbin";
390 else
391 FatbinConstantName =
392 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
393 // NVIDIA's cuobjdump looks for fatbins in this section.
394 FatbinSectionName =
395 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
396
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000397 // TODO: Figure out how this is called on mac OS!
Yaxun Liu29155b02018-05-18 15:07:56 +0000398 ModuleIDSectionName = "__nv_module_id";
399 ModuleIDPrefix = "__nv_";
400
401 // For CUDA, create a string literal containing the fat binary loaded from
402 // the given file.
403 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
404 FatbinConstantName, 8);
405 FatMagic = CudaFatMagic;
406 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000407
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000408 // Create initialized wrapper structure that points to the loaded GPU binary
409 ConstantInitBuilder Builder(CGM);
410 auto Values = Builder.beginStruct(FatbinWrapperTy);
411 // Fatbin wrapper magic.
Yaxun Liu29155b02018-05-18 15:07:56 +0000412 Values.addInt(IntTy, FatMagic);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000413 // Fatbin version.
414 Values.addInt(IntTy, 1);
415 // Data.
Yaxun Liu29155b02018-05-18 15:07:56 +0000416 Values.add(FatBinStr);
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000417 // Unused in fatbin v1.
418 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
419 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
Yaxun Liu887c5692018-04-25 01:10:37 +0000420 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000421 /*constant*/ true);
422 FatbinWrapper->setSection(FatbinSectionName);
Justin Lebard14fe882016-11-18 00:41:31 +0000423
Yaxun Liu29155b02018-05-18 15:07:56 +0000424 // Register binary with CUDA/HIP runtime. This is substantially different in
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000425 // default mode vs. separate compilation!
426 if (!RelocatableDeviceCode) {
Yaxun Liu29155b02018-05-18 15:07:56 +0000427 // GpuBinaryHandle = __{cuda|hip}RegisterFatBinary(&FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000428 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
429 RegisterFatbinFunc,
430 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
431 GpuBinaryHandle = new llvm::GlobalVariable(
432 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
Yaxun Liu887c5692018-04-25 01:10:37 +0000433 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
434 addUnderscoredPrefixToName("_gpubin_handle"));
435
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000436 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
437 CGM.getPointerAlign());
Artem Belevich52cc4872015-05-07 19:34:16 +0000438
Yaxun Liu29155b02018-05-18 15:07:56 +0000439 // Call __{cuda|hip}_register_globals(GpuBinaryHandle);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000440 if (RegisterGlobalsFunc)
441 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
442 } else {
443 // Generate a unique module ID.
Yaxun Liu29155b02018-05-18 15:07:56 +0000444 SmallString<64> ModuleID;
445 llvm::raw_svector_ostream OS(ModuleID);
446 OS << ModuleIDPrefix << llvm::format("%x", FatbinWrapper->getGUID());
447 llvm::Constant *ModuleIDConstant =
448 makeConstantString(ModuleID.str(), "", ModuleIDSectionName, 32);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000449
Yaxun Liu29155b02018-05-18 15:07:56 +0000450 // Create an alias for the FatbinWrapper that nvcc or hip backend will
451 // look for.
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000452 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
Yaxun Liu29155b02018-05-18 15:07:56 +0000453 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000454
Yaxun Liu29155b02018-05-18 15:07:56 +0000455 // void __{cuda|hip}RegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000456 // void *, void (*)(void **))
Yaxun Liu887c5692018-04-25 01:10:37 +0000457 SmallString<128> RegisterLinkedBinaryName(
458 addUnderscoredPrefixToName("RegisterLinkedBinary"));
Yaxun Liu29155b02018-05-18 15:07:56 +0000459 RegisterLinkedBinaryName += ModuleID;
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000460 llvm::Constant *RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
461 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
462
463 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
464 llvm::Value *Args[] = {RegisterGlobalsFunc,
465 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
Yaxun Liu29155b02018-05-18 15:07:56 +0000466 ModuleIDConstant,
Jonas Hahnfeldf5527c22018-04-20 13:04:45 +0000467 makeDummyFunction(getCallbackFnTy())};
468 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
469 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000470
471 CtorBuilder.CreateRetVoid();
472 return ModuleCtorFunc;
473}
474
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000475/// Creates a global destructor function that unregisters the GPU code blob
Artem Belevich52cc4872015-05-07 19:34:16 +0000476/// registered by constructor.
477/// \code
478/// void __cuda_module_dtor(void*) {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000479/// __cudaUnregisterFatBinary(Handle);
Artem Belevich52cc4872015-05-07 19:34:16 +0000480/// }
481/// \endcode
482llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000483 // No need for destructor if we don't have a handle to unregister.
484 if (!GpuBinaryHandle)
Artem Belevich8c1ec1e2016-03-02 18:28:53 +0000485 return nullptr;
486
Artem Belevich52cc4872015-05-07 19:34:16 +0000487 // void __cudaUnregisterFatBinary(void ** handle);
488 llvm::Constant *UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
489 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000490 addUnderscoredPrefixToName("UnregisterFatBinary"));
Artem Belevich52cc4872015-05-07 19:34:16 +0000491
492 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
493 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
Yaxun Liu887c5692018-04-25 01:10:37 +0000494 llvm::GlobalValue::InternalLinkage,
495 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
496
Artem Belevich52cc4872015-05-07 19:34:16 +0000497 llvm::BasicBlock *DtorEntryBB =
498 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000499 CGBuilderTy DtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000500 DtorBuilder.SetInsertPoint(DtorEntryBB);
501
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000502 auto HandleValue =
John McCall7f416cc2015-09-08 08:05:57 +0000503 DtorBuilder.CreateAlignedLoad(GpuBinaryHandle, CGM.getPointerAlign());
Jonas Hahnfelde7681322018-02-28 17:53:46 +0000504 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
Artem Belevich52cc4872015-05-07 19:34:16 +0000505
506 DtorBuilder.CreateRetVoid();
507 return ModuleDtorFunc;
508}
509
Peter Collingbournefe883422011-10-06 18:29:37 +0000510CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
511 return new CGNVCUDARuntime(CGM);
512}