19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
24 using namespace clang;
25 using namespace CodeGen;
33 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
38 llvm::Module &TheModule;
47 llvm::Constant *getSetupArgumentFn()
const;
48 llvm::Constant *getLaunchFn()
const;
51 llvm::Function *makeRegisterGlobalsFn();
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)};
61 auto ConstStr = CGM.GetAddrOfConstantCString(Str,
Name.c_str());
62 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
63 ConstStr.getPointer(), Zeros);
72 void registerDeviceVar(llvm::GlobalVariable &Var,
unsigned Flags)
override {
73 DeviceVars.push_back(std::make_pair(&Var, Flags));
77 llvm::Function *makeModuleCtorFunction()
override;
79 llvm::Function *makeModuleDtorFunction()
override;
86 TheModule(CGM.getModule()) {
99 llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn()
const {
101 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
104 "cudaSetupArgument");
107 llvm::Constant *CGNVCUDARuntime::getLaunchFn()
const {
110 llvm::FunctionType::get(IntTy, CharPtrTy,
false),
"cudaLaunch");
115 EmittedKernels.push_back(CGF.
CurFn);
116 emitDeviceStubBody(CGF, Args);
123 std::vector<llvm::Type *> ArgTypes;
124 for (FunctionArgList::const_iterator
I = Args.begin(),
E = Args.end();
127 ArgValues.push_back(V);
128 assert(isa<llvm::PointerType>(V->getType()) &&
"Arg type not PointerType");
129 ArgTypes.push_back(cast<llvm::PointerType>(V->getType())->getElementType());
131 llvm::StructType *ArgStackTy = llvm::StructType::get(
Context, ArgTypes);
136 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
137 for (
unsigned I = 0,
E = Args.size();
I !=
E; ++
I) {
140 Args[0] = CGF.
Builder.CreatePointerCast(ArgValues[
I], VoidPtrTy);
141 Args[1] = CGF.
Builder.CreateIntCast(
142 llvm::ConstantExpr::getSizeOf(ArgTypes[I]),
144 Args[2] = CGF.
Builder.CreateIntCast(
145 llvm::ConstantExpr::getOffsetOf(ArgStackTy, I),
148 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
150 CGF.
Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
155 llvm::Constant *cudaLaunchFn = getLaunchFn();
177 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
179 if (EmittedKernels.empty() && DeviceVars.empty())
183 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
185 llvm::BasicBlock *EntryBB =
188 Builder.SetInsertPoint(EntryBB);
193 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
194 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
196 llvm::FunctionType::get(IntTy, RegisterFuncParams,
false),
197 "__cudaRegisterFunction");
202 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
203 for (llvm::Function *Kernel : EmittedKernels) {
204 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
205 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
207 &GpuBinaryHandlePtr,
Builder.CreateBitCast(Kernel, VoidPtrTy),
208 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
209 NullPtr, NullPtr, NullPtr,
210 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
211 Builder.CreateCall(RegisterFunc, Args);
216 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
217 CharPtrTy, IntTy, IntTy,
220 llvm::FunctionType::get(IntTy, RegisterVarParams,
false),
221 "__cudaRegisterVar");
222 for (
auto &Pair : DeviceVars) {
223 llvm::GlobalVariable *Var = Pair.first;
224 unsigned Flags = Pair.second;
225 llvm::Constant *VarName = makeConstantString(Var->getName());
230 Builder.CreateBitCast(Var, VoidPtrTy),
233 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
234 llvm::ConstantInt::get(IntTy, VarSize),
235 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
236 llvm::ConstantInt::get(IntTy, 0)};
237 Builder.CreateCall(RegisterVar, Args);
241 return RegisterKernelsFunc;
254 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
260 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
263 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy,
false),
264 "__cudaRegisterFatBinary");
266 llvm::StructType *FatbinWrapperTy =
267 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy,
nullptr);
270 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
272 llvm::BasicBlock *CtorEntryBB =
276 CtorBuilder.SetInsertPoint(CtorEntryBB);
283 for (
const std::string &GpuBinaryFileName :
285 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GpuBinaryOrErr =
286 llvm::MemoryBuffer::getFileOrSTDIN(GpuBinaryFileName);
287 if (std::error_code EC = GpuBinaryOrErr.getError()) {
288 CGM.
getDiags().
Report(diag::err_cannot_open_file) << GpuBinaryFileName
294 llvm::Constant *Values[] = {
295 llvm::ConstantInt::get(IntTy, 0x466243b1),
296 llvm::ConstantInt::get(IntTy, 1),
297 makeConstantString(GpuBinaryOrErr.get()->getBuffer(),
"", 16),
298 llvm::ConstantPointerNull::get(VoidPtrTy)};
299 llvm::GlobalVariable *FatbinWrapper =
new llvm::GlobalVariable(
301 llvm::ConstantStruct::get(FatbinWrapperTy, Values),
302 "__cuda_fatbin_wrapper");
304 FatbinWrapper->setSection(
".nvFatBinSegment");
307 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
309 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
310 llvm::GlobalVariable *GpuBinaryHandle =
new llvm::GlobalVariable(
312 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
"__cuda_gpubin_handle");
313 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
317 if (RegisterGlobalsFunc)
318 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
321 GpuBinaryHandles.push_back(GpuBinaryHandle);
324 CtorBuilder.CreateRetVoid();
325 return ModuleCtorFunc;
337 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
339 if (GpuBinaryHandles.empty())
344 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
345 "__cudaUnregisterFatBinary");
348 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
350 llvm::BasicBlock *DtorEntryBB =
353 DtorBuilder.SetInsertPoint(DtorEntryBB);
355 for (llvm::GlobalVariable *GpuBinaryHandle : GpuBinaryHandles) {
358 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
361 DtorBuilder.CreateRetVoid();
362 return ModuleDtorFunc;
366 return new CGNVCUDARuntime(CGM);
llvm::IntegerType * IntTy
int
CodeGenTypes & getTypes()
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const llvm::DataLayout & getDataLayout() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
std::vector< std::string > CudaGpuBinaryFileNames
A list of file names passed with -fcuda-include-gpubinary options to forward to CUDA runtime back-end...
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
llvm::IntegerType * SizeTy
llvm::PointerType * VoidPtrTy
llvm::PointerType * VoidPtrPtrTy
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
detail::InMemoryDirectory::const_iterator I
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
llvm::Value * getPointer() const
ASTContext & getContext() const
The l-value was considered opaque, so the alignment was determined from a type.
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeSet ExtraAttrs=llvm::AttributeSet())
Create a new runtime function with the specified type and name.
CharUnits getPointerAlign() const
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
const CodeGenOptions & getCodeGenOpts() const
FunctionArgList - Type for representing both the decl and type of parameters to a function...
This class organizes the cross-function state that is used while generating LLVM code.
detail::InMemoryDirectory::const_iterator E
This class organizes the cross-module state that is used while lowering AST types to LLVM types...
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
DiagnosticsEngine & getDiags() const
BoundNodesTreeBuilder *const Builder
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block, taking care to avoid creation of branches from dummy blocks.