clang 23.0.0git
CGCUDANV.cpp
Go to the documentation of this file.
1//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for CUDA code generation targeting the NVIDIA CUDA
10// runtime library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/Basic/Cuda.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Frontend/Offloading/Utility.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/ReplaceConstant.h"
29#include "llvm/ProfileData/InstrProf.h"
30#include "llvm/Support/Format.h"
31#include "llvm/Support/VirtualFileSystem.h"
32#include "llvm/Transforms/Utils/ModuleUtils.h"
33
34using namespace clang;
35using namespace CodeGen;
36
37namespace {
38constexpr unsigned CudaFatMagic = 0x466243b1;
39constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
40
41class CGNVCUDARuntime : public CGCUDARuntime {
42
43 /// The prefix used for function calls and section names (CUDA, HIP, LLVM)
44 StringRef Prefix;
45
46private:
47 llvm::IntegerType *IntTy, *SizeTy;
48 llvm::Type *VoidTy;
49 llvm::PointerType *PtrTy;
50
51 /// Convenience reference to LLVM Context
52 llvm::LLVMContext &Context;
53 /// Convenience reference to the current module
54 llvm::Module &TheModule;
55 /// Keeps track of kernel launch stubs and handles emitted in this module
56 struct KernelInfo {
57 llvm::Function *Kernel; // stub function to help launch kernel
58 const Decl *D;
59 };
60 llvm::SmallVector<KernelInfo, 16> EmittedKernels;
61 // Map a kernel mangled name to a symbol for identifying kernel in host code
62 // For CUDA, the symbol for identifying the kernel is the same as the device
63 // stub function. For HIP, they are different.
64 llvm::DenseMap<StringRef, llvm::GlobalValue *> KernelHandles;
65 // Map a kernel handle to the kernel stub.
66 llvm::DenseMap<llvm::GlobalValue *, llvm::Function *> KernelStubs;
67 struct VarInfo {
68 llvm::GlobalVariable *Var;
69 const VarDecl *D;
70 DeviceVarFlags Flags;
71 };
72 llvm::SmallVector<VarInfo, 16> DeviceVars;
73 /// Keeps track of variable containing handle of GPU binary. Populated by
74 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
75 /// ModuleDtorFunction()
76 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
77 /// Host-side shadow for the per-TU __llvm_profile_sections_<CUID> global,
78 /// emitted only for HIP host compiles when PGO is on. Registered via
79 /// __hipRegisterVar (non-RDC) or an offloading entry (RDC) so the runtime
80 /// can locate the device-side table by name.
81 llvm::GlobalVariable *OffloadProfShadow = nullptr;
82 struct OffloadProfSectionShadowInfo {
83 llvm::GlobalVariable *Shadow;
84 std::string DeviceName;
85 };
86 llvm::SmallVector<OffloadProfSectionShadowInfo, 16> OffloadProfSectionShadows;
87 /// Whether we generate relocatable device code.
88 bool RelocatableDeviceCode;
89 /// Mangle context for device.
90 std::unique_ptr<MangleContext> DeviceMC;
91
92 llvm::FunctionCallee getSetupArgumentFn() const;
93 llvm::FunctionCallee getLaunchFn() const;
94
95 llvm::FunctionType *getRegisterGlobalsFnTy() const;
96 llvm::FunctionType *getCallbackFnTy() const;
97 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
98 std::string addPrefixToName(StringRef FuncName) const;
99 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
100
101 /// Creates a function to register all kernel stubs generated in this module.
102 llvm::Function *makeRegisterGlobalsFn();
103
104 /// Helper function that generates a constant string and returns a pointer to
105 /// the start of the string. The result of this function can be used anywhere
106 /// where the C code specifies const char*.
107 llvm::Constant *makeConstantString(const std::string &Str,
108 const std::string &Name = "") {
109 return CGM.GetAddrOfConstantCString(Str, Name).getPointer();
110 }
111
112 /// Helper function which generates an initialized constant array from Str,
113 /// and optionally sets section name and alignment. AddNull specifies whether
114 /// the array should nave NUL termination.
115 llvm::Constant *makeConstantArray(StringRef Str,
116 StringRef Name = "",
117 StringRef SectionName = "",
118 unsigned Alignment = 0,
119 bool AddNull = false) {
120 llvm::Constant *Value =
121 llvm::ConstantDataArray::getString(Context, Str, AddNull);
122 auto *GV = new llvm::GlobalVariable(
123 TheModule, Value->getType(), /*isConstant=*/true,
124 llvm::GlobalValue::PrivateLinkage, Value, Name);
125 if (!SectionName.empty()) {
126 GV->setSection(SectionName);
127 // Mark the address as used which make sure that this section isn't
128 // merged and we will really have it in the object file.
129 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
130 }
131 if (Alignment)
132 GV->setAlignment(llvm::Align(Alignment));
133 return GV;
134 }
135
136 /// Helper function that generates an empty dummy function returning void.
137 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
138 assert(FnTy->getReturnType()->isVoidTy() &&
139 "Can only generate dummy functions returning void!");
140 llvm::Function *DummyFunc = llvm::Function::Create(
141 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
142
143 llvm::BasicBlock *DummyBlock =
144 llvm::BasicBlock::Create(Context, "", DummyFunc);
145 CGBuilderTy FuncBuilder(CGM, Context);
146 FuncBuilder.SetInsertPoint(DummyBlock);
147 FuncBuilder.CreateRetVoid();
148
149 return DummyFunc;
150 }
151
152 Address prepareKernelArgs(CodeGenFunction &CGF, FunctionArgList &Args);
153 Address prepareKernelArgsLLVMOffload(CodeGenFunction &CGF,
154 FunctionArgList &Args);
155 void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
156 void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
157 std::string getDeviceSideName(const NamedDecl *ND) override;
158
159 void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
160 bool Extern, bool Constant) {
161 DeviceVars.push_back({&Var,
162 VD,
163 {DeviceVarFlags::Variable, Extern, Constant,
164 VD->hasAttr<HIPManagedAttr>(),
165 /*Normalized*/ false, 0}});
166 }
167 void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,
168 bool Extern, int Type) {
169 DeviceVars.push_back({&Var,
170 VD,
171 {DeviceVarFlags::Surface, Extern, /*Constant*/ false,
172 /*Managed*/ false,
173 /*Normalized*/ false, Type}});
174 }
175 void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,
176 bool Extern, int Type, bool Normalized) {
177 DeviceVars.push_back({&Var,
178 VD,
179 {DeviceVarFlags::Texture, Extern, /*Constant*/ false,
180 /*Managed*/ false, Normalized, Type}});
181 }
182
183 /// Creates module constructor function
184 llvm::Function *makeModuleCtorFunction();
185 /// Creates module destructor function
186 llvm::Function *makeModuleDtorFunction();
187 /// Transform managed variables for device compilation.
188 void transformManagedVars();
189 /// Create offloading entries to register globals in RDC mode.
190 void createOffloadingEntries();
191 /// For HIP+PGO, emit the per-TU __llvm_profile_sections_<CUID> global.
192 /// On the device side it is the populated 7-pointer section-bounds table.
193 /// On the host side it is a placeholder void* shadow stored in
194 /// OffloadProfShadow, registered later by makeRegisterGlobalsFn (non-RDC)
195 /// or createOffloadingEntries (RDC) so the runtime can locate the
196 /// device-side table by name.
197 void emitOffloadProfilingSections();
198
199public:
200 CGNVCUDARuntime(CodeGenModule &CGM);
201
202 llvm::GlobalValue *getKernelHandle(llvm::Function *F, GlobalDecl GD) override;
203 llvm::Function *getKernelStub(llvm::GlobalValue *Handle) override {
204 auto Loc = KernelStubs.find(Handle);
205 assert(Loc != KernelStubs.end());
206 return Loc->second;
207 }
208 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
209 void handleVarRegistration(const VarDecl *VD,
210 llvm::GlobalVariable &Var) override;
211 void
212 internalizeDeviceSideVar(const VarDecl *D,
213 llvm::GlobalValue::LinkageTypes &Linkage) override;
214
215 llvm::Function *finalizeModule() override;
216};
217
218} // end anonymous namespace
219
220std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
221 return (Prefix + FuncName).str();
222}
223std::string
224CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
225 return ("__" + Prefix + FuncName).str();
226}
227
228static std::unique_ptr<MangleContext> InitDeviceMC(CodeGenModule &CGM) {
229 // If the host and device have different C++ ABIs, mark it as the device
230 // mangle context so that the mangling needs to retrieve the additional
231 // device lambda mangling number instead of the regular host one.
232 if (CGM.getContext().getAuxTargetInfo() &&
235 return std::unique_ptr<MangleContext>(
237 *CGM.getContext().getAuxTargetInfo()));
238 }
239
240 return std::unique_ptr<MangleContext>(CGM.getContext().createMangleContext(
242}
243
244CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
245 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
246 TheModule(CGM.getModule()),
247 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
248 DeviceMC(InitDeviceMC(CGM)) {
249 IntTy = CGM.IntTy;
250 SizeTy = CGM.SizeTy;
251 VoidTy = CGM.VoidTy;
252 PtrTy = CGM.DefaultPtrTy;
253
254 if (CGM.getLangOpts().OffloadViaLLVM)
255 Prefix = "llvm";
256 else if (CGM.getLangOpts().HIP)
257 Prefix = "hip";
258 else
259 Prefix = "cuda";
260}
261
262llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
263 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
264 llvm::Type *Params[] = {PtrTy, SizeTy, SizeTy};
265 return CGM.CreateRuntimeFunction(
266 llvm::FunctionType::get(IntTy, Params, false),
267 addPrefixToName("SetupArgument"));
268}
269
270llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
271 if (CGM.getLangOpts().HIP) {
272 // hipError_t hipLaunchByPtr(char *);
273 return CGM.CreateRuntimeFunction(
274 llvm::FunctionType::get(IntTy, PtrTy, false), "hipLaunchByPtr");
275 }
276 // cudaError_t cudaLaunch(char *);
277 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(IntTy, PtrTy, false),
278 "cudaLaunch");
279}
280
281llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
282 return llvm::FunctionType::get(VoidTy, PtrTy, false);
283}
284
285llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
286 return llvm::FunctionType::get(VoidTy, PtrTy, false);
287}
288
289llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
290 llvm::Type *Params[] = {llvm::PointerType::getUnqual(Context), PtrTy, PtrTy,
291 llvm::PointerType::getUnqual(Context)};
292 return llvm::FunctionType::get(VoidTy, Params, false);
293}
294
295std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
296 GlobalDecl GD;
297 // D could be either a kernel or a variable.
298 if (auto *FD = dyn_cast<FunctionDecl>(ND))
299 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
300 else
301 GD = GlobalDecl(ND);
302 std::string DeviceSideName;
303 MangleContext *MC;
304 if (CGM.getLangOpts().CUDAIsDevice)
305 MC = &CGM.getCXXABI().getMangleContext();
306 else
307 MC = DeviceMC.get();
308 if (MC->shouldMangleDeclName(ND)) {
309 SmallString<256> Buffer;
310 llvm::raw_svector_ostream Out(Buffer);
311 MC->mangleName(GD, Out);
312 DeviceSideName = std::string(Out.str());
313 } else
314 DeviceSideName = std::string(ND->getIdentifier()->getName());
315
316 // Make unique name for device side static file-scope variable for HIP.
317 if (CGM.getContext().shouldExternalize(ND) &&
318 CGM.getLangOpts().GPURelocatableDeviceCode) {
319 SmallString<256> Buffer;
320 llvm::raw_svector_ostream Out(Buffer);
321 Out << DeviceSideName;
323 DeviceSideName = std::string(Out.str());
324 }
325 return DeviceSideName;
326}
327
328void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
329 FunctionArgList &Args) {
330 EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
331 if (auto *GV =
332 dyn_cast<llvm::GlobalVariable>(KernelHandles[CGF.CurFn->getName()])) {
333 GV->setLinkage(CGF.CurFn->getLinkage());
334 GV->setInitializer(CGF.CurFn);
335 }
337 CudaFeature::CUDA_USES_NEW_LAUNCH) ||
338 (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI) ||
339 (CGF.getLangOpts().OffloadViaLLVM))
340 emitDeviceStubBodyNew(CGF, Args);
341 else
342 emitDeviceStubBodyLegacy(CGF, Args);
343}
344
345/// CUDA passes the arguments with a level of indirection. For example, a
346/// (void*, short, void*) is passed as {void **, short *, void **} to the launch
347/// function. For the LLVM/offload launch we flatten the arguments into the
348/// struct directly. In addition, we include the size of the arguments, thus
349/// pass {sizeof({void *, short, void *}), ptr to {void *, short, void *},
350/// nullptr}. The last nullptr needs to be initialized to an array of pointers
351/// pointing to the arguments if we want to offload to the host.
352Address CGNVCUDARuntime::prepareKernelArgsLLVMOffload(CodeGenFunction &CGF,
353 FunctionArgList &Args) {
354 SmallVector<llvm::Type *> ArgTypes, KernelLaunchParamsTypes;
355 for (auto &Arg : Args)
356 ArgTypes.push_back(CGF.ConvertTypeForMem(Arg->getType()));
357 llvm::StructType *KernelArgsTy = llvm::StructType::create(ArgTypes);
358
359 auto *Int64Ty = CGF.Builder.getInt64Ty();
360 KernelLaunchParamsTypes.push_back(Int64Ty);
361 KernelLaunchParamsTypes.push_back(PtrTy);
362 KernelLaunchParamsTypes.push_back(PtrTy);
363
364 llvm::StructType *KernelLaunchParamsTy =
365 llvm::StructType::create(KernelLaunchParamsTypes);
366 Address KernelArgs = CGF.CreateTempAllocaWithoutCast(
367 KernelArgsTy, CharUnits::fromQuantity(16), "kernel_args");
368 Address KernelLaunchParams = CGF.CreateTempAllocaWithoutCast(
369 KernelLaunchParamsTy, CharUnits::fromQuantity(16),
370 "kernel_launch_params");
371
372 auto KernelArgsSize = CGM.getDataLayout().getTypeAllocSize(KernelArgsTy);
373 CGF.Builder.CreateStore(llvm::ConstantInt::get(Int64Ty, KernelArgsSize),
374 CGF.Builder.CreateStructGEP(KernelLaunchParams, 0));
375 CGF.Builder.CreateStore(KernelArgs.emitRawPointer(CGF),
376 CGF.Builder.CreateStructGEP(KernelLaunchParams, 1));
377 CGF.Builder.CreateStore(llvm::Constant::getNullValue(PtrTy),
378 CGF.Builder.CreateStructGEP(KernelLaunchParams, 2));
379
380 for (unsigned i = 0; i < Args.size(); ++i) {
381 auto *ArgVal = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[i]));
382 CGF.Builder.CreateStore(ArgVal, CGF.Builder.CreateStructGEP(KernelArgs, i));
383 }
384
385 return KernelLaunchParams;
386}
387
388Address CGNVCUDARuntime::prepareKernelArgs(CodeGenFunction &CGF,
389 FunctionArgList &Args) {
390 // Calculate amount of space we will need for all arguments. If we have no
391 // args, allocate a single pointer so we still have a valid pointer to the
392 // argument array that we can pass to runtime, even if it will be unused.
393 Address KernelArgs = CGF.CreateTempAlloca(
394 PtrTy, LangAS::Default, CharUnits::fromQuantity(16), "kernel_args",
395 llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
396 // Store pointers to the arguments in a locally allocated launch_args.
397 for (unsigned i = 0; i < Args.size(); ++i) {
398 llvm::Value *VarPtr = CGF.GetAddrOfLocalVar(Args[i]).emitRawPointer(CGF);
399 llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, PtrTy);
401 VoidVarPtr, CGF.Builder.CreateConstGEP1_32(
402 PtrTy, KernelArgs.emitRawPointer(CGF), i));
403 }
404 return KernelArgs;
405}
406
407// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
408// array and kernels are launched using cudaLaunchKernel().
409void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
410 FunctionArgList &Args) {
411 // Build the shadow stack entry at the very start of the function.
412 Address KernelArgs = CGF.getLangOpts().OffloadViaLLVM
413 ? prepareKernelArgsLLVMOffload(CGF, Args)
414 : prepareKernelArgs(CGF, Args);
415
416 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
417
418 // Lookup cudaLaunchKernel/hipLaunchKernel function.
419 // HIP kernel launching API name depends on -fgpu-default-stream option. For
420 // the default value 'legacy', it is hipLaunchKernel. For 'per-thread',
421 // it is hipLaunchKernel_spt.
422 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
423 // void **args, size_t sharedMem,
424 // cudaStream_t stream);
425 // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,
426 // dim3 blockDim, void **args,
427 // size_t sharedMem, hipStream_t stream);
428 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
429 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
430 std::string KernelLaunchAPI = "LaunchKernel";
431 if (CGF.getLangOpts().GPUDefaultStream ==
432 LangOptions::GPUDefaultStreamKind::PerThread) {
433 if (CGF.getLangOpts().HIP)
434 KernelLaunchAPI = KernelLaunchAPI + "_spt";
435 else if (CGF.getLangOpts().CUDA)
436 KernelLaunchAPI = KernelLaunchAPI + "_ptsz";
437 }
438 auto LaunchKernelName = addPrefixToName(KernelLaunchAPI);
439 const IdentifierInfo &cudaLaunchKernelII =
440 CGM.getContext().Idents.get(LaunchKernelName);
441 FunctionDecl *cudaLaunchKernelFD = nullptr;
442 for (auto *Result : DC->lookup(&cudaLaunchKernelII)) {
443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
444 cudaLaunchKernelFD = FD;
445 }
446
447 if (cudaLaunchKernelFD == nullptr) {
448 CGM.Error(CGF.CurFuncDecl->getLocation(),
449 "Can't find declaration for " + LaunchKernelName);
450 return;
451 }
452 // Create temporary dim3 grid_dim, block_dim.
453 ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
454 QualType Dim3Ty = GridDimParam->getType();
455 Address GridDim = CGF.CreateMemTempWithoutCast(
456 Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
457 Address BlockDim = CGF.CreateMemTempWithoutCast(
458 Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
459 Address ShmemSize = CGF.CreateTempAlloca(SizeTy, LangAS::Default,
460 CGM.getSizeAlign(), "shmem_size");
461 Address Stream = CGF.CreateTempAlloca(PtrTy, LangAS::Default,
462 CGM.getPointerAlign(), "stream");
463 llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
464 llvm::FunctionType::get(IntTy,
465 {/*gridDim=*/GridDim.getType(),
466 /*blockDim=*/BlockDim.getType(),
467 /*ShmemSize=*/ShmemSize.getType(),
468 /*Stream=*/Stream.getType()},
469 /*isVarArg=*/false),
470 addUnderscoredPrefixToName("PopCallConfiguration"));
471
472 CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn, {GridDim.emitRawPointer(CGF),
473 BlockDim.emitRawPointer(CGF),
474 ShmemSize.emitRawPointer(CGF),
475 Stream.emitRawPointer(CGF)});
476
477 // Emit the call to cudaLaunch
478 llvm::Value *Kernel =
479 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);
480 CallArgList LaunchKernelArgs;
481 LaunchKernelArgs.add(RValue::get(Kernel),
482 cudaLaunchKernelFD->getParamDecl(0)->getType());
483 LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
484 LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
485 LaunchKernelArgs.add(RValue::get(KernelArgs, CGF),
486 cudaLaunchKernelFD->getParamDecl(3)->getType());
487 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
488 cudaLaunchKernelFD->getParamDecl(4)->getType());
489 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
490 cudaLaunchKernelFD->getParamDecl(5)->getType());
491
492 QualType QT = cudaLaunchKernelFD->getType();
493 QualType CQT = QT.getCanonicalType();
494 llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
495 llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
496
497 const CGFunctionInfo &FI =
498 CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
499 llvm::FunctionCallee cudaLaunchKernelFn =
500 CGM.CreateRuntimeFunction(FTy, LaunchKernelName);
501 CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
502 LaunchKernelArgs);
503
504 // To prevent CUDA device stub functions from being merged by ICF in MSVC
505 // environment, create an unique global variable for each kernel and write to
506 // the variable in the device stub.
508 !CGF.getLangOpts().HIP) {
509 llvm::Function *KernelFunction = llvm::cast<llvm::Function>(Kernel);
510 std::string GlobalVarName = (KernelFunction->getName() + ".id").str();
511
512 llvm::GlobalVariable *HandleVar =
513 CGM.getModule().getNamedGlobal(GlobalVarName);
514 if (!HandleVar) {
515 HandleVar = new llvm::GlobalVariable(
516 CGM.getModule(), CGM.Int8Ty,
517 /*Constant=*/false, KernelFunction->getLinkage(),
518 llvm::ConstantInt::get(CGM.Int8Ty, 0), GlobalVarName);
519 HandleVar->setDSOLocal(KernelFunction->isDSOLocal());
520 HandleVar->setVisibility(KernelFunction->getVisibility());
521 if (KernelFunction->hasComdat())
522 HandleVar->setComdat(CGM.getModule().getOrInsertComdat(GlobalVarName));
523 }
524
525 CGF.Builder.CreateAlignedStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
526 HandleVar, CharUnits::One(),
527 /*IsVolatile=*/true);
528 }
529
530 CGF.EmitBranch(EndBlock);
531
532 CGF.EmitBlock(EndBlock);
533}
534
535void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
536 FunctionArgList &Args) {
537 // Emit a call to cudaSetupArgument for each arg in Args.
538 llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
539 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
540 CharUnits Offset = CharUnits::Zero();
541 for (const VarDecl *A : Args) {
542 auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType());
543 Offset = Offset.alignTo(TInfo.Align);
544 llvm::Value *Args[] = {
545 CGF.Builder.CreatePointerCast(
546 CGF.GetAddrOfLocalVar(A).emitRawPointer(CGF), PtrTy),
547 llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()),
548 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
549 };
550 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
551 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
552 llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
553 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
554 CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
555 CGF.EmitBlock(NextBlock);
556 Offset += TInfo.Width;
557 }
558
559 // Emit the call to cudaLaunch
560 llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
561 llvm::Value *Arg =
562 CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn->getName()], PtrTy);
563 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
564 CGF.EmitBranch(EndBlock);
565
566 CGF.EmitBlock(EndBlock);
567}
568
569// Replace the original variable Var with the address loaded from variable
570// ManagedVar populated by HIP runtime.
571static void replaceManagedVar(llvm::GlobalVariable *Var,
572 llvm::GlobalVariable *ManagedVar) {
574 for (auto &&VarUse : Var->uses()) {
575 WorkList.push_back({VarUse.getUser()});
576 }
577 while (!WorkList.empty()) {
578 auto &&WorkItem = WorkList.pop_back_val();
579 auto *U = WorkItem.back();
581 for (auto &&UU : U->uses()) {
582 WorkItem.push_back(UU.getUser());
583 WorkList.push_back(WorkItem);
584 WorkItem.pop_back();
585 }
586 continue;
587 }
588 if (auto *I = dyn_cast<llvm::Instruction>(U)) {
589 llvm::Value *OldV = Var;
590 llvm::Instruction *NewV = new llvm::LoadInst(
591 Var->getType(), ManagedVar, "ld.managed", false,
592 llvm::Align(Var->getAlignment()), I->getIterator());
593 WorkItem.pop_back();
594 // Replace constant expressions directly or indirectly using the managed
595 // variable with instructions.
596 for (auto &&Op : WorkItem) {
597 auto *CE = cast<llvm::ConstantExpr>(Op);
598 auto *NewInst = CE->getAsInstruction();
599 NewInst->insertBefore(*I->getParent(), I->getIterator());
600 NewInst->replaceUsesOfWith(OldV, NewV);
601 OldV = CE;
602 NewV = NewInst;
603 }
604 I->replaceUsesOfWith(OldV, NewV);
605 } else {
606 llvm_unreachable("Invalid use of managed variable");
607 }
608 }
609}
610
611/// Creates a function that sets up state on the host side for CUDA objects that
612/// have a presence on both the host and device sides. Specifically, registers
613/// the host side of kernel functions and device global variables with the CUDA
614/// runtime.
615/// \code
616/// void __cuda_register_globals(void** GpuBinaryHandle) {
617/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
618/// ...
619/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
620/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
621/// ...
622/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
623/// }
624/// \endcode
625llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
626 // No need to register anything
627 if (EmittedKernels.empty() && DeviceVars.empty())
628 return nullptr;
629
630 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
631 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
632 addUnderscoredPrefixToName("_register_globals"), &TheModule);
633 llvm::BasicBlock *EntryBB =
634 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
635 CGBuilderTy Builder(CGM, Context);
636 Builder.SetInsertPoint(EntryBB);
637
638 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
639 // int, uint3*, uint3*, dim3*, dim3*, int*)
640 llvm::Type *RegisterFuncParams[] = {
641 PtrTy, PtrTy, PtrTy, PtrTy, IntTy,
642 PtrTy, PtrTy, PtrTy, PtrTy, llvm::PointerType::getUnqual(Context)};
643 llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
644 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
645 addUnderscoredPrefixToName("RegisterFunction"));
646
647 // Extract GpuBinaryHandle passed as the first argument passed to
648 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
649 // each emitted kernel.
650 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
651 for (auto &&I : EmittedKernels) {
652 llvm::Constant *KernelName =
653 makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));
654 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(PtrTy);
655 llvm::Value *Args[] = {
656 &GpuBinaryHandlePtr,
657 KernelHandles[I.Kernel->getName()],
658 KernelName,
659 KernelName,
660 llvm::ConstantInt::getAllOnesValue(IntTy),
661 NullPtr,
662 NullPtr,
663 NullPtr,
664 NullPtr,
665 llvm::ConstantPointerNull::get(llvm::PointerType::getUnqual(Context))};
666 Builder.CreateCall(RegisterFunc, Args);
667 }
668
669 llvm::Type *VarSizeTy = IntTy;
670 // For HIP or CUDA 9.0+, device variable size is type of `size_t`.
671 if (CGM.getLangOpts().HIP ||
672 ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)
673 VarSizeTy = SizeTy;
674
675 // void __cudaRegisterVar(void **, char *, char *, const char *,
676 // int, int, int, int)
677 llvm::Type *RegisterVarParams[] = {PtrTy, PtrTy, PtrTy, PtrTy,
678 IntTy, VarSizeTy, IntTy, IntTy};
679 llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
680 llvm::FunctionType::get(VoidTy, RegisterVarParams, false),
681 addUnderscoredPrefixToName("RegisterVar"));
682 // void __hipRegisterManagedVar(void **, char *, char *, const char *,
683 // size_t, unsigned)
684 llvm::Type *RegisterManagedVarParams[] = {PtrTy, PtrTy, PtrTy,
685 PtrTy, VarSizeTy, IntTy};
686 llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction(
687 llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false),
688 addUnderscoredPrefixToName("RegisterManagedVar"));
689 // void __cudaRegisterSurface(void **, const struct surfaceReference *,
690 // const void **, const char *, int, int);
691 llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(
692 llvm::FunctionType::get(
693 VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy}, false),
694 addUnderscoredPrefixToName("RegisterSurface"));
695 // void __cudaRegisterTexture(void **, const struct textureReference *,
696 // const void **, const char *, int, int, int)
697 llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(
698 llvm::FunctionType::get(
699 VoidTy, {PtrTy, PtrTy, PtrTy, PtrTy, IntTy, IntTy, IntTy}, false),
700 addUnderscoredPrefixToName("RegisterTexture"));
701 for (auto &&Info : DeviceVars) {
702 llvm::GlobalVariable *Var = Info.Var;
703 assert((!Var->isDeclaration() || Info.Flags.isManaged()) &&
704 "External variables should not show up here, except HIP managed "
705 "variables");
706 llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
707 switch (Info.Flags.getKind()) {
708 case DeviceVarFlags::Variable: {
709 uint64_t VarSize =
710 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
711 if (Info.Flags.isManaged()) {
712 assert(Var->getName().ends_with(".managed") &&
713 "HIP managed variables not transformed");
714 auto *ManagedVar = CGM.getModule().getNamedGlobal(
715 Var->getName().drop_back(StringRef(".managed").size()));
716 llvm::Value *Args[] = {
717 &GpuBinaryHandlePtr,
718 ManagedVar,
719 Var,
720 VarName,
721 llvm::ConstantInt::get(VarSizeTy, VarSize),
722 llvm::ConstantInt::get(IntTy, Var->getAlignment())};
723 if (!Var->isDeclaration())
724 Builder.CreateCall(RegisterManagedVar, Args);
725 } else {
726 llvm::Value *Args[] = {
727 &GpuBinaryHandlePtr,
728 Var,
729 VarName,
730 VarName,
731 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),
732 llvm::ConstantInt::get(VarSizeTy, VarSize),
733 llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),
734 llvm::ConstantInt::get(IntTy, 0)};
735 Builder.CreateCall(RegisterVar, Args);
736 }
737 break;
738 }
739 case DeviceVarFlags::Surface:
740 Builder.CreateCall(
741 RegisterSurf,
742 {&GpuBinaryHandlePtr, Var, VarName, VarName,
743 llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
744 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
745 break;
746 case DeviceVarFlags::Texture:
747 Builder.CreateCall(
748 RegisterTex,
749 {&GpuBinaryHandlePtr, Var, VarName, VarName,
750 llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
751 llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),
752 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
753 break;
754 }
755 }
756
757 // Register the per-TU offload-profiling shadow so the host runtime can
758 // locate the matching device-side __llvm_profile_sections_<CUID>. We
759 // emit both __hipRegisterVar (so the HIP runtime can map the host
760 // shadow to the device symbol) and
761 // __llvm_profile_offload_register_shadow_variable (so the profile
762 // runtime adds the shadow to its drain list).
763 if (OffloadProfShadow) {
764 llvm::Constant *Name =
765 makeConstantString(std::string(OffloadProfShadow->getName()));
766 llvm::Constant *IntZero = llvm::ConstantInt::get(IntTy, 0);
767 llvm::Value *RegisterVarArgs[] = {
768 &GpuBinaryHandlePtr,
769 OffloadProfShadow,
770 Name,
771 Name,
772 IntZero,
773 llvm::ConstantInt::get(VarSizeTy,
774 CGM.getDataLayout().getPointerSize(/*AS=*/0)),
775 IntZero,
776 IntZero};
777 Builder.CreateCall(RegisterVar, RegisterVarArgs);
778
779 llvm::FunctionCallee RegisterShadow = CGM.CreateRuntimeFunction(
780 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
781 "__llvm_profile_offload_register_shadow_variable");
782 Builder.CreateCall(RegisterShadow, {OffloadProfShadow});
783 }
784
785 if (!OffloadProfSectionShadows.empty()) {
786 llvm::FunctionCallee RegisterSectionShadow = CGM.CreateRuntimeFunction(
787 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
788 "__llvm_profile_offload_register_section_shadow_variable");
789 llvm::Constant *IntZero = llvm::ConstantInt::get(IntTy, 0);
790 for (const auto &Info : OffloadProfSectionShadows) {
791 llvm::Constant *Name = makeConstantString(Info.DeviceName);
792 llvm::Value *RegisterVarArgs[] = {
793 &GpuBinaryHandlePtr,
794 Info.Shadow,
795 Name,
796 Name,
797 IntZero,
798 llvm::ConstantInt::get(VarSizeTy,
799 CGM.getDataLayout().getPointerSize(/*AS=*/0)),
800 IntZero,
801 IntZero};
802 Builder.CreateCall(RegisterVar, RegisterVarArgs);
803 Builder.CreateCall(RegisterSectionShadow, {Info.Shadow});
804 }
805 }
806
807 Builder.CreateRetVoid();
808 return RegisterKernelsFunc;
809}
810
811/// Creates a global constructor function for the module:
812///
813/// For CUDA:
814/// \code
815/// void __cuda_module_ctor() {
816/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
817/// __cuda_register_globals(Handle);
818/// }
819/// \endcode
820///
821/// For HIP:
822/// \code
823/// void __hip_module_ctor() {
824/// if (__hip_gpubin_handle == 0) {
825/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);
826/// __hip_register_globals(__hip_gpubin_handle);
827/// }
828/// }
829/// \endcode
830llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
831 bool IsHIP = CGM.getLangOpts().HIP;
832 bool IsCUDA = CGM.getLangOpts().CUDA;
833 // No need to generate ctors/dtors if there is no GPU binary.
834 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
835 if (CudaGpuBinaryFileName.empty() && !IsHIP)
836 return nullptr;
837 if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&
838 DeviceVars.empty())
839 return nullptr;
840
841 // void __{cuda|hip}_register_globals(void* handle);
842 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
843 // We always need a function to pass in as callback. Create a dummy
844 // implementation if we don't need to register anything.
845 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
846 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
847
848 // void ** __{cuda|hip}RegisterFatBinary(void *);
849 llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
850 llvm::FunctionType::get(PtrTy, PtrTy, false),
851 addUnderscoredPrefixToName("RegisterFatBinary"));
852 // struct { int magic, int version, void * gpu_binary, void * dont_care };
853 llvm::StructType *FatbinWrapperTy =
854 llvm::StructType::get(IntTy, IntTy, PtrTy, PtrTy);
855
856 // Register GPU binary with the CUDA runtime, store returned handle in a
857 // global variable and save a reference in GpuBinaryHandle to be cleaned up
858 // in destructor on exit. Then associate all known kernels with the GPU binary
859 // handle so CUDA runtime can figure out what to call on the GPU side.
860 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
861 if (!CudaGpuBinaryFileName.empty()) {
862 auto VFS = CGM.getFileSystem();
863 auto CudaGpuBinaryOrErr =
864 VFS->getBufferForFile(CudaGpuBinaryFileName, -1, false);
865 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
866 CGM.getDiags().Report(diag::err_cannot_open_file)
867 << CudaGpuBinaryFileName << EC.message();
868 return nullptr;
869 }
870 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
871 }
872
873 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
874 llvm::FunctionType::get(VoidTy, false),
875 llvm::GlobalValue::InternalLinkage,
876 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
877 llvm::BasicBlock *CtorEntryBB =
878 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
879 CGBuilderTy CtorBuilder(CGM, Context);
880
881 CtorBuilder.SetInsertPoint(CtorEntryBB);
882
883 const char *FatbinConstantName;
884 const char *FatbinSectionName;
885 const char *ModuleIDSectionName;
886 StringRef ModuleIDPrefix;
887 llvm::Constant *FatBinStr;
888 unsigned FatMagic;
889 if (IsHIP) {
890 // On macOS (Mach-O), section names must be in "segment,section" format.
891 FatbinConstantName =
892 CGM.getTriple().isMacOSX() ? "__HIP,__hip_fatbin" : ".hip_fatbin";
893 FatbinSectionName =
894 CGM.getTriple().isMacOSX() ? "__HIP,__fatbin" : ".hipFatBinSegment";
895
896 ModuleIDSectionName =
897 CGM.getTriple().isMacOSX() ? "__HIP,__module_id" : "__hip_module_id";
898 ModuleIDPrefix = "__hip_";
899
900 if (CudaGpuBinary) {
901 // If fatbin is available from early finalization, create a string
902 // literal containing the fat binary loaded from the given file.
903 const unsigned HIPCodeObjectAlign = 4096;
904 FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",
905 FatbinConstantName, HIPCodeObjectAlign);
906 } else {
907 // If fatbin is not available, create an external symbol
908 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
909 // to contain the fat binary but will be populated somewhere else,
910 // e.g. by lld through link script.
911 FatBinStr = new llvm::GlobalVariable(
912 CGM.getModule(), CGM.Int8Ty,
913 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
914 "__hip_fatbin" + (CGM.getLangOpts().CUID.empty()
915 ? ""
916 : "_" + CGM.getContext().getCUIDHash()),
917 nullptr, llvm::GlobalVariable::NotThreadLocal);
918 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
919 }
920
921 FatMagic = HIPFatMagic;
922 } else {
923 if (RelocatableDeviceCode)
924 FatbinConstantName = CGM.getTriple().isMacOSX()
925 ? "__NV_CUDA,__nv_relfatbin"
926 : "__nv_relfatbin";
927 else
928 FatbinConstantName =
929 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
930 // NVIDIA's cuobjdump looks for fatbins in this section.
931 FatbinSectionName =
932 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
933
934 ModuleIDSectionName = CGM.getTriple().isMacOSX()
935 ? "__NV_CUDA,__nv_module_id"
936 : "__nv_module_id";
937 ModuleIDPrefix = "__nv_";
938
939 // For CUDA, create a string literal containing the fat binary loaded from
940 // the given file.
941 FatBinStr = makeConstantArray(std::string(CudaGpuBinary->getBuffer()), "",
942 FatbinConstantName, 8);
943 FatMagic = CudaFatMagic;
944 }
945
946 // Create initialized wrapper structure that points to the loaded GPU binary
947 ConstantInitBuilder Builder(CGM);
948 auto Values = Builder.beginStruct(FatbinWrapperTy);
949 // Fatbin wrapper magic.
950 Values.addInt(IntTy, FatMagic);
951 // Fatbin version.
952 Values.addInt(IntTy, 1);
953 // Data.
954 Values.add(FatBinStr);
955 // Unused in fatbin v1.
956 Values.add(llvm::ConstantPointerNull::get(PtrTy));
957 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
958 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
959 /*constant*/ true);
960 FatbinWrapper->setSection(FatbinSectionName);
962
963 // There is only one HIP fat binary per linked module, however there are
964 // multiple constructor functions. Make sure the fat binary is registered
965 // only once. The constructor functions are executed by the dynamic loader
966 // before the program gains control. The dynamic loader cannot execute the
967 // constructor functions concurrently since doing that would not guarantee
968 // thread safety of the loaded program. Therefore we can assume sequential
969 // execution of constructor functions here.
970 if (IsHIP) {
971 auto Linkage = RelocatableDeviceCode ? llvm::GlobalValue::ExternalLinkage
972 : llvm::GlobalValue::InternalLinkage;
973 llvm::BasicBlock *IfBlock =
974 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
975 llvm::BasicBlock *ExitBlock =
976 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
977 // The name, size, and initialization pattern of this variable is part
978 // of HIP ABI.
979 GpuBinaryHandle = new llvm::GlobalVariable(
980 TheModule, PtrTy, /*isConstant=*/false, Linkage,
981 /*Initializer=*/
982 !RelocatableDeviceCode ? llvm::ConstantPointerNull::get(PtrTy)
983 : nullptr,
984 "__hip_gpubin_handle" + (CGM.getLangOpts().CUID.empty()
985 ? ""
986 : "_" + CGM.getContext().getCUIDHash()));
987 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
988 // Prevent the weak symbol in different shared libraries being merged.
989 if (Linkage != llvm::GlobalValue::InternalLinkage)
990 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
991 Address GpuBinaryAddr(
992 GpuBinaryHandle, PtrTy,
993 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
994 {
995 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
996 llvm::Constant *Zero =
997 llvm::Constant::getNullValue(HandleValue->getType());
998 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
999 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
1000 }
1001 {
1002 CtorBuilder.SetInsertPoint(IfBlock);
1003 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
1004 llvm::CallInst *RegisterFatbinCall =
1005 CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);
1006 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
1007 CtorBuilder.CreateBr(ExitBlock);
1008 }
1009 {
1010 CtorBuilder.SetInsertPoint(ExitBlock);
1011 // Call __hip_register_globals(GpuBinaryHandle);
1012 if (RegisterGlobalsFunc) {
1013 auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
1014 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
1015 }
1016 }
1017 } else if (!RelocatableDeviceCode) {
1018 // Register binary with CUDA runtime. This is substantially different in
1019 // default mode vs. separate compilation!
1020 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
1021 llvm::CallInst *RegisterFatbinCall =
1022 CtorBuilder.CreateCall(RegisterFatbinFunc, FatbinWrapper);
1023 GpuBinaryHandle = new llvm::GlobalVariable(
1024 TheModule, PtrTy, false, llvm::GlobalValue::InternalLinkage,
1025 llvm::ConstantPointerNull::get(PtrTy), "__cuda_gpubin_handle");
1026 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
1027 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
1028 CGM.getPointerAlign());
1029
1030 // Call __cuda_register_globals(GpuBinaryHandle);
1031 if (RegisterGlobalsFunc)
1032 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
1033
1034 // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
1036 CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
1037 // void __cudaRegisterFatBinaryEnd(void **);
1038 llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
1039 llvm::FunctionType::get(VoidTy, PtrTy, false),
1040 "__cudaRegisterFatBinaryEnd");
1041 CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
1042 }
1043 } else {
1044 // Generate a unique module ID.
1045 SmallString<64> ModuleID;
1046 llvm::raw_svector_ostream OS(ModuleID);
1047 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
1048 llvm::Constant *ModuleIDConstant = makeConstantArray(
1049 std::string(ModuleID), "", ModuleIDSectionName, 32, /*AddNull=*/true);
1050
1051 // Create an alias for the FatbinWrapper that nvcc will look for.
1052 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
1053 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
1054
1055 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
1056 // void *, void (*)(void **))
1057 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
1058 RegisterLinkedBinaryName += ModuleID;
1059 llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
1060 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
1061
1062 assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
1063 llvm::Value *Args[] = {RegisterGlobalsFunc, FatbinWrapper, ModuleIDConstant,
1064 makeDummyFunction(getCallbackFnTy())};
1065 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
1066 }
1067
1068 // Create destructor and register it with atexit() the way NVCC does it. Doing
1069 // it during regular destructor phase worked in CUDA before 9.2 but results in
1070 // double-free in 9.2.
1071 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
1072 // extern "C" int atexit(void (*f)(void));
1073 llvm::FunctionType *AtExitTy =
1074 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
1075 llvm::FunctionCallee AtExitFunc =
1076 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
1077 /*Local=*/true);
1078 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
1079 }
1080
1081 CtorBuilder.CreateRetVoid();
1082 return ModuleCtorFunc;
1083}
1084
1085/// Creates a global destructor function that unregisters the GPU code blob
1086/// registered by constructor.
1087///
1088/// For CUDA:
1089/// \code
1090/// void __cuda_module_dtor() {
1091/// __cudaUnregisterFatBinary(Handle);
1092/// }
1093/// \endcode
1094///
1095/// For HIP:
1096/// \code
1097/// void __hip_module_dtor() {
1098/// if (__hip_gpubin_handle) {
1099/// __hipUnregisterFatBinary(__hip_gpubin_handle);
1100/// __hip_gpubin_handle = 0;
1101/// }
1102/// }
1103/// \endcode
1104llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
1105 // No need for destructor if we don't have a handle to unregister.
1106 if (!GpuBinaryHandle)
1107 return nullptr;
1108
1109 // void __cudaUnregisterFatBinary(void ** handle);
1110 llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
1111 llvm::FunctionType::get(VoidTy, PtrTy, false),
1112 addUnderscoredPrefixToName("UnregisterFatBinary"));
1113
1114 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
1115 llvm::FunctionType::get(VoidTy, false),
1116 llvm::GlobalValue::InternalLinkage,
1117 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
1118
1119 llvm::BasicBlock *DtorEntryBB =
1120 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
1121 CGBuilderTy DtorBuilder(CGM, Context);
1122 DtorBuilder.SetInsertPoint(DtorEntryBB);
1123
1124 Address GpuBinaryAddr(
1125 GpuBinaryHandle, GpuBinaryHandle->getValueType(),
1126 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
1127 auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
1128 // There is only one HIP fat binary per linked module, however there are
1129 // multiple destructor functions. Make sure the fat binary is unregistered
1130 // only once.
1131 if (CGM.getLangOpts().HIP) {
1132 llvm::BasicBlock *IfBlock =
1133 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
1134 llvm::BasicBlock *ExitBlock =
1135 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
1136 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
1137 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
1138 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
1139
1140 DtorBuilder.SetInsertPoint(IfBlock);
1141 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
1142 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
1143 DtorBuilder.CreateBr(ExitBlock);
1144
1145 DtorBuilder.SetInsertPoint(ExitBlock);
1146 } else {
1147 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
1148 }
1149 DtorBuilder.CreateRetVoid();
1150 return ModuleDtorFunc;
1151}
1152
1154 return new CGNVCUDARuntime(CGM);
1155}
1156
1157void CGNVCUDARuntime::internalizeDeviceSideVar(
1158 const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) {
1159 // For -fno-gpu-rdc, host-side shadows of external declarations of device-side
1160 // global variables become internal definitions. These have to be internal in
1161 // order to prevent name conflicts with global host variables with the same
1162 // name in a different TUs.
1163 //
1164 // For -fgpu-rdc, the shadow variables should not be internalized because
1165 // they may be accessed by different TU.
1166 if (CGM.getLangOpts().GPURelocatableDeviceCode)
1167 return;
1168
1169 // __shared__ variables are odd. Shadows do get created, but
1170 // they are not registered with the CUDA runtime, so they
1171 // can't really be used to access their device-side
1172 // counterparts. It's not clear yet whether it's nvcc's bug or
1173 // a feature, but we've got to do the same for compatibility.
1174 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
1175 D->hasAttr<CUDASharedAttr>() ||
1178 Linkage = llvm::GlobalValue::InternalLinkage;
1179 }
1180}
1181
1182void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D,
1183 llvm::GlobalVariable &GV) {
1184 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
1185 // Shadow variables and their properties must be registered with CUDA
1186 // runtime. Skip Extern global variables, which will be registered in
1187 // the TU where they are defined.
1188 //
1189 // Don't register a C++17 inline variable. The local symbol can be
1190 // discarded and referencing a discarded local symbol from outside the
1191 // comdat (__cuda_register_globals) is disallowed by the ELF spec.
1192 //
1193 // HIP managed variables need to be always recorded in device and host
1194 // compilations for transformation.
1195 //
1196 // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are
1197 // added to llvm.compiler-used, therefore they are safe to be registered.
1198 if ((!D->hasExternalStorage() && !D->isInline()) ||
1199 CGM.getContext().CUDADeviceVarODRUsedByHost.contains(D) ||
1200 D->hasAttr<HIPManagedAttr>()) {
1201 registerDeviceVar(D, GV, !D->hasDefinition(),
1202 D->hasAttr<CUDAConstantAttr>());
1203 }
1204 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
1206 // Builtin surfaces and textures and their template arguments are
1207 // also registered with CUDA runtime.
1210 const TemplateArgumentList &Args = TD->getTemplateArgs();
1211 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
1212 assert(Args.size() == 2 &&
1213 "Unexpected number of template arguments of CUDA device "
1214 "builtin surface type.");
1215 auto SurfType = Args[1].getAsIntegral();
1216 if (!D->hasExternalStorage())
1217 registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue());
1218 } else {
1219 assert(Args.size() == 3 &&
1220 "Unexpected number of template arguments of CUDA device "
1221 "builtin texture type.");
1222 auto TexType = Args[1].getAsIntegral();
1223 auto Normalized = Args[2].getAsIntegral();
1224 if (!D->hasExternalStorage())
1225 registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(),
1226 Normalized.getZExtValue());
1227 }
1228 }
1229}
1230
1231// Transform managed variables to pointers to managed variables in device code.
1232// Each use of the original managed variable is replaced by a load from the
1233// transformed managed variable. The transformed managed variable contains
1234// the address of managed memory which will be allocated by the runtime.
1235void CGNVCUDARuntime::transformManagedVars() {
1236 for (auto &&Info : DeviceVars) {
1237 llvm::GlobalVariable *Var = Info.Var;
1238 if (Info.Flags.getKind() == DeviceVarFlags::Variable &&
1239 Info.Flags.isManaged()) {
1240 auto *ManagedVar = new llvm::GlobalVariable(
1241 CGM.getModule(), Var->getType(),
1242 /*isConstant=*/false, Var->getLinkage(),
1243 /*Init=*/Var->isDeclaration()
1244 ? nullptr
1245 : llvm::ConstantPointerNull::get(Var->getType()),
1246 /*Name=*/"", /*InsertBefore=*/nullptr,
1247 llvm::GlobalVariable::NotThreadLocal,
1248 CGM.getContext().getTargetAddressSpace(CGM.getLangOpts().CUDAIsDevice
1249 ? LangAS::cuda_device
1250 : LangAS::Default));
1251 ManagedVar->setDSOLocal(Var->isDSOLocal());
1252 ManagedVar->setVisibility(Var->getVisibility());
1253 ManagedVar->setExternallyInitialized(true);
1254 replaceManagedVar(Var, ManagedVar);
1255 ManagedVar->takeName(Var);
1256 Var->setName(Twine(ManagedVar->getName()) + ".managed");
1257 // Keep managed variables even if they are not used in device code since
1258 // they need to be allocated by the runtime.
1259 if (CGM.getLangOpts().CUDAIsDevice && !Var->isDeclaration()) {
1260 assert(!ManagedVar->isDeclaration());
1261 CGM.addCompilerUsedGlobal(Var);
1262 CGM.addCompilerUsedGlobal(ManagedVar);
1263 }
1264 }
1265 }
1266}
1267
1268// Creates offloading entries for all the kernels and globals that must be
1269// registered. The linker will provide a pointer to this section so we can
1270// register the symbols with the linked device image.
1271void CGNVCUDARuntime::createOffloadingEntries() {
1272 llvm::object::OffloadKind Kind = CGM.getLangOpts().HIP
1273 ? llvm::object::OffloadKind::OFK_HIP
1274 : llvm::object::OffloadKind::OFK_Cuda;
1275 // For now, just spoof this as OpenMP because that's the runtime it uses.
1276 if (CGM.getLangOpts().OffloadViaLLVM)
1277 Kind = llvm::object::OffloadKind::OFK_OpenMP;
1278
1279 llvm::Module &M = CGM.getModule();
1280 for (KernelInfo &I : EmittedKernels)
1281 llvm::offloading::emitOffloadingEntry(
1282 M, Kind, KernelHandles[I.Kernel->getName()],
1283 getDeviceSideName(cast<NamedDecl>(I.D)), /*Flags=*/0, /*Data=*/0,
1284 llvm::offloading::OffloadGlobalEntry);
1285
1286 for (VarInfo &I : DeviceVars) {
1287 uint64_t VarSize =
1288 CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
1289 int32_t Flags =
1290 (I.Flags.isExtern()
1291 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalExtern)
1292 : 0) |
1293 (I.Flags.isConstant()
1294 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalConstant)
1295 : 0) |
1296 (I.Flags.isNormalized()
1297 ? static_cast<int32_t>(llvm::offloading::OffloadGlobalNormalized)
1298 : 0);
1299 if (I.Flags.getKind() == DeviceVarFlags::Variable) {
1300 if (I.Flags.isManaged()) {
1301 assert(I.Var->getName().ends_with(".managed") &&
1302 "HIP managed variables not transformed");
1303
1304 auto *ManagedVar = M.getNamedGlobal(
1305 I.Var->getName().drop_back(StringRef(".managed").size()));
1306 llvm::offloading::emitOffloadingEntry(
1307 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1308 llvm::offloading::OffloadGlobalManagedEntry | Flags,
1309 /*Data=*/I.Var->getAlignment(), ManagedVar);
1310 } else {
1311 llvm::offloading::emitOffloadingEntry(
1312 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1313 llvm::offloading::OffloadGlobalEntry | Flags,
1314 /*Data=*/0);
1315 }
1316 } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
1317 llvm::offloading::emitOffloadingEntry(
1318 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1319 llvm::offloading::OffloadGlobalSurfaceEntry | Flags,
1320 I.Flags.getSurfTexType());
1321 } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
1322 llvm::offloading::emitOffloadingEntry(
1323 M, Kind, I.Var, getDeviceSideName(I.D), VarSize,
1324 llvm::offloading::OffloadGlobalTextureEntry | Flags,
1325 I.Flags.getSurfTexType());
1326 }
1327 }
1328
1329 // Register the per-TU offload-profiling shadow. The offloading entry
1330 // makes the linker-wrapper emit the host __hipRegisterVar call in the
1331 // combined ctor. Separately emit a per-TU ctor that registers the
1332 // shadow with the profile runtime's drain list.
1333 if (OffloadProfShadow) {
1334 llvm::offloading::emitOffloadingEntry(
1335 M, Kind, OffloadProfShadow, OffloadProfShadow->getName(),
1336 CGM.getDataLayout().getPointerSize(/*AS=*/0),
1337 llvm::offloading::OffloadGlobalEntry, /*Data=*/0);
1338
1339 llvm::LLVMContext &Ctx = M.getContext();
1340 auto *PtrTy = llvm::PointerType::getUnqual(Ctx);
1341 llvm::FunctionCallee RegisterShadow = CGM.CreateRuntimeFunction(
1342 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
1343 "__llvm_profile_offload_register_shadow_variable");
1344 llvm::FunctionCallee RegisterSectionShadow = CGM.CreateRuntimeFunction(
1345 llvm::FunctionType::get(VoidTy, {PtrTy}, false),
1346 "__llvm_profile_offload_register_section_shadow_variable");
1347 auto *CtorFn = llvm::Function::Create(
1348 llvm::FunctionType::get(VoidTy, false),
1349 llvm::GlobalValue::InternalLinkage,
1350 "__llvm_profile_register_shadow." + CGM.getContext().getCUIDHash(), &M);
1351 auto *Entry = llvm::BasicBlock::Create(Ctx, "entry", CtorFn);
1352 llvm::IRBuilder<> B(Entry);
1353 B.CreateCall(RegisterShadow, {OffloadProfShadow});
1354 for (const auto &Info : OffloadProfSectionShadows) {
1355 llvm::offloading::emitOffloadingEntry(
1356 M, Kind, Info.Shadow, Info.DeviceName,
1357 CGM.getDataLayout().getPointerSize(/*AS=*/0),
1358 llvm::offloading::OffloadGlobalEntry, /*Data=*/0);
1359 B.CreateCall(RegisterSectionShadow, {Info.Shadow});
1360 }
1361 B.CreateRetVoid();
1362 llvm::appendToGlobalCtors(M, CtorFn, /*Priority=*/65535);
1363 }
1364}
1365
1366// For HIP host+device compiles with PGO enabled, emit the per-TU global
1367// __llvm_profile_sections_<CUID>. Device side: a 7-pointer struct holding
1368// section start/stop bounds for the names/counters/data sections plus the
1369// raw-version variable. Host side: an opaque void* shadow whose only
1370// purpose is to give the host-runtime a registered symbol name to look up
1371// via hipGetSymbolAddress; the actual device-side data lives in the
1372// matching device-side global.
1373void CGNVCUDARuntime::emitOffloadProfilingSections() {
1374 if (!CGM.getLangOpts().HIP)
1375 return;
1376 if (!CGM.getCodeGenOpts().hasProfileInstr())
1377 return;
1378
1379 StringRef CUIDHash = CGM.getContext().getCUIDHash();
1380 if (CUIDHash.empty())
1381 return;
1382
1383 llvm::Module &M = CGM.getModule();
1384 llvm::LLVMContext &Ctx = M.getContext();
1385 std::string Name = ("__llvm_profile_sections_" + CUIDHash).str();
1386
1387 // If the global already exists (e.g. another TU was merged in), don't
1388 // duplicate it.
1389 if (M.getNamedValue(Name))
1390 return;
1391
1392 if (CGM.getLangOpts().CUDAIsDevice) {
1393 // Device side: emit only the per-TU names postfix marker. The sections
1394 // struct is emitted later by the InstrProfiling pass, which emits it only
1395 // when the TU has profile data, avoiding dangling section references.
1396 unsigned GlobalAS = M.getDataLayout().getDefaultGlobalsAddressSpace();
1397 std::string NamesVarPostfixVarName =
1398 std::string(llvm::getInstrProfNamesVarPostfixVarName());
1399 if (!M.getNamedValue(NamesVarPostfixVarName)) {
1400 auto *NamesVarPostfix = llvm::ConstantDataArray::getString(
1401 Ctx, (llvm::Twine("_") + CUIDHash).str(), true);
1402 auto *NamesGV = new llvm::GlobalVariable(
1403 M, NamesVarPostfix->getType(), /*isConstant=*/true,
1404 llvm::GlobalValue::PrivateLinkage, NamesVarPostfix,
1405 NamesVarPostfixVarName,
1406 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1407 GlobalAS);
1408 CGM.addCompilerUsedGlobal(NamesGV);
1409 }
1410 return;
1411 }
1412
1413 // Host side: emit an opaque void* shadow. Layout doesn't matter — the
1414 // runtime locates it by name via hipGetSymbolAddress and treats it as
1415 // the address of the device-side struct. Registration with the HIP
1416 // runtime is added by makeRegisterGlobalsFn (non-RDC) or
1417 // createOffloadingEntries (RDC).
1418 auto *PtrTy = llvm::PointerType::getUnqual(Ctx);
1419 OffloadProfShadow = new llvm::GlobalVariable(
1420 M, PtrTy, /*isConstant=*/false, llvm::GlobalValue::ExternalLinkage,
1421 llvm::ConstantPointerNull::get(PtrTy), Name);
1422 CGM.addCompilerUsedGlobal(OffloadProfShadow);
1423
1424 auto AddSectionShadow = [&](StringRef Kind, const Twine &DeviceName) {
1425 std::string ShadowName =
1426 (Twine("__llvm_profile_shadow_") + Kind + "_" + CUIDHash + "_" +
1427 Twine(OffloadProfSectionShadows.size()))
1428 .str();
1429 auto *Shadow = new llvm::GlobalVariable(
1430 M, PtrTy, /*isConstant=*/false, llvm::GlobalValue::ExternalLinkage,
1431 llvm::ConstantPointerNull::get(PtrTy), ShadowName);
1432 CGM.addCompilerUsedGlobal(Shadow);
1433 OffloadProfSectionShadows.push_back({Shadow, DeviceName.str()});
1434 };
1435
1436 // Keep this order in sync with the runtime: data, counters, then names.
1437 for (auto &&I : EmittedKernels) {
1438 std::string KernelName = getDeviceSideName(cast<NamedDecl>(I.D));
1439 AddSectionShadow("data", Twine("__profd_") + KernelName);
1440 AddSectionShadow("cnts", Twine("__profc_") + KernelName);
1441 AddSectionShadow("names",
1442 Twine(llvm::getInstrProfNamesVarName()) + "_" + CUIDHash);
1443 }
1444}
1445
1446// Returns module constructor to be added.
1447llvm::Function *CGNVCUDARuntime::finalizeModule() {
1448 transformManagedVars();
1449 emitOffloadProfilingSections();
1450 if (CGM.getLangOpts().CUDAIsDevice) {
1451 // Mark ODR-used device variables as compiler used to prevent it from being
1452 // eliminated by optimization. This is necessary for device variables
1453 // ODR-used by host functions. Sema correctly marks them as ODR-used no
1454 // matter whether they are ODR-used by device or host functions.
1455 //
1456 // We do not need to do this if the variable has used attribute since it
1457 // has already been added.
1458 //
1459 // Static device variables have been externalized at this point, therefore
1460 // variables with LLVM private or internal linkage need not be added.
1461 for (auto &&Info : DeviceVars) {
1462 auto Kind = Info.Flags.getKind();
1463 if (!Info.Var->isDeclaration() &&
1464 !llvm::GlobalValue::isLocalLinkage(Info.Var->getLinkage()) &&
1465 (Kind == DeviceVarFlags::Variable ||
1466 Kind == DeviceVarFlags::Surface ||
1467 Kind == DeviceVarFlags::Texture) &&
1468 Info.D->isUsed() && !Info.D->hasAttr<UsedAttr>()) {
1469 CGM.addCompilerUsedGlobal(Info.Var);
1470 }
1471 }
1472 return nullptr;
1473 }
1474 if (CGM.getLangOpts().OffloadViaLLVM ||
1475 (CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode))
1476 createOffloadingEntries();
1477 else
1478 return makeModuleCtorFunction();
1479
1480 return nullptr;
1481}
1482
1483llvm::GlobalValue *CGNVCUDARuntime::getKernelHandle(llvm::Function *F,
1484 GlobalDecl GD) {
1485 auto Loc = KernelHandles.find(F->getName());
1486 if (Loc != KernelHandles.end()) {
1487 auto OldHandle = Loc->second;
1488 if (KernelStubs[OldHandle] == F)
1489 return OldHandle;
1490
1491 // We've found the function name, but F itself has changed, so we need to
1492 // update the references.
1493 if (CGM.getLangOpts().HIP) {
1494 // For HIP compilation the handle itself does not change, so we only need
1495 // to update the Stub value.
1496 KernelStubs[OldHandle] = F;
1497 return OldHandle;
1498 }
1499 // For non-HIP compilation, erase the old Stub and fall-through to creating
1500 // new entries.
1501 KernelStubs.erase(OldHandle);
1502 }
1503
1504 if (!CGM.getLangOpts().HIP) {
1505 KernelHandles[F->getName()] = F;
1506 KernelStubs[F] = F;
1507 return F;
1508 }
1509
1510 auto *Var = new llvm::GlobalVariable(
1511 TheModule, F->getType(), /*isConstant=*/true, F->getLinkage(),
1512 /*Initializer=*/nullptr,
1513 CGM.getMangledName(
1514 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel)));
1515 Var->setAlignment(CGM.getPointerAlign().getAsAlign());
1516 Var->setDSOLocal(F->isDSOLocal());
1517 Var->setVisibility(F->getVisibility());
1518 auto *FD = cast<FunctionDecl>(GD.getDecl());
1519 auto *FT = FD->getPrimaryTemplate();
1520 if (!FT || FT->isThisDeclarationADefinition())
1521 CGM.maybeSetTrivialComdat(*FD, *Var);
1522 KernelHandles[F->getName()] = Var;
1523 KernelStubs[Var] = F;
1524 return Var;
1525}
static std::unique_ptr< MangleContext > InitDeviceMC(CodeGenModule &CGM)
Definition CGCUDANV.cpp:228
static void replaceManagedVar(llvm::GlobalVariable *Var, llvm::GlobalVariable *ManagedVar)
Definition CGCUDANV.cpp:571
Result
Implement __builtin_bit_cast and related operations.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
StringRef getCUIDHash() const
IdentifierTable & Idents
Definition ASTContext.h:802
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:922
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
TypeInfoChars getTypeInfoInChars(const Type *T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
unsigned getTargetAddressSpace(LangAS AS) const
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
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 ...
Definition CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
bool hasProfileInstr() const
Check if any form of instrumentation is on.
std::string CudaGpuBinaryFileName
Name of file passed with -fcuda-include-gpubinary option to forward to CUDA runtime back-end for inco...
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition CGBuilder.h:153
llvm::StoreInst * CreateDefaultAlignedStore(llvm::Value *Val, llvm::Value *Addr, bool IsVolatile=false)
Definition CGBuilder.h:161
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:138
void add(RValue rvalue, QualType type)
Definition CGCall.h:303
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5411
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:159
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5567
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:231
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:108
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:663
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:643
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
SanitizerMetadata * getSanitizerMetadata()
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeFunctionDeclaration(const GlobalDecl GD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition CGCall.cpp:531
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2824
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
Definition GlobalDecl.h:203
const Decl * getDecl() const
Definition GlobalDecl.h:106
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
std::string CUID
The user provided compilation unit ID, if non-empty.
GPUDefaultStreamKind GPUDefaultStream
The default stream kind used for HIP kernel launching.
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:127
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:190
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
QualType getCanonicalType() const
Definition TypeBase.h:8499
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
const llvm::VersionTuple & getSDKVersion() const
unsigned size() const
Retrieve the number of template arguments in this template argument list.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition Decl.h:151
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5474
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5483
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1573
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1238
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
@ VFS
Remove unused -ivfsoverlay arguments.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
CudaVersion ToCudaVersion(llvm::VersionTuple)
Definition Cuda.cpp:72
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:172
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Type
The name was classified as a type.
Definition Sema.h:564
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 int32_t
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64