20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 25 using namespace clang;
26 using namespace CodeGen;
33 llvm::IntegerType *IntTy, *SizeTy;
35 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
38 llvm::LLVMContext &Context;
40 llvm::Module &TheModule;
49 llvm::Constant *getSetupArgumentFn()
const;
50 llvm::Constant *getLaunchFn()
const;
53 llvm::Function *makeRegisterGlobalsFn();
58 llvm::Constant *makeConstantString(
const std::string &Str,
59 const std::string &Name =
"",
60 const std::string &SectionName =
"",
61 unsigned Alignment = 0) {
62 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
63 llvm::ConstantInt::get(SizeTy, 0)};
64 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
65 llvm::GlobalVariable *GV =
66 cast<llvm::GlobalVariable>(ConstStr.getPointer());
67 if (!SectionName.empty())
68 GV->setSection(SectionName);
70 GV->setAlignment(Alignment);
72 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
73 ConstStr.getPointer(), Zeros);
82 void registerDeviceVar(llvm::GlobalVariable &Var,
unsigned Flags)
override {
83 DeviceVars.push_back(std::make_pair(&Var, Flags));
87 llvm::Function *makeModuleCtorFunction()
override;
89 llvm::Function *makeModuleDtorFunction()
override;
96 TheModule(CGM.getModule()) {
106 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
109 llvm::Constant *CGNVCUDARuntime::getSetupArgumentFn()
const {
114 "cudaSetupArgument");
117 llvm::Constant *CGNVCUDARuntime::getLaunchFn()
const {
120 llvm::FunctionType::get(IntTy, CharPtrTy,
false),
"cudaLaunch");
125 EmittedKernels.push_back(CGF.
CurFn);
126 emitDeviceStubBody(CGF, Args);
132 llvm::Constant *cudaSetupArgFn = getSetupArgumentFn();
135 for (
const VarDecl *A : Args) {
137 std::tie(TyWidth, TyAlign) =
139 Offset = Offset.
alignTo(TyAlign);
143 llvm::ConstantInt::get(SizeTy, TyWidth.
getQuantity()),
144 llvm::ConstantInt::get(SizeTy, Offset.
getQuantity()),
147 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
150 CGF.
Builder.CreateCondBr(CSZero, NextBlock, EndBlock);
156 llvm::Constant *cudaLaunchFn = getLaunchFn();
178 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
180 if (EmittedKernels.empty() && DeviceVars.empty())
184 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
186 llvm::BasicBlock *EntryBB =
189 Builder.SetInsertPoint(EntryBB);
197 llvm::FunctionType::get(IntTy, RegisterFuncParams,
false),
198 "__cudaRegisterFunction");
203 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
204 for (llvm::Function *Kernel : EmittedKernels) {
205 llvm::Constant *KernelName = makeConstantString(Kernel->getName());
206 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
209 KernelName, KernelName, llvm::ConstantInt::get(IntTy, -1), NullPtr,
210 NullPtr, NullPtr, NullPtr,
211 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
212 Builder.CreateCall(RegisterFunc, Args);
221 llvm::FunctionType::get(IntTy, RegisterVarParams,
false),
222 "__cudaRegisterVar");
223 for (
auto &Pair : DeviceVars) {
224 llvm::GlobalVariable *Var = Pair.first;
225 unsigned Flags = Pair.second;
226 llvm::Constant *VarName = makeConstantString(Var->getName());
234 llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 1 : 0),
235 llvm::ConstantInt::get(IntTy, VarSize),
236 llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 1 : 0),
237 llvm::ConstantInt::get(IntTy, 0)};
238 Builder.CreateCall(RegisterVar, Args);
242 return RegisterKernelsFunc;
255 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
261 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
264 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy,
false),
265 "__cudaRegisterFatBinary");
267 llvm::StructType *FatbinWrapperTy =
268 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
271 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
273 llvm::BasicBlock *CtorEntryBB =
277 CtorBuilder.SetInsertPoint(CtorEntryBB);
284 for (
const std::string &GpuBinaryFileName :
286 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> GpuBinaryOrErr =
287 llvm::MemoryBuffer::getFileOrSTDIN(GpuBinaryFileName);
288 if (std::error_code EC = GpuBinaryOrErr.getError()) {
289 CGM.
getDiags().
Report(diag::err_cannot_open_file) << GpuBinaryFileName
294 const char *FatbinConstantName =
295 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__nv_fatbin" :
".nv_fatbin";
297 const char *FatbinSectionName =
298 CGM.
getTriple().isMacOSX() ?
"__NV_CUDA,__fatbin" :
".nvFatBinSegment";
302 auto Values =
Builder.beginStruct(FatbinWrapperTy);
304 Values.addInt(IntTy, 0x466243b1);
306 Values.addInt(IntTy, 1);
308 Values.add(makeConstantString(GpuBinaryOrErr.get()->getBuffer(),
309 "", FatbinConstantName, 8));
311 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
312 llvm::GlobalVariable *FatbinWrapper =
313 Values.finishAndCreateGlobal(
"__cuda_fatbin_wrapper",
316 FatbinWrapper->setSection(FatbinSectionName);
319 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
321 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
322 llvm::GlobalVariable *GpuBinaryHandle =
new llvm::GlobalVariable(
324 llvm::ConstantPointerNull::get(VoidPtrPtrTy),
"__cuda_gpubin_handle");
325 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
329 if (RegisterGlobalsFunc)
330 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
333 GpuBinaryHandles.push_back(GpuBinaryHandle);
336 CtorBuilder.CreateRetVoid();
337 return ModuleCtorFunc;
349 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
351 if (GpuBinaryHandles.empty())
356 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy,
false),
357 "__cudaUnregisterFatBinary");
360 llvm::FunctionType::get(VoidTy, VoidPtrTy,
false),
362 llvm::BasicBlock *DtorEntryBB =
365 DtorBuilder.SetInsertPoint(DtorEntryBB);
367 for (llvm::GlobalVariable *GpuBinaryHandle : GpuBinaryHandles) {
370 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
373 DtorBuilder.CreateRetVoid();
374 return ModuleDtorFunc;
378 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
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.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
DiagnosticsEngine & getDiags() const
llvm::Value * getPointer() const
std::vector< std::string > CudaGpuBinaryFileNames
A list of file names passed with -fcuda-include-gpubinary options to forward to CUDA runtime back-end...
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.
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.
Dataflow Directional Tag Classes.
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