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/Decl.h"
19 #include "clang/Basic/Cuda.h"
20 #include "clang/CodeGen/CodeGenABITypes.h"
21 #include "clang/CodeGen/ConstantInitBuilder.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/ReplaceConstant.h"
26 #include "llvm/Support/Format.h"
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 namespace {
32 constexpr unsigned CudaFatMagic = 0x466243b1;
33 constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
34 
35 class CGNVCUDARuntime : public CGCUDARuntime {
36 
37 private:
38   llvm::IntegerType *IntTy, *SizeTy;
39   llvm::Type *VoidTy;
40   llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
41 
42   /// Convenience reference to LLVM Context
43   llvm::LLVMContext &Context;
44   /// Convenience reference to the current module
45   llvm::Module &TheModule;
46   /// Keeps track of kernel launch stubs and handles emitted in this module
47   struct KernelInfo {
48     llvm::Function *Kernel; // stub function to help launch kernel
49     const Decl *D;
50   };
51   llvm::SmallVector<KernelInfo, 16> EmittedKernels;
52   // Map a device stub function to a symbol for identifying kernel in host code.
53   // For CUDA, the symbol for identifying the kernel is the same as the device
54   // stub function. For HIP, they are different.
55   llvm::DenseMap<llvm::Function *, llvm::GlobalValue *> KernelHandles;
56   // Map a kernel handle to the kernel stub.
57   llvm::DenseMap<llvm::GlobalValue *, llvm::Function *> KernelStubs;
58   struct VarInfo {
59     llvm::GlobalVariable *Var;
60     const VarDecl *D;
61     DeviceVarFlags Flags;
62   };
63   llvm::SmallVector<VarInfo, 16> DeviceVars;
64   /// Keeps track of variable containing handle of GPU binary. Populated by
65   /// ModuleCtorFunction() and used to create corresponding cleanup calls in
66   /// ModuleDtorFunction()
67   llvm::GlobalVariable *GpuBinaryHandle = nullptr;
68   /// Whether we generate relocatable device code.
69   bool RelocatableDeviceCode;
70   /// Mangle context for device.
71   std::unique_ptr<MangleContext> DeviceMC;
72 
73   llvm::FunctionCallee getSetupArgumentFn() const;
74   llvm::FunctionCallee getLaunchFn() const;
75 
76   llvm::FunctionType *getRegisterGlobalsFnTy() const;
77   llvm::FunctionType *getCallbackFnTy() const;
78   llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
79   std::string addPrefixToName(StringRef FuncName) const;
80   std::string addUnderscoredPrefixToName(StringRef FuncName) const;
81 
82   /// Creates a function to register all kernel stubs generated in this module.
83   llvm::Function *makeRegisterGlobalsFn();
84 
85   /// Helper function that generates a constant string and returns a pointer to
86   /// the start of the string.  The result of this function can be used anywhere
87   /// where the C code specifies const char*.
88   llvm::Constant *makeConstantString(const std::string &Str,
89                                      const std::string &Name = "",
90                                      const std::string &SectionName = "",
91                                      unsigned Alignment = 0) {
92     llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
93                                llvm::ConstantInt::get(SizeTy, 0)};
94     auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
95     llvm::GlobalVariable *GV =
96         cast<llvm::GlobalVariable>(ConstStr.getPointer());
97     if (!SectionName.empty()) {
98       GV->setSection(SectionName);
99       // Mark the address as used which make sure that this section isn't
100       // merged and we will really have it in the object file.
101       GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
102     }
103     if (Alignment)
104       GV->setAlignment(llvm::Align(Alignment));
105 
106     return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
107                                                 ConstStr.getPointer(), Zeros);
108   }
109 
110   /// Helper function that generates an empty dummy function returning void.
111   llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
112     assert(FnTy->getReturnType()->isVoidTy() &&
113            "Can only generate dummy functions returning void!");
114     llvm::Function *DummyFunc = llvm::Function::Create(
115         FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
116 
117     llvm::BasicBlock *DummyBlock =
118         llvm::BasicBlock::Create(Context, "", DummyFunc);
119     CGBuilderTy FuncBuilder(CGM, Context);
120     FuncBuilder.SetInsertPoint(DummyBlock);
121     FuncBuilder.CreateRetVoid();
122 
123     return DummyFunc;
124   }
125 
126   void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
127   void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
128   std::string getDeviceSideName(const NamedDecl *ND) override;
129 
130   void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
131                          bool Extern, bool Constant) {
132     DeviceVars.push_back({&Var,
133                           VD,
134                           {DeviceVarFlags::Variable, Extern, Constant,
135                            VD->hasAttr<HIPManagedAttr>(),
136                            /*Normalized*/ false, 0}});
137   }
138   void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,
139                           bool Extern, int Type) {
140     DeviceVars.push_back({&Var,
141                           VD,
142                           {DeviceVarFlags::Surface, Extern, /*Constant*/ false,
143                            /*Managed*/ false,
144                            /*Normalized*/ false, Type}});
145   }
146   void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,
147                          bool Extern, int Type, bool Normalized) {
148     DeviceVars.push_back({&Var,
149                           VD,
150                           {DeviceVarFlags::Texture, Extern, /*Constant*/ false,
151                            /*Managed*/ false, Normalized, Type}});
152   }
153 
154   /// Creates module constructor function
155   llvm::Function *makeModuleCtorFunction();
156   /// Creates module destructor function
157   llvm::Function *makeModuleDtorFunction();
158   /// Transform managed variables for device compilation.
159   void transformManagedVars();
160   /// Create offloading entries to register globals in RDC mode.
161   void createOffloadingEntries();
162 
163 public:
164   CGNVCUDARuntime(CodeGenModule &CGM);
165 
166   llvm::GlobalValue *getKernelHandle(llvm::Function *F, GlobalDecl GD) override;
167   llvm::Function *getKernelStub(llvm::GlobalValue *Handle) override {
168     auto Loc = KernelStubs.find(Handle);
169     assert(Loc != KernelStubs.end());
170     return Loc->second;
171   }
172   void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
173   void handleVarRegistration(const VarDecl *VD,
174                              llvm::GlobalVariable &Var) override;
175   void
176   internalizeDeviceSideVar(const VarDecl *D,
177                            llvm::GlobalValue::LinkageTypes &Linkage) override;
178 
179   llvm::Function *finalizeModule() override;
180 };
181 
182 } // end anonymous namespace
183 
184 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
185   if (CGM.getLangOpts().HIP)
186     return ((Twine("hip") + Twine(FuncName)).str());
187   return ((Twine("cuda") + Twine(FuncName)).str());
188 }
189 std::string
190 CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
191   if (CGM.getLangOpts().HIP)
192     return ((Twine("__hip") + Twine(FuncName)).str());
193   return ((Twine("__cuda") + Twine(FuncName)).str());
194 }
195 
196 static std::unique_ptr<MangleContext> InitDeviceMC(CodeGenModule &CGM) {
197   // If the host and device have different C++ ABIs, mark it as the device
198   // mangle context so that the mangling needs to retrieve the additional
199   // device lambda mangling number instead of the regular host one.
200   if (CGM.getContext().getAuxTargetInfo() &&
201       CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() &&
202       CGM.getContext().getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
203     return std::unique_ptr<MangleContext>(
204         CGM.getContext().createDeviceMangleContext(
205             *CGM.getContext().getAuxTargetInfo()));
206   }
207 
208   return std::unique_ptr<MangleContext>(CGM.getContext().createMangleContext(
209       CGM.getContext().getAuxTargetInfo()));
210 }
211 
212 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
213     : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
214       TheModule(CGM.getModule()),
215       RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode ||
216                             CGM.getLangOpts().OffloadingNewDriver),
217       DeviceMC(InitDeviceMC(CGM)) {
218   CodeGen::CodeGenTypes &Types = CGM.getTypes();
219   ASTContext &Ctx = CGM.getContext();
220 
221   IntTy = CGM.IntTy;
222   SizeTy = CGM.SizeTy;
223   VoidTy = CGM.VoidTy;
224 
225   CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
226   VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
227   VoidPtrPtrTy = VoidPtrTy->getPointerTo();
228 }
229 
230 llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
231   // cudaError_t cudaSetupArgument(void *, size_t, size_t)
232   llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
233   return CGM.CreateRuntimeFunction(
234       llvm::FunctionType::get(IntTy, Params, false),
235       addPrefixToName("SetupArgument"));
236 }
237 
238 llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
239   if (CGM.getLangOpts().HIP) {
240     // hipError_t hipLaunchByPtr(char *);
241     return CGM.CreateRuntimeFunction(
242         llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
243   }
244   // cudaError_t cudaLaunch(char *);
245   return CGM.CreateRuntimeFunction(
246       llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
247 }
248 
249 llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
250   return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
251 }
252 
253 llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
254   return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
255 }
256 
257 llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
258   auto *CallbackFnTy = getCallbackFnTy();
259   auto *RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
260   llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
261                           VoidPtrTy, CallbackFnTy->getPointerTo()};
262   return llvm::FunctionType::get(VoidTy, Params, false);
263 }
264 
265 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
266   GlobalDecl GD;
267   // D could be either a kernel or a variable.
268   if (auto *FD = dyn_cast<FunctionDecl>(ND))
269     GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
270   else
271     GD = GlobalDecl(ND);
272   std::string DeviceSideName;
273   MangleContext *MC;
274   if (CGM.getLangOpts().CUDAIsDevice)
275     MC = &CGM.getCXXABI().getMangleContext();
276   else
277     MC = DeviceMC.get();
278   if (MC->shouldMangleDeclName(ND)) {
279     SmallString<256> Buffer;
280     llvm::raw_svector_ostream Out(Buffer);
281     MC->mangleName(GD, Out);
282     DeviceSideName = std::string(Out.str());
283   } else
284     DeviceSideName = std::string(ND->getIdentifier()->getName());
285 
286   // Make unique name for device side static file-scope variable for HIP.
287   if (CGM.getContext().shouldExternalize(ND) &&
288       CGM.getLangOpts().GPURelocatableDeviceCode) {
289     SmallString<256> Buffer;
290     llvm::raw_svector_ostream Out(Buffer);
291     Out << DeviceSideName;
292     CGM.printPostfixForExternalizedDecl(Out, ND);
293     DeviceSideName = std::string(Out.str());
294   }
295   return DeviceSideName;
296 }
297 
298 void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
299                                      FunctionArgList &Args) {
300   EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
301   if (auto *GV = dyn_cast<llvm::GlobalVariable>(KernelHandles[CGF.CurFn])) {
302     GV->setLinkage(CGF.CurFn->getLinkage());
303     GV->setInitializer(CGF.CurFn);
304   }
305   if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
306                          CudaFeature::CUDA_USES_NEW_LAUNCH) ||
307       (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI))
308     emitDeviceStubBodyNew(CGF, Args);
309   else
310     emitDeviceStubBodyLegacy(CGF, Args);
311 }
312 
313 // CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
314 // array and kernels are launched using cudaLaunchKernel().
315 void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
316                                             FunctionArgList &Args) {
317   // Build the shadow stack entry at the very start of the function.
318 
319   // Calculate amount of space we will need for all arguments.  If we have no
320   // args, allocate a single pointer so we still have a valid pointer to the
321   // argument array that we can pass to runtime, even if it will be unused.
322   Address KernelArgs = CGF.CreateTempAlloca(
323       VoidPtrTy, CharUnits::fromQuantity(16), "kernel_args",
324       llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
325   // Store pointers to the arguments in a locally allocated launch_args.
326   for (unsigned i = 0; i < Args.size(); ++i) {
327     llvm::Value* VarPtr = CGF.GetAddrOfLocalVar(Args[i]).getPointer();
328     llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, VoidPtrTy);
329     CGF.Builder.CreateDefaultAlignedStore(
330         VoidVarPtr,
331         CGF.Builder.CreateConstGEP1_32(VoidPtrTy, KernelArgs.getPointer(), i));
332   }
333 
334   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
335 
336   // Lookup cudaLaunchKernel/hipLaunchKernel function.
337   // HIP kernel launching API name depends on -fgpu-default-stream option. For
338   // the default value 'legacy', it is hipLaunchKernel. For 'per-thread',
339   // it is hipLaunchKernel_spt.
340   // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
341   //                              void **args, size_t sharedMem,
342   //                              cudaStream_t stream);
343   // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,
344   //                                  dim3 blockDim, void **args,
345   //                                  size_t sharedMem, hipStream_t stream);
346   TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
347   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
348   std::string KernelLaunchAPI = "LaunchKernel";
349   if (CGF.getLangOpts().HIP && CGF.getLangOpts().GPUDefaultStream ==
350                                    LangOptions::GPUDefaultStreamKind::PerThread)
351     KernelLaunchAPI = KernelLaunchAPI + "_spt";
352   auto LaunchKernelName = addPrefixToName(KernelLaunchAPI);
353   IdentifierInfo &cudaLaunchKernelII =
354       CGM.getContext().Idents.get(LaunchKernelName);
355   FunctionDecl *cudaLaunchKernelFD = nullptr;
356   for (auto *Result : DC->lookup(&cudaLaunchKernelII)) {
357     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
358       cudaLaunchKernelFD = FD;
359   }
360 
361   if (cudaLaunchKernelFD == nullptr) {
362     CGM.Error(CGF.CurFuncDecl->getLocation(),
363               "Can't find declaration for " + LaunchKernelName);
364     return;
365   }
366   // Create temporary dim3 grid_dim, block_dim.
367   ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
368   QualType Dim3Ty = GridDimParam->getType();
369   Address GridDim =
370       CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
371   Address BlockDim =
372       CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
373   Address ShmemSize =
374       CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size");
375   Address Stream =
376       CGF.CreateTempAlloca(VoidPtrTy, CGM.getPointerAlign(), "stream");
377   llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
378       llvm::FunctionType::get(IntTy,
379                               {/*gridDim=*/GridDim.getType(),
380                                /*blockDim=*/BlockDim.getType(),
381                                /*ShmemSize=*/ShmemSize.getType(),
382                                /*Stream=*/Stream.getType()},
383                               /*isVarArg=*/false),
384       addUnderscoredPrefixToName("PopCallConfiguration"));
385 
386   CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn,
387                               {GridDim.getPointer(), BlockDim.getPointer(),
388                                ShmemSize.getPointer(), Stream.getPointer()});
389 
390   // Emit the call to cudaLaunch
391   llvm::Value *Kernel =
392       CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn], VoidPtrTy);
393   CallArgList LaunchKernelArgs;
394   LaunchKernelArgs.add(RValue::get(Kernel),
395                        cudaLaunchKernelFD->getParamDecl(0)->getType());
396   LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
397   LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
398   LaunchKernelArgs.add(RValue::get(KernelArgs.getPointer()),
399                        cudaLaunchKernelFD->getParamDecl(3)->getType());
400   LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
401                        cudaLaunchKernelFD->getParamDecl(4)->getType());
402   LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
403                        cudaLaunchKernelFD->getParamDecl(5)->getType());
404 
405   QualType QT = cudaLaunchKernelFD->getType();
406   QualType CQT = QT.getCanonicalType();
407   llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
408   llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
409 
410   const CGFunctionInfo &FI =
411       CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
412   llvm::FunctionCallee cudaLaunchKernelFn =
413       CGM.CreateRuntimeFunction(FTy, LaunchKernelName);
414   CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
415                LaunchKernelArgs);
416   CGF.EmitBranch(EndBlock);
417 
418   CGF.EmitBlock(EndBlock);
419 }
420 
421 void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
422                                                FunctionArgList &Args) {
423   // Emit a call to cudaSetupArgument for each arg in Args.
424   llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
425   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
426   CharUnits Offset = CharUnits::Zero();
427   for (const VarDecl *A : Args) {
428     auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType());
429     Offset = Offset.alignTo(TInfo.Align);
430     llvm::Value *Args[] = {
431         CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
432                                       VoidPtrTy),
433         llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()),
434         llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
435     };
436     llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
437     llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
438     llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
439     llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
440     CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
441     CGF.EmitBlock(NextBlock);
442     Offset += TInfo.Width;
443   }
444 
445   // Emit the call to cudaLaunch
446   llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
447   llvm::Value *Arg =
448       CGF.Builder.CreatePointerCast(KernelHandles[CGF.CurFn], CharPtrTy);
449   CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
450   CGF.EmitBranch(EndBlock);
451 
452   CGF.EmitBlock(EndBlock);
453 }
454 
455 // Replace the original variable Var with the address loaded from variable
456 // ManagedVar populated by HIP runtime.
457 static void replaceManagedVar(llvm::GlobalVariable *Var,
458                               llvm::GlobalVariable *ManagedVar) {
459   SmallVector<SmallVector<llvm::User *, 8>, 8> WorkList;
460   for (auto &&VarUse : Var->uses()) {
461     WorkList.push_back({VarUse.getUser()});
462   }
463   while (!WorkList.empty()) {
464     auto &&WorkItem = WorkList.pop_back_val();
465     auto *U = WorkItem.back();
466     if (isa<llvm::ConstantExpr>(U)) {
467       for (auto &&UU : U->uses()) {
468         WorkItem.push_back(UU.getUser());
469         WorkList.push_back(WorkItem);
470         WorkItem.pop_back();
471       }
472       continue;
473     }
474     if (auto *I = dyn_cast<llvm::Instruction>(U)) {
475       llvm::Value *OldV = Var;
476       llvm::Instruction *NewV =
477           new llvm::LoadInst(Var->getType(), ManagedVar, "ld.managed", false,
478                              llvm::Align(Var->getAlignment()), I);
479       WorkItem.pop_back();
480       // Replace constant expressions directly or indirectly using the managed
481       // variable with instructions.
482       for (auto &&Op : WorkItem) {
483         auto *CE = cast<llvm::ConstantExpr>(Op);
484         auto *NewInst = CE->getAsInstruction(I);
485         NewInst->replaceUsesOfWith(OldV, NewV);
486         OldV = CE;
487         NewV = NewInst;
488       }
489       I->replaceUsesOfWith(OldV, NewV);
490     } else {
491       llvm_unreachable("Invalid use of managed variable");
492     }
493   }
494 }
495 
496 /// Creates a function that sets up state on the host side for CUDA objects that
497 /// have a presence on both the host and device sides. Specifically, registers
498 /// the host side of kernel functions and device global variables with the CUDA
499 /// runtime.
500 /// \code
501 /// void __cuda_register_globals(void** GpuBinaryHandle) {
502 ///    __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
503 ///    ...
504 ///    __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
505 ///    __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
506 ///    ...
507 ///    __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
508 /// }
509 /// \endcode
510 llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
511   // No need to register anything
512   if (EmittedKernels.empty() && DeviceVars.empty())
513     return nullptr;
514 
515   llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
516       getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
517       addUnderscoredPrefixToName("_register_globals"), &TheModule);
518   llvm::BasicBlock *EntryBB =
519       llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
520   CGBuilderTy Builder(CGM, Context);
521   Builder.SetInsertPoint(EntryBB);
522 
523   // void __cudaRegisterFunction(void **, const char *, char *, const char *,
524   //                             int, uint3*, uint3*, dim3*, dim3*, int*)
525   llvm::Type *RegisterFuncParams[] = {
526       VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
527       VoidPtrTy,    VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
528   llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
529       llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
530       addUnderscoredPrefixToName("RegisterFunction"));
531 
532   // Extract GpuBinaryHandle passed as the first argument passed to
533   // __cuda_register_globals() and generate __cudaRegisterFunction() call for
534   // each emitted kernel.
535   llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
536   for (auto &&I : EmittedKernels) {
537     llvm::Constant *KernelName =
538         makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));
539     llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
540     llvm::Value *Args[] = {
541         &GpuBinaryHandlePtr,
542         Builder.CreateBitCast(KernelHandles[I.Kernel], VoidPtrTy),
543         KernelName,
544         KernelName,
545         llvm::ConstantInt::get(IntTy, -1),
546         NullPtr,
547         NullPtr,
548         NullPtr,
549         NullPtr,
550         llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
551     Builder.CreateCall(RegisterFunc, Args);
552   }
553 
554   llvm::Type *VarSizeTy = IntTy;
555   // For HIP or CUDA 9.0+, device variable size is type of `size_t`.
556   if (CGM.getLangOpts().HIP ||
557       ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)
558     VarSizeTy = SizeTy;
559 
560   // void __cudaRegisterVar(void **, char *, char *, const char *,
561   //                        int, int, int, int)
562   llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
563                                      CharPtrTy,    IntTy,     VarSizeTy,
564                                      IntTy,        IntTy};
565   llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
566       llvm::FunctionType::get(VoidTy, RegisterVarParams, false),
567       addUnderscoredPrefixToName("RegisterVar"));
568   // void __hipRegisterManagedVar(void **, char *, char *, const char *,
569   //                              size_t, unsigned)
570   llvm::Type *RegisterManagedVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
571                                             CharPtrTy,    VarSizeTy, IntTy};
572   llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction(
573       llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false),
574       addUnderscoredPrefixToName("RegisterManagedVar"));
575   // void __cudaRegisterSurface(void **, const struct surfaceReference *,
576   //                            const void **, const char *, int, int);
577   llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(
578       llvm::FunctionType::get(
579           VoidTy, {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy},
580           false),
581       addUnderscoredPrefixToName("RegisterSurface"));
582   // void __cudaRegisterTexture(void **, const struct textureReference *,
583   //                            const void **, const char *, int, int, int)
584   llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(
585       llvm::FunctionType::get(
586           VoidTy,
587           {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy, IntTy},
588           false),
589       addUnderscoredPrefixToName("RegisterTexture"));
590   for (auto &&Info : DeviceVars) {
591     llvm::GlobalVariable *Var = Info.Var;
592     assert((!Var->isDeclaration() || Info.Flags.isManaged()) &&
593            "External variables should not show up here, except HIP managed "
594            "variables");
595     llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
596     switch (Info.Flags.getKind()) {
597     case DeviceVarFlags::Variable: {
598       uint64_t VarSize =
599           CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
600       if (Info.Flags.isManaged()) {
601         auto *ManagedVar = new llvm::GlobalVariable(
602             CGM.getModule(), Var->getType(),
603             /*isConstant=*/false, Var->getLinkage(),
604             /*Init=*/Var->isDeclaration()
605                 ? nullptr
606                 : llvm::ConstantPointerNull::get(Var->getType()),
607             /*Name=*/"", /*InsertBefore=*/nullptr,
608             llvm::GlobalVariable::NotThreadLocal);
609         ManagedVar->setDSOLocal(Var->isDSOLocal());
610         ManagedVar->setVisibility(Var->getVisibility());
611         ManagedVar->setExternallyInitialized(true);
612         ManagedVar->takeName(Var);
613         Var->setName(Twine(ManagedVar->getName() + ".managed"));
614         replaceManagedVar(Var, ManagedVar);
615         llvm::Value *Args[] = {
616             &GpuBinaryHandlePtr,
617             Builder.CreateBitCast(ManagedVar, VoidPtrTy),
618             Builder.CreateBitCast(Var, VoidPtrTy),
619             VarName,
620             llvm::ConstantInt::get(VarSizeTy, VarSize),
621             llvm::ConstantInt::get(IntTy, Var->getAlignment())};
622         if (!Var->isDeclaration())
623           Builder.CreateCall(RegisterManagedVar, Args);
624       } else {
625         llvm::Value *Args[] = {
626             &GpuBinaryHandlePtr,
627             Builder.CreateBitCast(Var, VoidPtrTy),
628             VarName,
629             VarName,
630             llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),
631             llvm::ConstantInt::get(VarSizeTy, VarSize),
632             llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),
633             llvm::ConstantInt::get(IntTy, 0)};
634         Builder.CreateCall(RegisterVar, Args);
635       }
636       break;
637     }
638     case DeviceVarFlags::Surface:
639       Builder.CreateCall(
640           RegisterSurf,
641           {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
642            VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
643            llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
644       break;
645     case DeviceVarFlags::Texture:
646       Builder.CreateCall(
647           RegisterTex,
648           {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
649            VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
650            llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),
651            llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
652       break;
653     }
654   }
655 
656   Builder.CreateRetVoid();
657   return RegisterKernelsFunc;
658 }
659 
660 /// Creates a global constructor function for the module:
661 ///
662 /// For CUDA:
663 /// \code
664 /// void __cuda_module_ctor() {
665 ///     Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
666 ///     __cuda_register_globals(Handle);
667 /// }
668 /// \endcode
669 ///
670 /// For HIP:
671 /// \code
672 /// void __hip_module_ctor() {
673 ///     if (__hip_gpubin_handle == 0) {
674 ///         __hip_gpubin_handle  = __hipRegisterFatBinary(GpuBinaryBlob);
675 ///         __hip_register_globals(__hip_gpubin_handle);
676 ///     }
677 /// }
678 /// \endcode
679 llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
680   bool IsHIP = CGM.getLangOpts().HIP;
681   bool IsCUDA = CGM.getLangOpts().CUDA;
682   // No need to generate ctors/dtors if there is no GPU binary.
683   StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
684   if (CudaGpuBinaryFileName.empty() && !IsHIP)
685     return nullptr;
686   if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&
687       DeviceVars.empty())
688     return nullptr;
689 
690   // void __{cuda|hip}_register_globals(void* handle);
691   llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
692   // We always need a function to pass in as callback. Create a dummy
693   // implementation if we don't need to register anything.
694   if (RelocatableDeviceCode && !RegisterGlobalsFunc)
695     RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
696 
697   // void ** __{cuda|hip}RegisterFatBinary(void *);
698   llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
699       llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
700       addUnderscoredPrefixToName("RegisterFatBinary"));
701   // struct { int magic, int version, void * gpu_binary, void * dont_care };
702   llvm::StructType *FatbinWrapperTy =
703       llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
704 
705   // Register GPU binary with the CUDA runtime, store returned handle in a
706   // global variable and save a reference in GpuBinaryHandle to be cleaned up
707   // in destructor on exit. Then associate all known kernels with the GPU binary
708   // handle so CUDA runtime can figure out what to call on the GPU side.
709   std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
710   if (!CudaGpuBinaryFileName.empty()) {
711     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
712         llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
713     if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
714       CGM.getDiags().Report(diag::err_cannot_open_file)
715           << CudaGpuBinaryFileName << EC.message();
716       return nullptr;
717     }
718     CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
719   }
720 
721   llvm::Function *ModuleCtorFunc = llvm::Function::Create(
722       llvm::FunctionType::get(VoidTy, false),
723       llvm::GlobalValue::InternalLinkage,
724       addUnderscoredPrefixToName("_module_ctor"), &TheModule);
725   llvm::BasicBlock *CtorEntryBB =
726       llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
727   CGBuilderTy CtorBuilder(CGM, Context);
728 
729   CtorBuilder.SetInsertPoint(CtorEntryBB);
730 
731   const char *FatbinConstantName;
732   const char *FatbinSectionName;
733   const char *ModuleIDSectionName;
734   StringRef ModuleIDPrefix;
735   llvm::Constant *FatBinStr;
736   unsigned FatMagic;
737   if (IsHIP) {
738     FatbinConstantName = ".hip_fatbin";
739     FatbinSectionName = ".hipFatBinSegment";
740 
741     ModuleIDSectionName = "__hip_module_id";
742     ModuleIDPrefix = "__hip_";
743 
744     if (CudaGpuBinary) {
745       // If fatbin is available from early finalization, create a string
746       // literal containing the fat binary loaded from the given file.
747       const unsigned HIPCodeObjectAlign = 4096;
748       FatBinStr =
749           makeConstantString(std::string(CudaGpuBinary->getBuffer()), "",
750                              FatbinConstantName, HIPCodeObjectAlign);
751     } else {
752       // If fatbin is not available, create an external symbol
753       // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
754       // to contain the fat binary but will be populated somewhere else,
755       // e.g. by lld through link script.
756       FatBinStr = new llvm::GlobalVariable(
757         CGM.getModule(), CGM.Int8Ty,
758         /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
759         "__hip_fatbin", nullptr,
760         llvm::GlobalVariable::NotThreadLocal);
761       cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
762     }
763 
764     FatMagic = HIPFatMagic;
765   } else {
766     if (RelocatableDeviceCode)
767       FatbinConstantName = CGM.getTriple().isMacOSX()
768                                ? "__NV_CUDA,__nv_relfatbin"
769                                : "__nv_relfatbin";
770     else
771       FatbinConstantName =
772           CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
773     // NVIDIA's cuobjdump looks for fatbins in this section.
774     FatbinSectionName =
775         CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
776 
777     ModuleIDSectionName = CGM.getTriple().isMacOSX()
778                               ? "__NV_CUDA,__nv_module_id"
779                               : "__nv_module_id";
780     ModuleIDPrefix = "__nv_";
781 
782     // For CUDA, create a string literal containing the fat binary loaded from
783     // the given file.
784     FatBinStr = makeConstantString(std::string(CudaGpuBinary->getBuffer()), "",
785                                    FatbinConstantName, 8);
786     FatMagic = CudaFatMagic;
787   }
788 
789   // Create initialized wrapper structure that points to the loaded GPU binary
790   ConstantInitBuilder Builder(CGM);
791   auto Values = Builder.beginStruct(FatbinWrapperTy);
792   // Fatbin wrapper magic.
793   Values.addInt(IntTy, FatMagic);
794   // Fatbin version.
795   Values.addInt(IntTy, 1);
796   // Data.
797   Values.add(FatBinStr);
798   // Unused in fatbin v1.
799   Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
800   llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
801       addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
802       /*constant*/ true);
803   FatbinWrapper->setSection(FatbinSectionName);
804 
805   // There is only one HIP fat binary per linked module, however there are
806   // multiple constructor functions. Make sure the fat binary is registered
807   // only once. The constructor functions are executed by the dynamic loader
808   // before the program gains control. The dynamic loader cannot execute the
809   // constructor functions concurrently since doing that would not guarantee
810   // thread safety of the loaded program. Therefore we can assume sequential
811   // execution of constructor functions here.
812   if (IsHIP) {
813     auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage :
814         llvm::GlobalValue::LinkOnceAnyLinkage;
815     llvm::BasicBlock *IfBlock =
816         llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
817     llvm::BasicBlock *ExitBlock =
818         llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
819     // The name, size, and initialization pattern of this variable is part
820     // of HIP ABI.
821     GpuBinaryHandle = new llvm::GlobalVariable(
822         TheModule, VoidPtrPtrTy, /*isConstant=*/false,
823         Linkage,
824         /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
825         "__hip_gpubin_handle");
826     if (Linkage == llvm::GlobalValue::LinkOnceAnyLinkage)
827       GpuBinaryHandle->setComdat(
828           CGM.getModule().getOrInsertComdat(GpuBinaryHandle->getName()));
829     GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
830     // Prevent the weak symbol in different shared libraries being merged.
831     if (Linkage != llvm::GlobalValue::InternalLinkage)
832       GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
833     Address GpuBinaryAddr(
834         GpuBinaryHandle, VoidPtrPtrTy,
835         CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
836     {
837       auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
838       llvm::Constant *Zero =
839           llvm::Constant::getNullValue(HandleValue->getType());
840       llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
841       CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
842     }
843     {
844       CtorBuilder.SetInsertPoint(IfBlock);
845       // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
846       llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
847           RegisterFatbinFunc,
848           CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
849       CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
850       CtorBuilder.CreateBr(ExitBlock);
851     }
852     {
853       CtorBuilder.SetInsertPoint(ExitBlock);
854       // Call __hip_register_globals(GpuBinaryHandle);
855       if (RegisterGlobalsFunc) {
856         auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
857         CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
858       }
859     }
860   } else if (!RelocatableDeviceCode) {
861     // Register binary with CUDA runtime. This is substantially different in
862     // default mode vs. separate compilation!
863     // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
864     llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
865         RegisterFatbinFunc,
866         CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
867     GpuBinaryHandle = new llvm::GlobalVariable(
868         TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
869         llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
870     GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
871     CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
872                                    CGM.getPointerAlign());
873 
874     // Call __cuda_register_globals(GpuBinaryHandle);
875     if (RegisterGlobalsFunc)
876       CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
877 
878     // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
879     if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
880                            CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
881       // void __cudaRegisterFatBinaryEnd(void **);
882       llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
883           llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
884           "__cudaRegisterFatBinaryEnd");
885       CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
886     }
887   } else {
888     // Generate a unique module ID.
889     SmallString<64> ModuleID;
890     llvm::raw_svector_ostream OS(ModuleID);
891     OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
892     llvm::Constant *ModuleIDConstant = makeConstantString(
893         std::string(ModuleID.str()), "", ModuleIDSectionName, 32);
894 
895     // Create an alias for the FatbinWrapper that nvcc will look for.
896     llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
897                               Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
898 
899     // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
900     // void *, void (*)(void **))
901     SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
902     RegisterLinkedBinaryName += ModuleID;
903     llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
904         getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
905 
906     assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
907     llvm::Value *Args[] = {RegisterGlobalsFunc,
908                            CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
909                            ModuleIDConstant,
910                            makeDummyFunction(getCallbackFnTy())};
911     CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
912   }
913 
914   // Create destructor and register it with atexit() the way NVCC does it. Doing
915   // it during regular destructor phase worked in CUDA before 9.2 but results in
916   // double-free in 9.2.
917   if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
918     // extern "C" int atexit(void (*f)(void));
919     llvm::FunctionType *AtExitTy =
920         llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
921     llvm::FunctionCallee AtExitFunc =
922         CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
923                                   /*Local=*/true);
924     CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
925   }
926 
927   CtorBuilder.CreateRetVoid();
928   return ModuleCtorFunc;
929 }
930 
931 /// Creates a global destructor function that unregisters the GPU code blob
932 /// registered by constructor.
933 ///
934 /// For CUDA:
935 /// \code
936 /// void __cuda_module_dtor() {
937 ///     __cudaUnregisterFatBinary(Handle);
938 /// }
939 /// \endcode
940 ///
941 /// For HIP:
942 /// \code
943 /// void __hip_module_dtor() {
944 ///     if (__hip_gpubin_handle) {
945 ///         __hipUnregisterFatBinary(__hip_gpubin_handle);
946 ///         __hip_gpubin_handle = 0;
947 ///     }
948 /// }
949 /// \endcode
950 llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
951   // No need for destructor if we don't have a handle to unregister.
952   if (!GpuBinaryHandle)
953     return nullptr;
954 
955   // void __cudaUnregisterFatBinary(void ** handle);
956   llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
957       llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
958       addUnderscoredPrefixToName("UnregisterFatBinary"));
959 
960   llvm::Function *ModuleDtorFunc = llvm::Function::Create(
961       llvm::FunctionType::get(VoidTy, false),
962       llvm::GlobalValue::InternalLinkage,
963       addUnderscoredPrefixToName("_module_dtor"), &TheModule);
964 
965   llvm::BasicBlock *DtorEntryBB =
966       llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
967   CGBuilderTy DtorBuilder(CGM, Context);
968   DtorBuilder.SetInsertPoint(DtorEntryBB);
969 
970   Address GpuBinaryAddr(
971       GpuBinaryHandle, GpuBinaryHandle->getValueType(),
972       CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
973   auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
974   // There is only one HIP fat binary per linked module, however there are
975   // multiple destructor functions. Make sure the fat binary is unregistered
976   // only once.
977   if (CGM.getLangOpts().HIP) {
978     llvm::BasicBlock *IfBlock =
979         llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
980     llvm::BasicBlock *ExitBlock =
981         llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
982     llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
983     llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
984     DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
985 
986     DtorBuilder.SetInsertPoint(IfBlock);
987     DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
988     DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
989     DtorBuilder.CreateBr(ExitBlock);
990 
991     DtorBuilder.SetInsertPoint(ExitBlock);
992   } else {
993     DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
994   }
995   DtorBuilder.CreateRetVoid();
996   return ModuleDtorFunc;
997 }
998 
999 CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
1000   return new CGNVCUDARuntime(CGM);
1001 }
1002 
1003 void CGNVCUDARuntime::internalizeDeviceSideVar(
1004     const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) {
1005   // For -fno-gpu-rdc, host-side shadows of external declarations of device-side
1006   // global variables become internal definitions. These have to be internal in
1007   // order to prevent name conflicts with global host variables with the same
1008   // name in a different TUs.
1009   //
1010   // For -fgpu-rdc, the shadow variables should not be internalized because
1011   // they may be accessed by different TU.
1012   if (CGM.getLangOpts().GPURelocatableDeviceCode)
1013     return;
1014 
1015   // __shared__ variables are odd. Shadows do get created, but
1016   // they are not registered with the CUDA runtime, so they
1017   // can't really be used to access their device-side
1018   // counterparts. It's not clear yet whether it's nvcc's bug or
1019   // a feature, but we've got to do the same for compatibility.
1020   if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
1021       D->hasAttr<CUDASharedAttr>() ||
1022       D->getType()->isCUDADeviceBuiltinSurfaceType() ||
1023       D->getType()->isCUDADeviceBuiltinTextureType()) {
1024     Linkage = llvm::GlobalValue::InternalLinkage;
1025   }
1026 }
1027 
1028 void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D,
1029                                             llvm::GlobalVariable &GV) {
1030   if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
1031     // Shadow variables and their properties must be registered with CUDA
1032     // runtime. Skip Extern global variables, which will be registered in
1033     // the TU where they are defined.
1034     //
1035     // Don't register a C++17 inline variable. The local symbol can be
1036     // discarded and referencing a discarded local symbol from outside the
1037     // comdat (__cuda_register_globals) is disallowed by the ELF spec.
1038     //
1039     // HIP managed variables need to be always recorded in device and host
1040     // compilations for transformation.
1041     //
1042     // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are
1043     // added to llvm.compiler-used, therefore they are safe to be registered.
1044     if ((!D->hasExternalStorage() && !D->isInline()) ||
1045         CGM.getContext().CUDADeviceVarODRUsedByHost.contains(D) ||
1046         D->hasAttr<HIPManagedAttr>()) {
1047       registerDeviceVar(D, GV, !D->hasDefinition(),
1048                         D->hasAttr<CUDAConstantAttr>());
1049     }
1050   } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
1051              D->getType()->isCUDADeviceBuiltinTextureType()) {
1052     // Builtin surfaces and textures and their template arguments are
1053     // also registered with CUDA runtime.
1054     const auto *TD = cast<ClassTemplateSpecializationDecl>(
1055         D->getType()->castAs<RecordType>()->getDecl());
1056     const TemplateArgumentList &Args = TD->getTemplateArgs();
1057     if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
1058       assert(Args.size() == 2 &&
1059              "Unexpected number of template arguments of CUDA device "
1060              "builtin surface type.");
1061       auto SurfType = Args[1].getAsIntegral();
1062       if (!D->hasExternalStorage())
1063         registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue());
1064     } else {
1065       assert(Args.size() == 3 &&
1066              "Unexpected number of template arguments of CUDA device "
1067              "builtin texture type.");
1068       auto TexType = Args[1].getAsIntegral();
1069       auto Normalized = Args[2].getAsIntegral();
1070       if (!D->hasExternalStorage())
1071         registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(),
1072                           Normalized.getZExtValue());
1073     }
1074   }
1075 }
1076 
1077 // Transform managed variables to pointers to managed variables in device code.
1078 // Each use of the original managed variable is replaced by a load from the
1079 // transformed managed variable. The transformed managed variable contains
1080 // the address of managed memory which will be allocated by the runtime.
1081 void CGNVCUDARuntime::transformManagedVars() {
1082   for (auto &&Info : DeviceVars) {
1083     llvm::GlobalVariable *Var = Info.Var;
1084     if (Info.Flags.getKind() == DeviceVarFlags::Variable &&
1085         Info.Flags.isManaged()) {
1086       auto *ManagedVar = new llvm::GlobalVariable(
1087           CGM.getModule(), Var->getType(),
1088           /*isConstant=*/false, Var->getLinkage(),
1089           /*Init=*/Var->isDeclaration()
1090               ? nullptr
1091               : llvm::ConstantPointerNull::get(Var->getType()),
1092           /*Name=*/"", /*InsertBefore=*/nullptr,
1093           llvm::GlobalVariable::NotThreadLocal,
1094           CGM.getContext().getTargetAddressSpace(LangAS::cuda_device));
1095       ManagedVar->setDSOLocal(Var->isDSOLocal());
1096       ManagedVar->setVisibility(Var->getVisibility());
1097       ManagedVar->setExternallyInitialized(true);
1098       replaceManagedVar(Var, ManagedVar);
1099       ManagedVar->takeName(Var);
1100       Var->setName(Twine(ManagedVar->getName()) + ".managed");
1101       // Keep managed variables even if they are not used in device code since
1102       // they need to be allocated by the runtime.
1103       if (!Var->isDeclaration()) {
1104         assert(!ManagedVar->isDeclaration());
1105         CGM.addCompilerUsedGlobal(Var);
1106         CGM.addCompilerUsedGlobal(ManagedVar);
1107       }
1108     }
1109   }
1110 }
1111 
1112 // Creates offloading entries for all the kernels and globals that must be
1113 // registered. The linker will provide a pointer to this section so we can
1114 // register the symbols with the linked device image.
1115 void CGNVCUDARuntime::createOffloadingEntries() {
1116   llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
1117   OMPBuilder.initialize();
1118 
1119   StringRef Section = "cuda_offloading_entries";
1120   for (KernelInfo &I : EmittedKernels)
1121     OMPBuilder.emitOffloadingEntry(KernelHandles[I.Kernel],
1122                                    getDeviceSideName(cast<NamedDecl>(I.D)), 0,
1123                                    DeviceVarFlags::OffloadGlobalEntry, Section);
1124 
1125   for (VarInfo &I : DeviceVars) {
1126     uint64_t VarSize =
1127         CGM.getDataLayout().getTypeAllocSize(I.Var->getValueType());
1128     if (I.Flags.getKind() == DeviceVarFlags::Variable) {
1129       OMPBuilder.emitOffloadingEntry(
1130           I.Var, getDeviceSideName(I.D), VarSize,
1131           I.Flags.isManaged() ? DeviceVarFlags::OffloadGlobalManagedEntry
1132                               : DeviceVarFlags::OffloadGlobalEntry,
1133           Section);
1134     } else if (I.Flags.getKind() == DeviceVarFlags::Surface) {
1135       OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
1136                                      DeviceVarFlags::OffloadGlobalSurfaceEntry,
1137                                      Section);
1138     } else if (I.Flags.getKind() == DeviceVarFlags::Texture) {
1139       OMPBuilder.emitOffloadingEntry(I.Var, getDeviceSideName(I.D), VarSize,
1140                                      DeviceVarFlags::OffloadGlobalTextureEntry,
1141                                      Section);
1142     }
1143   }
1144 }
1145 
1146 // Returns module constructor to be added.
1147 llvm::Function *CGNVCUDARuntime::finalizeModule() {
1148   if (CGM.getLangOpts().CUDAIsDevice) {
1149     transformManagedVars();
1150 
1151     // Mark ODR-used device variables as compiler used to prevent it from being
1152     // eliminated by optimization. This is necessary for device variables
1153     // ODR-used by host functions. Sema correctly marks them as ODR-used no
1154     // matter whether they are ODR-used by device or host functions.
1155     //
1156     // We do not need to do this if the variable has used attribute since it
1157     // has already been added.
1158     //
1159     // Static device variables have been externalized at this point, therefore
1160     // variables with LLVM private or internal linkage need not be added.
1161     for (auto &&Info : DeviceVars) {
1162       auto Kind = Info.Flags.getKind();
1163       if (!Info.Var->isDeclaration() &&
1164           !llvm::GlobalValue::isLocalLinkage(Info.Var->getLinkage()) &&
1165           (Kind == DeviceVarFlags::Variable ||
1166            Kind == DeviceVarFlags::Surface ||
1167            Kind == DeviceVarFlags::Texture) &&
1168           Info.D->isUsed() && !Info.D->hasAttr<UsedAttr>()) {
1169         CGM.addCompilerUsedGlobal(Info.Var);
1170       }
1171     }
1172     return nullptr;
1173   }
1174   if (!(CGM.getLangOpts().OffloadingNewDriver && RelocatableDeviceCode))
1175     return makeModuleCtorFunction();
1176 
1177   createOffloadingEntries();
1178   return nullptr;
1179 }
1180 
1181 llvm::GlobalValue *CGNVCUDARuntime::getKernelHandle(llvm::Function *F,
1182                                                     GlobalDecl GD) {
1183   auto Loc = KernelHandles.find(F);
1184   if (Loc != KernelHandles.end())
1185     return Loc->second;
1186 
1187   if (!CGM.getLangOpts().HIP) {
1188     KernelHandles[F] = F;
1189     KernelStubs[F] = F;
1190     return F;
1191   }
1192 
1193   auto *Var = new llvm::GlobalVariable(
1194       TheModule, F->getType(), /*isConstant=*/true, F->getLinkage(),
1195       /*Initializer=*/nullptr,
1196       CGM.getMangledName(
1197           GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel)));
1198   Var->setAlignment(CGM.getPointerAlign().getAsAlign());
1199   Var->setDSOLocal(F->isDSOLocal());
1200   Var->setVisibility(F->getVisibility());
1201   CGM.maybeSetTrivialComdat(*GD.getDecl(), *Var);
1202   KernelHandles[F] = Var;
1203   KernelStubs[Var] = F;
1204   return Var;
1205 }
1206