blob: f0ecb57c71472e02206dbcc7665f00250cb297e0 [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"
Chandler Carruthffd55512013-01-02 11:45:17 +000019#include "llvm/IR/BasicBlock.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000020#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DerivedTypes.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000023
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28
29class CGNVCUDARuntime : public CGCUDARuntime {
Peter Collingbournefa4d6032011-10-06 18:51:56 +000030
31private:
Artem Belevich52cc4872015-05-07 19:34:16 +000032 llvm::Type *IntTy, *SizeTy, *VoidTy;
33 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
34
35 /// Convenience reference to LLVM Context
36 llvm::LLVMContext &Context;
37 /// Convenience reference to the current module
38 llvm::Module &TheModule;
39 /// Keeps track of kernel launch stubs emitted in this module
40 llvm::SmallVector<llvm::Function *, 16> EmittedKernels;
Artem Belevich42e19492016-03-02 18:28:50 +000041 llvm::SmallVector<std::pair<llvm::GlobalVariable *, unsigned>, 16> DeviceVars;
Artem Belevich52cc4872015-05-07 19:34:16 +000042 /// Keeps track of variables containing handles of GPU binaries. Populated by
43 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
44 /// ModuleDtorFunction()
45 llvm::SmallVector<llvm::GlobalVariable *, 16> GpuBinaryHandles;
Peter Collingbournefa4d6032011-10-06 18:51:56 +000046
47 llvm::Constant *getSetupArgumentFn() const;
48 llvm::Constant *getLaunchFn() const;
49
Artem Belevich52cc4872015-05-07 19:34:16 +000050 /// Creates a function to register all kernel stubs generated in this module.
Artem Belevich42e19492016-03-02 18:28:50 +000051 llvm::Function *makeRegisterGlobalsFn();
Artem Belevich52cc4872015-05-07 19:34:16 +000052
53 /// Helper function that generates a constant string and returns a pointer to
54 /// the start of the string. The result of this function can be used anywhere
55 /// where the C code specifies const char*.
56 llvm::Constant *makeConstantString(const std::string &Str,
57 const std::string &Name = "",
58 unsigned Alignment = 0) {
59 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
60 llvm::ConstantInt::get(SizeTy, 0)};
John McCall7f416cc2015-09-08 08:05:57 +000061 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
62 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
63 ConstStr.getPointer(), Zeros);
Artem Belevich52cc4872015-05-07 19:34:16 +000064 }
65
66 void emitDeviceStubBody(CodeGenFunction &CGF, FunctionArgList &Args);
67
Peter Collingbournefe883422011-10-06 18:29:37 +000068public:
69 CGNVCUDARuntime(CodeGenModule &CGM);
Peter Collingbournefa4d6032011-10-06 18:51:56 +000070
Artem Belevich52cc4872015-05-07 19:34:16 +000071 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
Artem Belevich42e19492016-03-02 18:28:50 +000072 void registerDeviceVar(llvm::GlobalVariable &Var, unsigned Flags) override {
73 DeviceVars.push_back(std::make_pair(&Var, Flags));
74 }
75
Artem Belevich52cc4872015-05-07 19:34:16 +000076 /// Creates module constructor function
77 llvm::Function *makeModuleCtorFunction() override;
78 /// Creates module destructor function
79 llvm::Function *makeModuleDtorFunction() override;
Peter Collingbournefe883422011-10-06 18:29:37 +000080};
81
Alexander Kornienkoab9db512015-06-22 23:07:51 +000082}
Peter Collingbournefe883422011-10-06 18:29:37 +000083
Artem Belevich52cc4872015-05-07 19:34:16 +000084CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
85 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
86 TheModule(CGM.getModule()) {
Peter Collingbournefa4d6032011-10-06 18:51:56 +000087 CodeGen::CodeGenTypes &Types = CGM.getTypes();
88 ASTContext &Ctx = CGM.getContext();
89
90 IntTy = Types.ConvertType(Ctx.IntTy);
91 SizeTy = Types.ConvertType(Ctx.getSizeType());
Artem Belevich52cc4872015-05-07 19:34:16 +000092 VoidTy = llvm::Type::getVoidTy(Context);
Peter Collingbournefa4d6032011-10-06 18:51:56 +000093
94 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
95 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
Artem Belevich52cc4872015-05-07 19:34:16 +000096 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
Peter Collingbournefa4d6032011-10-06 18:51:56 +000097}
98
99llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn() const {
100 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
101 std::vector<llvm::Type*> Params;
102 Params.push_back(VoidPtrTy);
103 Params.push_back(SizeTy);
104 Params.push_back(SizeTy);
105 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(IntTy,
106 Params, false),
107 "cudaSetupArgument");
108}
109
110llvm::Constant *CGNVCUDARuntime::getLaunchFn() const {
111 // cudaError_t cudaLaunch(char *)
Artem Belevich52cc4872015-05-07 19:34:16 +0000112 return CGM.CreateRuntimeFunction(
113 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000114}
115
Artem Belevich52cc4872015-05-07 19:34:16 +0000116void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
117 FunctionArgList &Args) {
118 EmittedKernels.push_back(CGF.CurFn);
119 emitDeviceStubBody(CGF, Args);
120}
121
122void CGNVCUDARuntime::emitDeviceStubBody(CodeGenFunction &CGF,
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000123 FunctionArgList &Args) {
124 // Build the argument value list and the argument stack struct type.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000125 SmallVector<llvm::Value *, 16> ArgValues;
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000126 std::vector<llvm::Type *> ArgTypes;
127 for (FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
128 I != E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +0000129 llvm::Value *V = CGF.GetAddrOfLocalVar(*I).getPointer();
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000130 ArgValues.push_back(V);
131 assert(isa<llvm::PointerType>(V->getType()) && "Arg type not PointerType");
132 ArgTypes.push_back(cast<llvm::PointerType>(V->getType())->getElementType());
133 }
Artem Belevich52cc4872015-05-07 19:34:16 +0000134 llvm::StructType *ArgStackTy = llvm::StructType::get(Context, ArgTypes);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000135
136 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
137
138 // Emit the calls to cudaSetupArgument
139 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
140 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
141 llvm::Value *Args[3];
142 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
143 Args[0] = CGF.Builder.CreatePointerCast(ArgValues[I], VoidPtrTy);
144 Args[1] = CGF.Builder.CreateIntCast(
145 llvm::ConstantExpr::getSizeOf(ArgTypes[I]),
146 SizeTy, false);
147 Args[2] = CGF.Builder.CreateIntCast(
148 llvm::ConstantExpr::getOffsetOf(ArgStackTy, I),
149 SizeTy, false);
John McCall882987f2013-02-28 19:01:20 +0000150 llvm::CallSite CS = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000151 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
152 llvm::Value *CSZero = CGF.Builder.CreateICmpEQ(CS.getInstruction(), Zero);
153 CGF.Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
154 CGF.EmitBlock(NextBlock);
155 }
156
157 // Emit the call to cudaLaunch
158 llvm::Constant *cudaLaunchFn = getLaunchFn();
159 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
John McCall882987f2013-02-28 19:01:20 +0000160 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
Peter Collingbournefa4d6032011-10-06 18:51:56 +0000161 CGF.EmitBranch(EndBlock);
162
163 CGF.EmitBlock(EndBlock);
Peter Collingbournefe883422011-10-06 18:29:37 +0000164}
165
Artem Belevich42e19492016-03-02 18:28:50 +0000166/// Creates a function that sets up state on the host side for CUDA objects that
167/// have a presence on both the host and device sides. Specifically, registers
168/// the host side of kernel functions and device global variables with the CUDA
169/// runtime.
Artem Belevich52cc4872015-05-07 19:34:16 +0000170/// \code
Artem Belevich42e19492016-03-02 18:28:50 +0000171/// void __cuda_register_globals(void** GpuBinaryHandle) {
Artem Belevich52cc4872015-05-07 19:34:16 +0000172/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
173/// ...
174/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
Artem Belevich42e19492016-03-02 18:28:50 +0000175/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
176/// ...
177/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
Artem Belevich52cc4872015-05-07 19:34:16 +0000178/// }
179/// \endcode
Artem Belevich42e19492016-03-02 18:28:50 +0000180llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
Artem Belevich52cc4872015-05-07 19:34:16 +0000181 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
182 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
Artem Belevich42e19492016-03-02 18:28:50 +0000183 llvm::GlobalValue::InternalLinkage, "__cuda_register_globals", &TheModule);
Artem Belevich52cc4872015-05-07 19:34:16 +0000184 llvm::BasicBlock *EntryBB =
185 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000186 CGBuilderTy Builder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000187 Builder.SetInsertPoint(EntryBB);
188
189 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
190 // int, uint3*, uint3*, dim3*, dim3*, int*)
191 std::vector<llvm::Type *> RegisterFuncParams = {
192 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
193 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
194 llvm::Constant *RegisterFunc = CGM.CreateRuntimeFunction(
195 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
196 "__cudaRegisterFunction");
197
198 // Extract GpuBinaryHandle passed as the first argument passed to
Artem Belevich42e19492016-03-02 18:28:50 +0000199 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
Artem Belevich52cc4872015-05-07 19:34:16 +0000200 // each emitted kernel.
201 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
202 for (llvm::Function *Kernel : EmittedKernels) {
203 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
204 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
Artem Belevich42e19492016-03-02 18:28:50 +0000205 llvm::Value *Args[] = {
Artem Belevich52cc4872015-05-07 19:34:16 +0000206 &GpuBinaryHandlePtr, Builder.CreateBitCast(Kernel, VoidPtrTy),
207 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
208 NullPtr, NullPtr, NullPtr,
209 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
Artem Belevich42e19492016-03-02 18:28:50 +0000210 Builder.CreateCall(RegisterFunc, Args);
211 }
212
213 // void __cudaRegisterVar(void **, char *, char *, const char *,
214 // int, int, int, int)
215 std::vector<llvm::Type *> RegisterVarParams = {
216 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy,
217 IntTy, IntTy, IntTy, IntTy};
218 llvm::Constant *RegisterVar = CGM.CreateRuntimeFunction(
219 llvm::FunctionType::get(IntTy, RegisterVarParams, false),
220 "__cudaRegisterVar");
221 for (auto &Pair : DeviceVars) {
222 llvm::GlobalVariable *Var = Pair.first;
223 unsigned Flags = Pair.second;
224 llvm::Constant *VarName = makeConstantString(Var->getName());
225 uint64_t VarSize =
226 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
227 llvm::Value *Args[] = {
228 &GpuBinaryHandlePtr,
229 Builder.CreateBitCast(Var, VoidPtrTy),
230 VarName,
231 VarName,
232 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
233 llvm::ConstantInt::get(IntTy, VarSize),
234 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
235 llvm::ConstantInt::get(IntTy, 0)};
236 Builder.CreateCall(RegisterVar, Args);
Artem Belevich52cc4872015-05-07 19:34:16 +0000237 }
238
239 Builder.CreateRetVoid();
240 return RegisterKernelsFunc;
241}
242
243/// Creates a global constructor function for the module:
244/// \code
245/// void __cuda_module_ctor(void*) {
246/// Handle0 = __cudaRegisterFatBinary(GpuBinaryBlob0);
Artem Belevich42e19492016-03-02 18:28:50 +0000247/// __cuda_register_globals(Handle0);
Artem Belevich52cc4872015-05-07 19:34:16 +0000248/// ...
249/// HandleN = __cudaRegisterFatBinary(GpuBinaryBlobN);
Artem Belevich42e19492016-03-02 18:28:50 +0000250/// __cuda_register_globals(HandleN);
Artem Belevich52cc4872015-05-07 19:34:16 +0000251/// }
252/// \endcode
253llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
Artem Belevich42e19492016-03-02 18:28:50 +0000254 // void __cuda_register_globals(void* handle);
255 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
Artem Belevich52cc4872015-05-07 19:34:16 +0000256 // void ** __cudaRegisterFatBinary(void *);
257 llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
258 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
259 "__cudaRegisterFatBinary");
260 // struct { int magic, int version, void * gpu_binary, void * dont_care };
261 llvm::StructType *FatbinWrapperTy =
262 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy, nullptr);
263
264 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
265 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
266 llvm::GlobalValue::InternalLinkage, "__cuda_module_ctor", &TheModule);
267 llvm::BasicBlock *CtorEntryBB =
268 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000269 CGBuilderTy CtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000270
271 CtorBuilder.SetInsertPoint(CtorEntryBB);
272
273 // For each GPU binary, register it with the CUDA runtime and store returned
274 // handle in a global variable and save the handle in GpuBinaryHandles vector
275 // to be cleaned up in destructor on exit. Then associate all known kernels
276 // with the GPU binary handle so CUDA runtime can figure out what to call on
277 // the GPU side.
278 for (const std::string &GpuBinaryFileName :
279 CGM.getCodeGenOpts().CudaGpuBinaryFileNames) {
280 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GpuBinaryOrErr =
281 llvm::MemoryBuffer::getFileOrSTDIN(GpuBinaryFileName);
282 if (std::error_code EC = GpuBinaryOrErr.getError()) {
283 CGM.getDiags().Report(diag::err_cannot_open_file) << GpuBinaryFileName
284 << EC.message();
285 continue;
286 }
287
288 // Create initialized wrapper structure that points to the loaded GPU binary
289 llvm::Constant *Values[] = {
290 llvm::ConstantInt::get(IntTy, 0x466243b1), // Fatbin wrapper magic.
291 llvm::ConstantInt::get(IntTy, 1), // Fatbin version.
292 makeConstantString(GpuBinaryOrErr.get()->getBuffer(), "", 16), // Data.
293 llvm::ConstantPointerNull::get(VoidPtrTy)}; // Unused in fatbin v1.
294 llvm::GlobalVariable *FatbinWrapper = new llvm::GlobalVariable(
295 TheModule, FatbinWrapperTy, true, llvm::GlobalValue::InternalLinkage,
296 llvm::ConstantStruct::get(FatbinWrapperTy, Values),
297 "__cuda_fatbin_wrapper");
Justin Lebar21e5d4f2016-01-14 21:41:27 +0000298 // NVIDIA's cuobjdump looks for fatbins in this section.
299 FatbinWrapper->setSection(".nvFatBinSegment");
Artem Belevich52cc4872015-05-07 19:34:16 +0000300
301 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
302 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
303 RegisterFatbinFunc,
304 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
305 llvm::GlobalVariable *GpuBinaryHandle = new llvm::GlobalVariable(
306 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
307 llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
John McCall7f416cc2015-09-08 08:05:57 +0000308 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
309 CGM.getPointerAlign());
Artem Belevich52cc4872015-05-07 19:34:16 +0000310
Artem Belevich42e19492016-03-02 18:28:50 +0000311 // Call __cuda_register_globals(GpuBinaryHandle);
312 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
Artem Belevich52cc4872015-05-07 19:34:16 +0000313
314 // Save GpuBinaryHandle so we can unregister it in destructor.
315 GpuBinaryHandles.push_back(GpuBinaryHandle);
316 }
317
318 CtorBuilder.CreateRetVoid();
319 return ModuleCtorFunc;
320}
321
322/// Creates a global destructor function that unregisters all GPU code blobs
323/// registered by constructor.
324/// \code
325/// void __cuda_module_dtor(void*) {
326/// __cudaUnregisterFatBinary(Handle0);
327/// ...
328/// __cudaUnregisterFatBinary(HandleN);
329/// }
330/// \endcode
331llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
332 // void __cudaUnregisterFatBinary(void ** handle);
333 llvm::Constant *UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
334 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
335 "__cudaUnregisterFatBinary");
336
337 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
338 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
339 llvm::GlobalValue::InternalLinkage, "__cuda_module_dtor", &TheModule);
340 llvm::BasicBlock *DtorEntryBB =
341 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
John McCall7f416cc2015-09-08 08:05:57 +0000342 CGBuilderTy DtorBuilder(CGM, Context);
Artem Belevich52cc4872015-05-07 19:34:16 +0000343 DtorBuilder.SetInsertPoint(DtorEntryBB);
344
345 for (llvm::GlobalVariable *GpuBinaryHandle : GpuBinaryHandles) {
John McCall7f416cc2015-09-08 08:05:57 +0000346 auto HandleValue =
347 DtorBuilder.CreateAlignedLoad(GpuBinaryHandle, CGM.getPointerAlign());
348 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
Artem Belevich52cc4872015-05-07 19:34:16 +0000349 }
350
351 DtorBuilder.CreateRetVoid();
352 return ModuleDtorFunc;
353}
354
Peter Collingbournefe883422011-10-06 18:29:37 +0000355CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
356 return new CGNVCUDARuntime(CGM);
357}