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);
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().GPURelocatableDeviceCode) {
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 =
nullptr;
357 if (!CudaGpuBinaryFileName.empty()) {
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 = makeConstantString(CudaGpuBinary->getBuffer(),
"",
395 FatbinConstantName, 8);
401 FatBinStr =
new llvm::GlobalVariable(
404 "__hip_fatbin",
nullptr,
405 llvm::GlobalVariable::NotThreadLocal);
406 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
409 FatMagic = HIPFatMagic;
411 if (RelocatableDeviceCode)
412 FatbinConstantName = CGM.
getTriple().isMacOSX()
413 ?
"__NV_CUDA,__nv_relfatbin" 417 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__nv_fatbin" :
".nv_fatbin";
420 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__fatbin" :
".nvFatBinSegment";
422 ModuleIDSectionName = CGM.
getTriple().isMacOSX()
423 ?
"__NV_CUDA,__nv_module_id" 425 ModuleIDPrefix =
"__nv_";
429 FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(),
"",
430 FatbinConstantName, 8);
431 FatMagic = CudaFatMagic;
436 auto Values =
Builder.beginStruct(FatbinWrapperTy);
438 Values.addInt(IntTy, FatMagic);
440 Values.addInt(IntTy, 1);
442 Values.add(FatBinStr);
444 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
445 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
448 FatbinWrapper->setSection(FatbinSectionName);
459 llvm::GlobalValue::LinkOnceAnyLinkage;
460 llvm::BasicBlock *IfBlock =
462 llvm::BasicBlock *ExitBlock =
466 GpuBinaryHandle =
new llvm::GlobalVariable(
467 TheModule, VoidPtrPtrTy,
false,
469 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
470 "__hip_gpubin_handle");
479 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
480 llvm::Constant *Zero =
481 llvm::Constant::getNullValue(HandleValue->getType());
482 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
483 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
486 CtorBuilder.SetInsertPoint(IfBlock);
488 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
490 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
491 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
492 CtorBuilder.CreateBr(ExitBlock);
495 CtorBuilder.SetInsertPoint(ExitBlock);
497 if (RegisterGlobalsFunc) {
498 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
499 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
502 }
else if (!RelocatableDeviceCode) {
506 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
508 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
509 GpuBinaryHandle =
new llvm::GlobalVariable(
511 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
"__cuda_gpubin_handle");
513 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
517 if (RegisterGlobalsFunc)
518 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
522 llvm::raw_svector_ostream
OS(ModuleID);
523 OS << ModuleIDPrefix << llvm::format(
"%" PRIx64, FatbinWrapper->getGUID());
524 llvm::Constant *ModuleIDConstant =
525 makeConstantString(ModuleID.str(),
"", ModuleIDSectionName, 32);
529 Twine(
"__fatbinwrap") + ModuleID, FatbinWrapper);
534 RegisterLinkedBinaryName += ModuleID;
536 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
538 assert(RegisterGlobalsFunc &&
"Expecting at least dummy function!");
540 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
542 makeDummyFunction(getCallbackFnTy())};
543 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
549 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
551 llvm::FunctionType *AtExitTy =
552 llvm::FunctionType::get(IntTy, CleanupFn->getType(),
false);
553 llvm::Constant *AtExitFunc =
556 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
559 CtorBuilder.CreateRetVoid();
560 return ModuleCtorFunc;
582 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
584 if (!GpuBinaryHandle)
589 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
590 addUnderscoredPrefixToName(
"UnregisterFatBinary"));
593 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
595 addUnderscoredPrefixToName(
"_module_dtor"), &TheModule);
597 llvm::BasicBlock *DtorEntryBB =
600 DtorBuilder.SetInsertPoint(DtorEntryBB);
603 GpuBinaryHandle->getAlignment()));
604 auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
609 llvm::BasicBlock *IfBlock =
611 llvm::BasicBlock *ExitBlock =
613 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
614 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
615 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
617 DtorBuilder.SetInsertPoint(IfBlock);
618 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
619 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
620 DtorBuilder.CreateBr(ExitBlock);
622 DtorBuilder.SetInsertPoint(ExitBlock);
624 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
626 DtorBuilder.CreateRetVoid();
627 return ModuleDtorFunc;
631 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.
Objects with "hidden" visibility are not seen by the dynamic linker.
DiagnosticsEngine & getDiags() const
llvm::Value * getPointer() const
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
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.
constexpr XRayInstrMask None
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
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
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