20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/Support/Format.h" 26 using namespace clang;
27 using namespace CodeGen;
30 constexpr
unsigned CudaFatMagic = 0x466243b1;
31 constexpr
unsigned HIPFatMagic = 0x48495046;
36 llvm::IntegerType *IntTy, *SizeTy;
38 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
41 llvm::LLVMContext &Context;
43 llvm::Module &TheModule;
50 llvm::GlobalVariable *GpuBinaryHandle =
nullptr;
52 bool RelocatableDeviceCode;
54 llvm::Constant *getSetupArgumentFn()
const;
55 llvm::Constant *getLaunchFn()
const;
57 llvm::FunctionType *getRegisterGlobalsFnTy()
const;
58 llvm::FunctionType *getCallbackFnTy()
const;
59 llvm::FunctionType *getRegisterLinkedBinaryFnTy()
const;
60 std::string addPrefixToName(StringRef FuncName)
const;
61 std::string addUnderscoredPrefixToName(StringRef FuncName)
const;
64 llvm::Function *makeRegisterGlobalsFn();
69 llvm::Constant *makeConstantString(
const std::string &Str,
70 const std::string &Name =
"",
71 const std::string &SectionName =
"",
72 unsigned Alignment = 0) {
73 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
74 llvm::ConstantInt::get(SizeTy, 0)};
75 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
76 llvm::GlobalVariable *GV =
77 cast<llvm::GlobalVariable>(ConstStr.getPointer());
78 if (!SectionName.empty()) {
79 GV->setSection(SectionName);
82 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
85 GV->setAlignment(Alignment);
87 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
88 ConstStr.getPointer(), Zeros);
92 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
93 assert(FnTy->getReturnType()->isVoidTy() &&
94 "Can only generate dummy functions returning void!");
98 llvm::BasicBlock *DummyBlock =
101 FuncBuilder.SetInsertPoint(DummyBlock);
102 FuncBuilder.CreateRetVoid();
113 void registerDeviceVar(llvm::GlobalVariable &Var,
unsigned Flags)
override {
114 DeviceVars.push_back(std::make_pair(&Var, Flags));
118 llvm::Function *makeModuleCtorFunction()
override;
120 llvm::Function *makeModuleDtorFunction()
override;
125 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName)
const {
126 if (CGM.getLangOpts().HIP)
127 return ((Twine(
"hip") + Twine(FuncName)).str());
128 return ((Twine(
"cuda") + Twine(FuncName)).str());
131 CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName)
const {
132 if (CGM.getLangOpts().HIP)
133 return ((Twine(
"__hip") + Twine(FuncName)).str());
134 return ((Twine(
"__cuda") + Twine(FuncName)).str());
139 TheModule(CGM.getModule()),
140 RelocatableDeviceCode(CGM.getLangOpts().CUDARelocatableDeviceCode) {
150 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
153 llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn()
const {
157 llvm::FunctionType::get(IntTy, Params,
false),
158 addPrefixToName(
"SetupArgument"));
161 llvm::Constant *CGNVCUDARuntime::getLaunchFn()
const {
165 llvm::FunctionType::get(IntTy, CharPtrTy,
false),
"hipLaunchByPtr");
169 llvm::FunctionType::get(IntTy, CharPtrTy,
false),
"cudaLaunch");
173 llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy()
const {
174 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false);
177 llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy()
const {
178 return llvm::FunctionType::get(VoidTy, VoidPtrTy,
false);
181 llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy()
const {
182 auto CallbackFnTy = getCallbackFnTy();
183 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
185 VoidPtrTy, CallbackFnTy->getPointerTo()};
186 return llvm::FunctionType::get(VoidTy, Params,
false);
191 EmittedKernels.push_back(CGF.
CurFn);
192 emitDeviceStubBody(CGF, Args);
198 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
201 for (
const VarDecl *A : Args) {
203 std::tie(TyWidth, TyAlign) =
205 Offset = Offset.
alignTo(TyAlign);
209 llvm::ConstantInt::get(SizeTy, TyWidth.
getQuantity()),
210 llvm::ConstantInt::get(SizeTy, Offset.
getQuantity()),
213 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
216 CGF.
Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
222 llvm::Constant *cudaLaunchFn = getLaunchFn();
244 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
246 if (EmittedKernels.empty() && DeviceVars.empty())
251 addUnderscoredPrefixToName(
"_register_globals"), &TheModule);
252 llvm::BasicBlock *EntryBB =
255 Builder.SetInsertPoint(EntryBB);
263 llvm::FunctionType::get(IntTy, RegisterFuncParams,
false),
264 addUnderscoredPrefixToName(
"RegisterFunction"));
269 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
270 for (llvm::Function *Kernel : EmittedKernels) {
271 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
272 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
275 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
276 NullPtr, NullPtr, NullPtr,
277 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
278 Builder.CreateCall(RegisterFunc, Args);
287 llvm::FunctionType::get(IntTy, RegisterVarParams,
false),
288 addUnderscoredPrefixToName(
"RegisterVar"));
289 for (
auto &Pair : DeviceVars) {
290 llvm::GlobalVariable *Var = Pair.first;
291 unsigned Flags = Pair.second;
292 llvm::Constant *VarName = makeConstantString(Var->getName());
300 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
301 llvm::ConstantInt::get(IntTy, VarSize),
302 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
303 llvm::ConstantInt::get(IntTy, 0)};
304 Builder.CreateCall(RegisterVar, Args);
308 return RegisterKernelsFunc;
330 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
334 if (CudaGpuBinaryFileName.empty() && !IsHIP)
338 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
341 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
342 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
346 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy,
false),
347 addUnderscoredPrefixToName(
"RegisterFatBinary"));
349 llvm::StructType *FatbinWrapperTy =
350 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
356 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary;
358 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
359 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
360 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
362 << CudaGpuBinaryFileName << EC.message();
365 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
369 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
371 addUnderscoredPrefixToName(
"_module_ctor"), &TheModule);
372 llvm::BasicBlock *CtorEntryBB =
376 CtorBuilder.SetInsertPoint(CtorEntryBB);
378 const char *FatbinConstantName;
379 const char *FatbinSectionName;
380 const char *ModuleIDSectionName;
381 StringRef ModuleIDPrefix;
382 llvm::Constant *FatBinStr;
385 FatbinConstantName =
".hip_fatbin";
386 FatbinSectionName =
".hipFatBinSegment";
388 ModuleIDSectionName =
"__hip_module_id";
389 ModuleIDPrefix =
"__hip_";
394 FatBinStr =
new llvm::GlobalVariable(
397 "__hip_fatbin",
nullptr,
398 llvm::GlobalVariable::NotThreadLocal);
399 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
401 FatMagic = HIPFatMagic;
403 if (RelocatableDeviceCode)
404 FatbinConstantName = CGM.
getTriple().isMacOSX()
405 ?
"__NV_CUDA,__nv_relfatbin" 409 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__nv_fatbin" :
".nv_fatbin";
412 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__fatbin" :
".nvFatBinSegment";
414 ModuleIDSectionName = CGM.
getTriple().isMacOSX()
415 ?
"__NV_CUDA,__nv_module_id" 417 ModuleIDPrefix =
"__nv_";
421 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(),
"",
422 FatbinConstantName, 8);
423 FatMagic = CudaFatMagic;
428 auto Values =
Builder.beginStruct(FatbinWrapperTy);
430 Values.addInt(IntTy, FatMagic);
432 Values.addInt(IntTy, 1);
434 Values.add(FatBinStr);
436 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
437 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
440 FatbinWrapper->setSection(FatbinSectionName);
450 llvm::BasicBlock *IfBlock =
452 llvm::BasicBlock *ExitBlock =
456 GpuBinaryHandle =
new llvm::GlobalVariable(
457 TheModule, VoidPtrPtrTy,
false,
458 llvm::GlobalValue::LinkOnceAnyLinkage,
459 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
460 "__hip_gpubin_handle");
466 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
467 llvm::Constant *Zero =
468 llvm::Constant::getNullValue(HandleValue->getType());
469 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
470 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
473 CtorBuilder.SetInsertPoint(IfBlock);
475 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
477 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
478 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
479 CtorBuilder.CreateBr(ExitBlock);
482 CtorBuilder.SetInsertPoint(ExitBlock);
484 if (RegisterGlobalsFunc) {
485 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
486 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
489 }
else if (!RelocatableDeviceCode) {
493 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
495 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
496 GpuBinaryHandle =
new llvm::GlobalVariable(
498 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
"__cuda_gpubin_handle");
500 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
504 if (RegisterGlobalsFunc)
505 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
509 llvm::raw_svector_ostream OS(ModuleID);
510 OS << ModuleIDPrefix << llvm::format(
"%x", FatbinWrapper->getGUID());
511 llvm::Constant *ModuleIDConstant =
512 makeConstantString(ModuleID.str(),
"", ModuleIDSectionName, 32);
516 Twine(
"__fatbinwrap") + ModuleID, FatbinWrapper);
521 RegisterLinkedBinaryName += ModuleID;
523 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
525 assert(RegisterGlobalsFunc &&
"Expecting at least dummy function!");
527 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
529 makeDummyFunction(getCallbackFnTy())};
530 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
536 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
538 llvm::FunctionType *AtExitTy =
539 llvm::FunctionType::get(IntTy, CleanupFn->getType(),
false);
540 llvm::Constant *AtExitFunc =
543 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
546 CtorBuilder.CreateRetVoid();
547 return ModuleCtorFunc;
569 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
571 if (!GpuBinaryHandle)
576 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
577 addUnderscoredPrefixToName(
"UnregisterFatBinary"));
580 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
582 addUnderscoredPrefixToName(
"_module_dtor"), &TheModule);
584 llvm::BasicBlock *DtorEntryBB =
587 DtorBuilder.SetInsertPoint(DtorEntryBB);
590 GpuBinaryHandle->getAlignment()));
591 auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
596 llvm::BasicBlock *IfBlock =
598 llvm::BasicBlock *ExitBlock =
600 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
601 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
602 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
604 DtorBuilder.SetInsertPoint(IfBlock);
605 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
606 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
607 DtorBuilder.CreateBr(ExitBlock);
609 DtorBuilder.SetInsertPoint(ExitBlock);
611 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
613 DtorBuilder.CreateRetVoid();
614 return ModuleDtorFunc;
618 return new CGNVCUDARuntime(CGM);
const llvm::DataLayout & getDataLayout() const
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
llvm::IntegerType * IntTy
int
External linkage, which indicates that the entity can be referred to from other translation units...
CodeGenTypes & getTypes()
const CodeGenOptions & getCodeGenOpts() const
The standard implementation of ConstantInitBuilder used in Clang.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Represents a variable declaration or definition.
DiagnosticsEngine & getDiags() const
llvm::Value * getPointer() const
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
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
CharUnits - This is an opaque type for sizes expressed in character units.
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.
CharUnits getPointerAlign() const
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
const LangOptions & getLangOpts() const
ASTContext & getContext() const
The l-value was considered opaque, so the alignment was determined from a type.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value *> args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) 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.
std::string CudaGpuBinaryFileName
Name of file passed with -fcuda-include-gpubinary option to forward to CUDA runtime back-end for inco...
Dataflow Directional Tag Classes.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
llvm::Module & getModule() const
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.
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.
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 llvm::Triple & getTriple() const