1*a58f00eaSDimitry Andric //===- OffloadWrapper.cpp ---------------------------------------*- C++ -*-===//
2*a58f00eaSDimitry Andric //
3*a58f00eaSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*a58f00eaSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*a58f00eaSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*a58f00eaSDimitry Andric //
7*a58f00eaSDimitry Andric //===----------------------------------------------------------------------===//
8*a58f00eaSDimitry Andric 
9*a58f00eaSDimitry Andric #include "llvm/Frontend/Offloading/OffloadWrapper.h"
10*a58f00eaSDimitry Andric #include "llvm/ADT/ArrayRef.h"
11*a58f00eaSDimitry Andric #include "llvm/BinaryFormat/Magic.h"
12*a58f00eaSDimitry Andric #include "llvm/Frontend/Offloading/Utility.h"
13*a58f00eaSDimitry Andric #include "llvm/IR/Constants.h"
14*a58f00eaSDimitry Andric #include "llvm/IR/GlobalVariable.h"
15*a58f00eaSDimitry Andric #include "llvm/IR/IRBuilder.h"
16*a58f00eaSDimitry Andric #include "llvm/IR/LLVMContext.h"
17*a58f00eaSDimitry Andric #include "llvm/IR/Module.h"
18*a58f00eaSDimitry Andric #include "llvm/Object/OffloadBinary.h"
19*a58f00eaSDimitry Andric #include "llvm/Support/Error.h"
20*a58f00eaSDimitry Andric #include "llvm/TargetParser/Triple.h"
21*a58f00eaSDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
22*a58f00eaSDimitry Andric 
23*a58f00eaSDimitry Andric using namespace llvm;
24*a58f00eaSDimitry Andric using namespace llvm::offloading;
25*a58f00eaSDimitry Andric 
26*a58f00eaSDimitry Andric namespace {
27*a58f00eaSDimitry Andric /// Magic number that begins the section containing the CUDA fatbinary.
28*a58f00eaSDimitry Andric constexpr unsigned CudaFatMagic = 0x466243b1;
29*a58f00eaSDimitry Andric constexpr unsigned HIPFatMagic = 0x48495046;
30*a58f00eaSDimitry Andric 
getSizeTTy(Module & M)31*a58f00eaSDimitry Andric IntegerType *getSizeTTy(Module &M) {
32*a58f00eaSDimitry Andric   return M.getDataLayout().getIntPtrType(M.getContext());
33*a58f00eaSDimitry Andric }
34*a58f00eaSDimitry Andric 
35*a58f00eaSDimitry Andric // struct __tgt_device_image {
36*a58f00eaSDimitry Andric //   void *ImageStart;
37*a58f00eaSDimitry Andric //   void *ImageEnd;
38*a58f00eaSDimitry Andric //   __tgt_offload_entry *EntriesBegin;
39*a58f00eaSDimitry Andric //   __tgt_offload_entry *EntriesEnd;
40*a58f00eaSDimitry Andric // };
getDeviceImageTy(Module & M)41*a58f00eaSDimitry Andric StructType *getDeviceImageTy(Module &M) {
42*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
43*a58f00eaSDimitry Andric   StructType *ImageTy = StructType::getTypeByName(C, "__tgt_device_image");
44*a58f00eaSDimitry Andric   if (!ImageTy)
45*a58f00eaSDimitry Andric     ImageTy =
46*a58f00eaSDimitry Andric         StructType::create("__tgt_device_image", PointerType::getUnqual(C),
47*a58f00eaSDimitry Andric                            PointerType::getUnqual(C), PointerType::getUnqual(C),
48*a58f00eaSDimitry Andric                            PointerType::getUnqual(C));
49*a58f00eaSDimitry Andric   return ImageTy;
50*a58f00eaSDimitry Andric }
51*a58f00eaSDimitry Andric 
getDeviceImagePtrTy(Module & M)52*a58f00eaSDimitry Andric PointerType *getDeviceImagePtrTy(Module &M) {
53*a58f00eaSDimitry Andric   return PointerType::getUnqual(getDeviceImageTy(M));
54*a58f00eaSDimitry Andric }
55*a58f00eaSDimitry Andric 
56*a58f00eaSDimitry Andric // struct __tgt_bin_desc {
57*a58f00eaSDimitry Andric //   int32_t NumDeviceImages;
58*a58f00eaSDimitry Andric //   __tgt_device_image *DeviceImages;
59*a58f00eaSDimitry Andric //   __tgt_offload_entry *HostEntriesBegin;
60*a58f00eaSDimitry Andric //   __tgt_offload_entry *HostEntriesEnd;
61*a58f00eaSDimitry Andric // };
getBinDescTy(Module & M)62*a58f00eaSDimitry Andric StructType *getBinDescTy(Module &M) {
63*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
64*a58f00eaSDimitry Andric   StructType *DescTy = StructType::getTypeByName(C, "__tgt_bin_desc");
65*a58f00eaSDimitry Andric   if (!DescTy)
66*a58f00eaSDimitry Andric     DescTy = StructType::create(
67*a58f00eaSDimitry Andric         "__tgt_bin_desc", Type::getInt32Ty(C), getDeviceImagePtrTy(M),
68*a58f00eaSDimitry Andric         PointerType::getUnqual(C), PointerType::getUnqual(C));
69*a58f00eaSDimitry Andric   return DescTy;
70*a58f00eaSDimitry Andric }
71*a58f00eaSDimitry Andric 
getBinDescPtrTy(Module & M)72*a58f00eaSDimitry Andric PointerType *getBinDescPtrTy(Module &M) {
73*a58f00eaSDimitry Andric   return PointerType::getUnqual(getBinDescTy(M));
74*a58f00eaSDimitry Andric }
75*a58f00eaSDimitry Andric 
76*a58f00eaSDimitry Andric /// Creates binary descriptor for the given device images. Binary descriptor
77*a58f00eaSDimitry Andric /// is an object that is passed to the offloading runtime at program startup
78*a58f00eaSDimitry Andric /// and it describes all device images available in the executable or shared
79*a58f00eaSDimitry Andric /// library. It is defined as follows
80*a58f00eaSDimitry Andric ///
81*a58f00eaSDimitry Andric /// __attribute__((visibility("hidden")))
82*a58f00eaSDimitry Andric /// extern __tgt_offload_entry *__start_omp_offloading_entries;
83*a58f00eaSDimitry Andric /// __attribute__((visibility("hidden")))
84*a58f00eaSDimitry Andric /// extern __tgt_offload_entry *__stop_omp_offloading_entries;
85*a58f00eaSDimitry Andric ///
86*a58f00eaSDimitry Andric /// static const char Image0[] = { <Bufs.front() contents> };
87*a58f00eaSDimitry Andric ///  ...
88*a58f00eaSDimitry Andric /// static const char ImageN[] = { <Bufs.back() contents> };
89*a58f00eaSDimitry Andric ///
90*a58f00eaSDimitry Andric /// static const __tgt_device_image Images[] = {
91*a58f00eaSDimitry Andric ///   {
92*a58f00eaSDimitry Andric ///     Image0,                            /*ImageStart*/
93*a58f00eaSDimitry Andric ///     Image0 + sizeof(Image0),           /*ImageEnd*/
94*a58f00eaSDimitry Andric ///     __start_omp_offloading_entries,    /*EntriesBegin*/
95*a58f00eaSDimitry Andric ///     __stop_omp_offloading_entries      /*EntriesEnd*/
96*a58f00eaSDimitry Andric ///   },
97*a58f00eaSDimitry Andric ///   ...
98*a58f00eaSDimitry Andric ///   {
99*a58f00eaSDimitry Andric ///     ImageN,                            /*ImageStart*/
100*a58f00eaSDimitry Andric ///     ImageN + sizeof(ImageN),           /*ImageEnd*/
101*a58f00eaSDimitry Andric ///     __start_omp_offloading_entries,    /*EntriesBegin*/
102*a58f00eaSDimitry Andric ///     __stop_omp_offloading_entries      /*EntriesEnd*/
103*a58f00eaSDimitry Andric ///   }
104*a58f00eaSDimitry Andric /// };
105*a58f00eaSDimitry Andric ///
106*a58f00eaSDimitry Andric /// static const __tgt_bin_desc BinDesc = {
107*a58f00eaSDimitry Andric ///   sizeof(Images) / sizeof(Images[0]),  /*NumDeviceImages*/
108*a58f00eaSDimitry Andric ///   Images,                              /*DeviceImages*/
109*a58f00eaSDimitry Andric ///   __start_omp_offloading_entries,      /*HostEntriesBegin*/
110*a58f00eaSDimitry Andric ///   __stop_omp_offloading_entries        /*HostEntriesEnd*/
111*a58f00eaSDimitry Andric /// };
112*a58f00eaSDimitry Andric ///
113*a58f00eaSDimitry Andric /// Global variable that represents BinDesc is returned.
createBinDesc(Module & M,ArrayRef<ArrayRef<char>> Bufs,EntryArrayTy EntryArray,StringRef Suffix)114*a58f00eaSDimitry Andric GlobalVariable *createBinDesc(Module &M, ArrayRef<ArrayRef<char>> Bufs,
115*a58f00eaSDimitry Andric                               EntryArrayTy EntryArray, StringRef Suffix) {
116*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
117*a58f00eaSDimitry Andric   auto [EntriesB, EntriesE] = EntryArray;
118*a58f00eaSDimitry Andric 
119*a58f00eaSDimitry Andric   auto *Zero = ConstantInt::get(getSizeTTy(M), 0u);
120*a58f00eaSDimitry Andric   Constant *ZeroZero[] = {Zero, Zero};
121*a58f00eaSDimitry Andric 
122*a58f00eaSDimitry Andric   // Create initializer for the images array.
123*a58f00eaSDimitry Andric   SmallVector<Constant *, 4u> ImagesInits;
124*a58f00eaSDimitry Andric   ImagesInits.reserve(Bufs.size());
125*a58f00eaSDimitry Andric   for (ArrayRef<char> Buf : Bufs) {
126*a58f00eaSDimitry Andric     // We embed the full offloading entry so the binary utilities can parse it.
127*a58f00eaSDimitry Andric     auto *Data = ConstantDataArray::get(C, Buf);
128*a58f00eaSDimitry Andric     auto *Image = new GlobalVariable(M, Data->getType(), /*isConstant=*/true,
129*a58f00eaSDimitry Andric                                      GlobalVariable::InternalLinkage, Data,
130*a58f00eaSDimitry Andric                                      ".omp_offloading.device_image" + Suffix);
131*a58f00eaSDimitry Andric     Image->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
132*a58f00eaSDimitry Andric     Image->setSection(".llvm.offloading");
133*a58f00eaSDimitry Andric     Image->setAlignment(Align(object::OffloadBinary::getAlignment()));
134*a58f00eaSDimitry Andric 
135*a58f00eaSDimitry Andric     StringRef Binary(Buf.data(), Buf.size());
136*a58f00eaSDimitry Andric     assert(identify_magic(Binary) == file_magic::offload_binary &&
137*a58f00eaSDimitry Andric            "Invalid binary format");
138*a58f00eaSDimitry Andric 
139*a58f00eaSDimitry Andric     // The device image struct contains the pointer to the beginning and end of
140*a58f00eaSDimitry Andric     // the image stored inside of the offload binary. There should only be one
141*a58f00eaSDimitry Andric     // of these for each buffer so we parse it out manually.
142*a58f00eaSDimitry Andric     const auto *Header =
143*a58f00eaSDimitry Andric         reinterpret_cast<const object::OffloadBinary::Header *>(
144*a58f00eaSDimitry Andric             Binary.bytes_begin());
145*a58f00eaSDimitry Andric     const auto *Entry = reinterpret_cast<const object::OffloadBinary::Entry *>(
146*a58f00eaSDimitry Andric         Binary.bytes_begin() + Header->EntryOffset);
147*a58f00eaSDimitry Andric 
148*a58f00eaSDimitry Andric     auto *Begin = ConstantInt::get(getSizeTTy(M), Entry->ImageOffset);
149*a58f00eaSDimitry Andric     auto *Size =
150*a58f00eaSDimitry Andric         ConstantInt::get(getSizeTTy(M), Entry->ImageOffset + Entry->ImageSize);
151*a58f00eaSDimitry Andric     Constant *ZeroBegin[] = {Zero, Begin};
152*a58f00eaSDimitry Andric     Constant *ZeroSize[] = {Zero, Size};
153*a58f00eaSDimitry Andric 
154*a58f00eaSDimitry Andric     auto *ImageB =
155*a58f00eaSDimitry Andric         ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroBegin);
156*a58f00eaSDimitry Andric     auto *ImageE =
157*a58f00eaSDimitry Andric         ConstantExpr::getGetElementPtr(Image->getValueType(), Image, ZeroSize);
158*a58f00eaSDimitry Andric 
159*a58f00eaSDimitry Andric     ImagesInits.push_back(ConstantStruct::get(getDeviceImageTy(M), ImageB,
160*a58f00eaSDimitry Andric                                               ImageE, EntriesB, EntriesE));
161*a58f00eaSDimitry Andric   }
162*a58f00eaSDimitry Andric 
163*a58f00eaSDimitry Andric   // Then create images array.
164*a58f00eaSDimitry Andric   auto *ImagesData = ConstantArray::get(
165*a58f00eaSDimitry Andric       ArrayType::get(getDeviceImageTy(M), ImagesInits.size()), ImagesInits);
166*a58f00eaSDimitry Andric 
167*a58f00eaSDimitry Andric   auto *Images =
168*a58f00eaSDimitry Andric       new GlobalVariable(M, ImagesData->getType(), /*isConstant*/ true,
169*a58f00eaSDimitry Andric                          GlobalValue::InternalLinkage, ImagesData,
170*a58f00eaSDimitry Andric                          ".omp_offloading.device_images" + Suffix);
171*a58f00eaSDimitry Andric   Images->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
172*a58f00eaSDimitry Andric 
173*a58f00eaSDimitry Andric   auto *ImagesB =
174*a58f00eaSDimitry Andric       ConstantExpr::getGetElementPtr(Images->getValueType(), Images, ZeroZero);
175*a58f00eaSDimitry Andric 
176*a58f00eaSDimitry Andric   // And finally create the binary descriptor object.
177*a58f00eaSDimitry Andric   auto *DescInit = ConstantStruct::get(
178*a58f00eaSDimitry Andric       getBinDescTy(M),
179*a58f00eaSDimitry Andric       ConstantInt::get(Type::getInt32Ty(C), ImagesInits.size()), ImagesB,
180*a58f00eaSDimitry Andric       EntriesB, EntriesE);
181*a58f00eaSDimitry Andric 
182*a58f00eaSDimitry Andric   return new GlobalVariable(M, DescInit->getType(), /*isConstant*/ true,
183*a58f00eaSDimitry Andric                             GlobalValue::InternalLinkage, DescInit,
184*a58f00eaSDimitry Andric                             ".omp_offloading.descriptor" + Suffix);
185*a58f00eaSDimitry Andric }
186*a58f00eaSDimitry Andric 
createRegisterFunction(Module & M,GlobalVariable * BinDesc,StringRef Suffix)187*a58f00eaSDimitry Andric void createRegisterFunction(Module &M, GlobalVariable *BinDesc,
188*a58f00eaSDimitry Andric                             StringRef Suffix) {
189*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
190*a58f00eaSDimitry Andric   auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
191*a58f00eaSDimitry Andric   auto *Func = Function::Create(FuncTy, GlobalValue::InternalLinkage,
192*a58f00eaSDimitry Andric                                 ".omp_offloading.descriptor_reg" + Suffix, &M);
193*a58f00eaSDimitry Andric   Func->setSection(".text.startup");
194*a58f00eaSDimitry Andric 
195*a58f00eaSDimitry Andric   // Get __tgt_register_lib function declaration.
196*a58f00eaSDimitry Andric   auto *RegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),
197*a58f00eaSDimitry Andric                                       /*isVarArg*/ false);
198*a58f00eaSDimitry Andric   FunctionCallee RegFuncC =
199*a58f00eaSDimitry Andric       M.getOrInsertFunction("__tgt_register_lib", RegFuncTy);
200*a58f00eaSDimitry Andric 
201*a58f00eaSDimitry Andric   // Construct function body
202*a58f00eaSDimitry Andric   IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
203*a58f00eaSDimitry Andric   Builder.CreateCall(RegFuncC, BinDesc);
204*a58f00eaSDimitry Andric   Builder.CreateRetVoid();
205*a58f00eaSDimitry Andric 
206*a58f00eaSDimitry Andric   // Add this function to constructors.
207*a58f00eaSDimitry Andric   // Set priority to 1 so that __tgt_register_lib is executed AFTER
208*a58f00eaSDimitry Andric   // __tgt_register_requires (we want to know what requirements have been
209*a58f00eaSDimitry Andric   // asked for before we load a libomptarget plugin so that by the time the
210*a58f00eaSDimitry Andric   // plugin is loaded it can report how many devices there are which can
211*a58f00eaSDimitry Andric   // satisfy these requirements).
212*a58f00eaSDimitry Andric   appendToGlobalCtors(M, Func, /*Priority*/ 1);
213*a58f00eaSDimitry Andric }
214*a58f00eaSDimitry Andric 
createUnregisterFunction(Module & M,GlobalVariable * BinDesc,StringRef Suffix)215*a58f00eaSDimitry Andric void createUnregisterFunction(Module &M, GlobalVariable *BinDesc,
216*a58f00eaSDimitry Andric                               StringRef Suffix) {
217*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
218*a58f00eaSDimitry Andric   auto *FuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
219*a58f00eaSDimitry Andric   auto *Func =
220*a58f00eaSDimitry Andric       Function::Create(FuncTy, GlobalValue::InternalLinkage,
221*a58f00eaSDimitry Andric                        ".omp_offloading.descriptor_unreg" + Suffix, &M);
222*a58f00eaSDimitry Andric   Func->setSection(".text.startup");
223*a58f00eaSDimitry Andric 
224*a58f00eaSDimitry Andric   // Get __tgt_unregister_lib function declaration.
225*a58f00eaSDimitry Andric   auto *UnRegFuncTy = FunctionType::get(Type::getVoidTy(C), getBinDescPtrTy(M),
226*a58f00eaSDimitry Andric                                         /*isVarArg*/ false);
227*a58f00eaSDimitry Andric   FunctionCallee UnRegFuncC =
228*a58f00eaSDimitry Andric       M.getOrInsertFunction("__tgt_unregister_lib", UnRegFuncTy);
229*a58f00eaSDimitry Andric 
230*a58f00eaSDimitry Andric   // Construct function body
231*a58f00eaSDimitry Andric   IRBuilder<> Builder(BasicBlock::Create(C, "entry", Func));
232*a58f00eaSDimitry Andric   Builder.CreateCall(UnRegFuncC, BinDesc);
233*a58f00eaSDimitry Andric   Builder.CreateRetVoid();
234*a58f00eaSDimitry Andric 
235*a58f00eaSDimitry Andric   // Add this function to global destructors.
236*a58f00eaSDimitry Andric   // Match priority of __tgt_register_lib
237*a58f00eaSDimitry Andric   appendToGlobalDtors(M, Func, /*Priority*/ 1);
238*a58f00eaSDimitry Andric }
239*a58f00eaSDimitry Andric 
240*a58f00eaSDimitry Andric // struct fatbin_wrapper {
241*a58f00eaSDimitry Andric //  int32_t magic;
242*a58f00eaSDimitry Andric //  int32_t version;
243*a58f00eaSDimitry Andric //  void *image;
244*a58f00eaSDimitry Andric //  void *reserved;
245*a58f00eaSDimitry Andric //};
getFatbinWrapperTy(Module & M)246*a58f00eaSDimitry Andric StructType *getFatbinWrapperTy(Module &M) {
247*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
248*a58f00eaSDimitry Andric   StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
249*a58f00eaSDimitry Andric   if (!FatbinTy)
250*a58f00eaSDimitry Andric     FatbinTy = StructType::create(
251*a58f00eaSDimitry Andric         "fatbin_wrapper", Type::getInt32Ty(C), Type::getInt32Ty(C),
252*a58f00eaSDimitry Andric         PointerType::getUnqual(C), PointerType::getUnqual(C));
253*a58f00eaSDimitry Andric   return FatbinTy;
254*a58f00eaSDimitry Andric }
255*a58f00eaSDimitry Andric 
256*a58f00eaSDimitry Andric /// Embed the image \p Image into the module \p M so it can be found by the
257*a58f00eaSDimitry Andric /// runtime.
createFatbinDesc(Module & M,ArrayRef<char> Image,bool IsHIP,StringRef Suffix)258*a58f00eaSDimitry Andric GlobalVariable *createFatbinDesc(Module &M, ArrayRef<char> Image, bool IsHIP,
259*a58f00eaSDimitry Andric                                  StringRef Suffix) {
260*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
261*a58f00eaSDimitry Andric   llvm::Type *Int8PtrTy = PointerType::getUnqual(C);
262*a58f00eaSDimitry Andric   llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
263*a58f00eaSDimitry Andric 
264*a58f00eaSDimitry Andric   // Create the global string containing the fatbinary.
265*a58f00eaSDimitry Andric   StringRef FatbinConstantSection =
266*a58f00eaSDimitry Andric       IsHIP ? ".hip_fatbin"
267*a58f00eaSDimitry Andric             : (Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin");
268*a58f00eaSDimitry Andric   auto *Data = ConstantDataArray::get(C, Image);
269*a58f00eaSDimitry Andric   auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
270*a58f00eaSDimitry Andric                                     GlobalVariable::InternalLinkage, Data,
271*a58f00eaSDimitry Andric                                     ".fatbin_image" + Suffix);
272*a58f00eaSDimitry Andric   Fatbin->setSection(FatbinConstantSection);
273*a58f00eaSDimitry Andric 
274*a58f00eaSDimitry Andric   // Create the fatbinary wrapper
275*a58f00eaSDimitry Andric   StringRef FatbinWrapperSection = IsHIP               ? ".hipFatBinSegment"
276*a58f00eaSDimitry Andric                                    : Triple.isMacOSX() ? "__NV_CUDA,__fatbin"
277*a58f00eaSDimitry Andric                                                        : ".nvFatBinSegment";
278*a58f00eaSDimitry Andric   Constant *FatbinWrapper[] = {
279*a58f00eaSDimitry Andric       ConstantInt::get(Type::getInt32Ty(C), IsHIP ? HIPFatMagic : CudaFatMagic),
280*a58f00eaSDimitry Andric       ConstantInt::get(Type::getInt32Ty(C), 1),
281*a58f00eaSDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
282*a58f00eaSDimitry Andric       ConstantPointerNull::get(PointerType::getUnqual(C))};
283*a58f00eaSDimitry Andric 
284*a58f00eaSDimitry Andric   Constant *FatbinInitializer =
285*a58f00eaSDimitry Andric       ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
286*a58f00eaSDimitry Andric 
287*a58f00eaSDimitry Andric   auto *FatbinDesc =
288*a58f00eaSDimitry Andric       new GlobalVariable(M, getFatbinWrapperTy(M),
289*a58f00eaSDimitry Andric                          /*isConstant*/ true, GlobalValue::InternalLinkage,
290*a58f00eaSDimitry Andric                          FatbinInitializer, ".fatbin_wrapper" + Suffix);
291*a58f00eaSDimitry Andric   FatbinDesc->setSection(FatbinWrapperSection);
292*a58f00eaSDimitry Andric   FatbinDesc->setAlignment(Align(8));
293*a58f00eaSDimitry Andric 
294*a58f00eaSDimitry Andric   return FatbinDesc;
295*a58f00eaSDimitry Andric }
296*a58f00eaSDimitry Andric 
297*a58f00eaSDimitry Andric /// Create the register globals function. We will iterate all of the offloading
298*a58f00eaSDimitry Andric /// entries stored at the begin / end symbols and register them according to
299*a58f00eaSDimitry Andric /// their type. This creates the following function in IR:
300*a58f00eaSDimitry Andric ///
301*a58f00eaSDimitry Andric /// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
302*a58f00eaSDimitry Andric /// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
303*a58f00eaSDimitry Andric ///
304*a58f00eaSDimitry Andric /// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
305*a58f00eaSDimitry Andric ///                                    void *, void *, void *, void *, int *);
306*a58f00eaSDimitry Andric /// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
307*a58f00eaSDimitry Andric ///                               int64_t, int32_t, int32_t);
308*a58f00eaSDimitry Andric ///
309*a58f00eaSDimitry Andric /// void __cudaRegisterTest(void **fatbinHandle) {
310*a58f00eaSDimitry Andric ///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
311*a58f00eaSDimitry Andric ///        entry != &__stop_cuda_offloading_entries; ++entry) {
312*a58f00eaSDimitry Andric ///     if (!entry->size)
313*a58f00eaSDimitry Andric ///       __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
314*a58f00eaSDimitry Andric ///                              entry->name, -1, 0, 0, 0, 0, 0);
315*a58f00eaSDimitry Andric ///     else
316*a58f00eaSDimitry Andric ///       __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,
317*a58f00eaSDimitry Andric ///                         0, entry->size, 0, 0);
318*a58f00eaSDimitry Andric ///   }
319*a58f00eaSDimitry Andric /// }
createRegisterGlobalsFunction(Module & M,bool IsHIP,EntryArrayTy EntryArray,StringRef Suffix,bool EmitSurfacesAndTextures)320*a58f00eaSDimitry Andric Function *createRegisterGlobalsFunction(Module &M, bool IsHIP,
321*a58f00eaSDimitry Andric                                         EntryArrayTy EntryArray,
322*a58f00eaSDimitry Andric                                         StringRef Suffix,
323*a58f00eaSDimitry Andric                                         bool EmitSurfacesAndTextures) {
324*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
325*a58f00eaSDimitry Andric   auto [EntriesB, EntriesE] = EntryArray;
326*a58f00eaSDimitry Andric 
327*a58f00eaSDimitry Andric   // Get the __cudaRegisterFunction function declaration.
328*a58f00eaSDimitry Andric   PointerType *Int8PtrTy = PointerType::get(C, 0);
329*a58f00eaSDimitry Andric   PointerType *Int8PtrPtrTy = PointerType::get(C, 0);
330*a58f00eaSDimitry Andric   PointerType *Int32PtrTy = PointerType::get(C, 0);
331*a58f00eaSDimitry Andric   auto *RegFuncTy = FunctionType::get(
332*a58f00eaSDimitry Andric       Type::getInt32Ty(C),
333*a58f00eaSDimitry Andric       {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
334*a58f00eaSDimitry Andric        Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32PtrTy},
335*a58f00eaSDimitry Andric       /*isVarArg*/ false);
336*a58f00eaSDimitry Andric   FunctionCallee RegFunc = M.getOrInsertFunction(
337*a58f00eaSDimitry Andric       IsHIP ? "__hipRegisterFunction" : "__cudaRegisterFunction", RegFuncTy);
338*a58f00eaSDimitry Andric 
339*a58f00eaSDimitry Andric   // Get the __cudaRegisterVar function declaration.
340*a58f00eaSDimitry Andric   auto *RegVarTy = FunctionType::get(
341*a58f00eaSDimitry Andric       Type::getVoidTy(C),
342*a58f00eaSDimitry Andric       {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
343*a58f00eaSDimitry Andric        getSizeTTy(M), Type::getInt32Ty(C), Type::getInt32Ty(C)},
344*a58f00eaSDimitry Andric       /*isVarArg*/ false);
345*a58f00eaSDimitry Andric   FunctionCallee RegVar = M.getOrInsertFunction(
346*a58f00eaSDimitry Andric       IsHIP ? "__hipRegisterVar" : "__cudaRegisterVar", RegVarTy);
347*a58f00eaSDimitry Andric 
348*a58f00eaSDimitry Andric   // Get the __cudaRegisterSurface function declaration.
349*a58f00eaSDimitry Andric   FunctionType *RegSurfaceTy =
350*a58f00eaSDimitry Andric       FunctionType::get(Type::getVoidTy(C),
351*a58f00eaSDimitry Andric                         {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy,
352*a58f00eaSDimitry Andric                          Type::getInt32Ty(C), Type::getInt32Ty(C)},
353*a58f00eaSDimitry Andric                         /*isVarArg=*/false);
354*a58f00eaSDimitry Andric   FunctionCallee RegSurface = M.getOrInsertFunction(
355*a58f00eaSDimitry Andric       IsHIP ? "__hipRegisterSurface" : "__cudaRegisterSurface", RegSurfaceTy);
356*a58f00eaSDimitry Andric 
357*a58f00eaSDimitry Andric   // Get the __cudaRegisterTexture function declaration.
358*a58f00eaSDimitry Andric   FunctionType *RegTextureTy = FunctionType::get(
359*a58f00eaSDimitry Andric       Type::getVoidTy(C),
360*a58f00eaSDimitry Andric       {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
361*a58f00eaSDimitry Andric        Type::getInt32Ty(C), Type::getInt32Ty(C)},
362*a58f00eaSDimitry Andric       /*isVarArg=*/false);
363*a58f00eaSDimitry Andric   FunctionCallee RegTexture = M.getOrInsertFunction(
364*a58f00eaSDimitry Andric       IsHIP ? "__hipRegisterTexture" : "__cudaRegisterTexture", RegTextureTy);
365*a58f00eaSDimitry Andric 
366*a58f00eaSDimitry Andric   auto *RegGlobalsTy = FunctionType::get(Type::getVoidTy(C), Int8PtrPtrTy,
367*a58f00eaSDimitry Andric                                          /*isVarArg*/ false);
368*a58f00eaSDimitry Andric   auto *RegGlobalsFn =
369*a58f00eaSDimitry Andric       Function::Create(RegGlobalsTy, GlobalValue::InternalLinkage,
370*a58f00eaSDimitry Andric                        IsHIP ? ".hip.globals_reg" : ".cuda.globals_reg", &M);
371*a58f00eaSDimitry Andric   RegGlobalsFn->setSection(".text.startup");
372*a58f00eaSDimitry Andric 
373*a58f00eaSDimitry Andric   // Create the loop to register all the entries.
374*a58f00eaSDimitry Andric   IRBuilder<> Builder(BasicBlock::Create(C, "entry", RegGlobalsFn));
375*a58f00eaSDimitry Andric   auto *EntryBB = BasicBlock::Create(C, "while.entry", RegGlobalsFn);
376*a58f00eaSDimitry Andric   auto *IfThenBB = BasicBlock::Create(C, "if.then", RegGlobalsFn);
377*a58f00eaSDimitry Andric   auto *IfElseBB = BasicBlock::Create(C, "if.else", RegGlobalsFn);
378*a58f00eaSDimitry Andric   auto *SwGlobalBB = BasicBlock::Create(C, "sw.global", RegGlobalsFn);
379*a58f00eaSDimitry Andric   auto *SwManagedBB = BasicBlock::Create(C, "sw.managed", RegGlobalsFn);
380*a58f00eaSDimitry Andric   auto *SwSurfaceBB = BasicBlock::Create(C, "sw.surface", RegGlobalsFn);
381*a58f00eaSDimitry Andric   auto *SwTextureBB = BasicBlock::Create(C, "sw.texture", RegGlobalsFn);
382*a58f00eaSDimitry Andric   auto *IfEndBB = BasicBlock::Create(C, "if.end", RegGlobalsFn);
383*a58f00eaSDimitry Andric   auto *ExitBB = BasicBlock::Create(C, "while.end", RegGlobalsFn);
384*a58f00eaSDimitry Andric 
385*a58f00eaSDimitry Andric   auto *EntryCmp = Builder.CreateICmpNE(EntriesB, EntriesE);
386*a58f00eaSDimitry Andric   Builder.CreateCondBr(EntryCmp, EntryBB, ExitBB);
387*a58f00eaSDimitry Andric   Builder.SetInsertPoint(EntryBB);
388*a58f00eaSDimitry Andric   auto *Entry = Builder.CreatePHI(PointerType::getUnqual(C), 2, "entry");
389*a58f00eaSDimitry Andric   auto *AddrPtr =
390*a58f00eaSDimitry Andric       Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
391*a58f00eaSDimitry Andric                                 {ConstantInt::get(getSizeTTy(M), 0),
392*a58f00eaSDimitry Andric                                  ConstantInt::get(Type::getInt32Ty(C), 0)});
393*a58f00eaSDimitry Andric   auto *Addr = Builder.CreateLoad(Int8PtrTy, AddrPtr, "addr");
394*a58f00eaSDimitry Andric   auto *NamePtr =
395*a58f00eaSDimitry Andric       Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
396*a58f00eaSDimitry Andric                                 {ConstantInt::get(getSizeTTy(M), 0),
397*a58f00eaSDimitry Andric                                  ConstantInt::get(Type::getInt32Ty(C), 1)});
398*a58f00eaSDimitry Andric   auto *Name = Builder.CreateLoad(Int8PtrTy, NamePtr, "name");
399*a58f00eaSDimitry Andric   auto *SizePtr =
400*a58f00eaSDimitry Andric       Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
401*a58f00eaSDimitry Andric                                 {ConstantInt::get(getSizeTTy(M), 0),
402*a58f00eaSDimitry Andric                                  ConstantInt::get(Type::getInt32Ty(C), 2)});
403*a58f00eaSDimitry Andric   auto *Size = Builder.CreateLoad(getSizeTTy(M), SizePtr, "size");
404*a58f00eaSDimitry Andric   auto *FlagsPtr =
405*a58f00eaSDimitry Andric       Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
406*a58f00eaSDimitry Andric                                 {ConstantInt::get(getSizeTTy(M), 0),
407*a58f00eaSDimitry Andric                                  ConstantInt::get(Type::getInt32Ty(C), 3)});
408*a58f00eaSDimitry Andric   auto *Flags = Builder.CreateLoad(Type::getInt32Ty(C), FlagsPtr, "flags");
409*a58f00eaSDimitry Andric   auto *DataPtr =
410*a58f00eaSDimitry Andric       Builder.CreateInBoundsGEP(offloading::getEntryTy(M), Entry,
411*a58f00eaSDimitry Andric                                 {ConstantInt::get(getSizeTTy(M), 0),
412*a58f00eaSDimitry Andric                                  ConstantInt::get(Type::getInt32Ty(C), 4)});
413*a58f00eaSDimitry Andric   auto *Data = Builder.CreateLoad(Type::getInt32Ty(C), DataPtr, "textype");
414*a58f00eaSDimitry Andric   auto *Kind = Builder.CreateAnd(
415*a58f00eaSDimitry Andric       Flags, ConstantInt::get(Type::getInt32Ty(C), 0x7), "type");
416*a58f00eaSDimitry Andric 
417*a58f00eaSDimitry Andric   // Extract the flags stored in the bit-field and convert them to C booleans.
418*a58f00eaSDimitry Andric   auto *ExternBit = Builder.CreateAnd(
419*a58f00eaSDimitry Andric       Flags, ConstantInt::get(Type::getInt32Ty(C),
420*a58f00eaSDimitry Andric                               llvm::offloading::OffloadGlobalExtern));
421*a58f00eaSDimitry Andric   auto *Extern = Builder.CreateLShr(
422*a58f00eaSDimitry Andric       ExternBit, ConstantInt::get(Type::getInt32Ty(C), 3), "extern");
423*a58f00eaSDimitry Andric   auto *ConstantBit = Builder.CreateAnd(
424*a58f00eaSDimitry Andric       Flags, ConstantInt::get(Type::getInt32Ty(C),
425*a58f00eaSDimitry Andric                               llvm::offloading::OffloadGlobalConstant));
426*a58f00eaSDimitry Andric   auto *Const = Builder.CreateLShr(
427*a58f00eaSDimitry Andric       ConstantBit, ConstantInt::get(Type::getInt32Ty(C), 4), "constant");
428*a58f00eaSDimitry Andric   auto *NormalizedBit = Builder.CreateAnd(
429*a58f00eaSDimitry Andric       Flags, ConstantInt::get(Type::getInt32Ty(C),
430*a58f00eaSDimitry Andric                               llvm::offloading::OffloadGlobalNormalized));
431*a58f00eaSDimitry Andric   auto *Normalized = Builder.CreateLShr(
432*a58f00eaSDimitry Andric       NormalizedBit, ConstantInt::get(Type::getInt32Ty(C), 5), "normalized");
433*a58f00eaSDimitry Andric   auto *FnCond =
434*a58f00eaSDimitry Andric       Builder.CreateICmpEQ(Size, ConstantInt::getNullValue(getSizeTTy(M)));
435*a58f00eaSDimitry Andric   Builder.CreateCondBr(FnCond, IfThenBB, IfElseBB);
436*a58f00eaSDimitry Andric 
437*a58f00eaSDimitry Andric   // Create kernel registration code.
438*a58f00eaSDimitry Andric   Builder.SetInsertPoint(IfThenBB);
439*a58f00eaSDimitry Andric   Builder.CreateCall(RegFunc, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
440*a58f00eaSDimitry Andric                                ConstantInt::get(Type::getInt32Ty(C), -1),
441*a58f00eaSDimitry Andric                                ConstantPointerNull::get(Int8PtrTy),
442*a58f00eaSDimitry Andric                                ConstantPointerNull::get(Int8PtrTy),
443*a58f00eaSDimitry Andric                                ConstantPointerNull::get(Int8PtrTy),
444*a58f00eaSDimitry Andric                                ConstantPointerNull::get(Int8PtrTy),
445*a58f00eaSDimitry Andric                                ConstantPointerNull::get(Int32PtrTy)});
446*a58f00eaSDimitry Andric   Builder.CreateBr(IfEndBB);
447*a58f00eaSDimitry Andric   Builder.SetInsertPoint(IfElseBB);
448*a58f00eaSDimitry Andric 
449*a58f00eaSDimitry Andric   auto *Switch = Builder.CreateSwitch(Kind, IfEndBB);
450*a58f00eaSDimitry Andric   // Create global variable registration code.
451*a58f00eaSDimitry Andric   Builder.SetInsertPoint(SwGlobalBB);
452*a58f00eaSDimitry Andric   Builder.CreateCall(RegVar,
453*a58f00eaSDimitry Andric                      {RegGlobalsFn->arg_begin(), Addr, Name, Name, Extern, Size,
454*a58f00eaSDimitry Andric                       Const, ConstantInt::get(Type::getInt32Ty(C), 0)});
455*a58f00eaSDimitry Andric   Builder.CreateBr(IfEndBB);
456*a58f00eaSDimitry Andric   Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalEntry),
457*a58f00eaSDimitry Andric                   SwGlobalBB);
458*a58f00eaSDimitry Andric 
459*a58f00eaSDimitry Andric   // Create managed variable registration code.
460*a58f00eaSDimitry Andric   Builder.SetInsertPoint(SwManagedBB);
461*a58f00eaSDimitry Andric   Builder.CreateBr(IfEndBB);
462*a58f00eaSDimitry Andric   Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalManagedEntry),
463*a58f00eaSDimitry Andric                   SwManagedBB);
464*a58f00eaSDimitry Andric   // Create surface variable registration code.
465*a58f00eaSDimitry Andric   Builder.SetInsertPoint(SwSurfaceBB);
466*a58f00eaSDimitry Andric   if (EmitSurfacesAndTextures)
467*a58f00eaSDimitry Andric     Builder.CreateCall(RegSurface, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
468*a58f00eaSDimitry Andric                                     Data, Extern});
469*a58f00eaSDimitry Andric   Builder.CreateBr(IfEndBB);
470*a58f00eaSDimitry Andric   Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalSurfaceEntry),
471*a58f00eaSDimitry Andric                   SwSurfaceBB);
472*a58f00eaSDimitry Andric 
473*a58f00eaSDimitry Andric   // Create texture variable registration code.
474*a58f00eaSDimitry Andric   Builder.SetInsertPoint(SwTextureBB);
475*a58f00eaSDimitry Andric   if (EmitSurfacesAndTextures)
476*a58f00eaSDimitry Andric     Builder.CreateCall(RegTexture, {RegGlobalsFn->arg_begin(), Addr, Name, Name,
477*a58f00eaSDimitry Andric                                     Data, Normalized, Extern});
478*a58f00eaSDimitry Andric   Builder.CreateBr(IfEndBB);
479*a58f00eaSDimitry Andric   Switch->addCase(Builder.getInt32(llvm::offloading::OffloadGlobalTextureEntry),
480*a58f00eaSDimitry Andric                   SwTextureBB);
481*a58f00eaSDimitry Andric 
482*a58f00eaSDimitry Andric   Builder.SetInsertPoint(IfEndBB);
483*a58f00eaSDimitry Andric   auto *NewEntry = Builder.CreateInBoundsGEP(
484*a58f00eaSDimitry Andric       offloading::getEntryTy(M), Entry, ConstantInt::get(getSizeTTy(M), 1));
485*a58f00eaSDimitry Andric   auto *Cmp = Builder.CreateICmpEQ(
486*a58f00eaSDimitry Andric       NewEntry,
487*a58f00eaSDimitry Andric       ConstantExpr::getInBoundsGetElementPtr(
488*a58f00eaSDimitry Andric           ArrayType::get(offloading::getEntryTy(M), 0), EntriesE,
489*a58f00eaSDimitry Andric           ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),
490*a58f00eaSDimitry Andric                                 ConstantInt::get(getSizeTTy(M), 0)})));
491*a58f00eaSDimitry Andric   Entry->addIncoming(
492*a58f00eaSDimitry Andric       ConstantExpr::getInBoundsGetElementPtr(
493*a58f00eaSDimitry Andric           ArrayType::get(offloading::getEntryTy(M), 0), EntriesB,
494*a58f00eaSDimitry Andric           ArrayRef<Constant *>({ConstantInt::get(getSizeTTy(M), 0),
495*a58f00eaSDimitry Andric                                 ConstantInt::get(getSizeTTy(M), 0)})),
496*a58f00eaSDimitry Andric       &RegGlobalsFn->getEntryBlock());
497*a58f00eaSDimitry Andric   Entry->addIncoming(NewEntry, IfEndBB);
498*a58f00eaSDimitry Andric   Builder.CreateCondBr(Cmp, ExitBB, EntryBB);
499*a58f00eaSDimitry Andric   Builder.SetInsertPoint(ExitBB);
500*a58f00eaSDimitry Andric   Builder.CreateRetVoid();
501*a58f00eaSDimitry Andric 
502*a58f00eaSDimitry Andric   return RegGlobalsFn;
503*a58f00eaSDimitry Andric }
504*a58f00eaSDimitry Andric 
505*a58f00eaSDimitry Andric // Create the constructor and destructor to register the fatbinary with the CUDA
506*a58f00eaSDimitry Andric // runtime.
createRegisterFatbinFunction(Module & M,GlobalVariable * FatbinDesc,bool IsHIP,EntryArrayTy EntryArray,StringRef Suffix,bool EmitSurfacesAndTextures)507*a58f00eaSDimitry Andric void createRegisterFatbinFunction(Module &M, GlobalVariable *FatbinDesc,
508*a58f00eaSDimitry Andric                                   bool IsHIP, EntryArrayTy EntryArray,
509*a58f00eaSDimitry Andric                                   StringRef Suffix,
510*a58f00eaSDimitry Andric                                   bool EmitSurfacesAndTextures) {
511*a58f00eaSDimitry Andric   LLVMContext &C = M.getContext();
512*a58f00eaSDimitry Andric   auto *CtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
513*a58f00eaSDimitry Andric   auto *CtorFunc = Function::Create(
514*a58f00eaSDimitry Andric       CtorFuncTy, GlobalValue::InternalLinkage,
515*a58f00eaSDimitry Andric       (IsHIP ? ".hip.fatbin_reg" : ".cuda.fatbin_reg") + Suffix, &M);
516*a58f00eaSDimitry Andric   CtorFunc->setSection(".text.startup");
517*a58f00eaSDimitry Andric 
518*a58f00eaSDimitry Andric   auto *DtorFuncTy = FunctionType::get(Type::getVoidTy(C), /*isVarArg*/ false);
519*a58f00eaSDimitry Andric   auto *DtorFunc = Function::Create(
520*a58f00eaSDimitry Andric       DtorFuncTy, GlobalValue::InternalLinkage,
521*a58f00eaSDimitry Andric       (IsHIP ? ".hip.fatbin_unreg" : ".cuda.fatbin_unreg") + Suffix, &M);
522*a58f00eaSDimitry Andric   DtorFunc->setSection(".text.startup");
523*a58f00eaSDimitry Andric 
524*a58f00eaSDimitry Andric   auto *PtrTy = PointerType::getUnqual(C);
525*a58f00eaSDimitry Andric 
526*a58f00eaSDimitry Andric   // Get the __cudaRegisterFatBinary function declaration.
527*a58f00eaSDimitry Andric   auto *RegFatTy = FunctionType::get(PtrTy, PtrTy, /*isVarArg=*/false);
528*a58f00eaSDimitry Andric   FunctionCallee RegFatbin = M.getOrInsertFunction(
529*a58f00eaSDimitry Andric       IsHIP ? "__hipRegisterFatBinary" : "__cudaRegisterFatBinary", RegFatTy);
530*a58f00eaSDimitry Andric   // Get the __cudaRegisterFatBinaryEnd function declaration.
531*a58f00eaSDimitry Andric   auto *RegFatEndTy =
532*a58f00eaSDimitry Andric       FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);
533*a58f00eaSDimitry Andric   FunctionCallee RegFatbinEnd =
534*a58f00eaSDimitry Andric       M.getOrInsertFunction("__cudaRegisterFatBinaryEnd", RegFatEndTy);
535*a58f00eaSDimitry Andric   // Get the __cudaUnregisterFatBinary function declaration.
536*a58f00eaSDimitry Andric   auto *UnregFatTy =
537*a58f00eaSDimitry Andric       FunctionType::get(Type::getVoidTy(C), PtrTy, /*isVarArg=*/false);
538*a58f00eaSDimitry Andric   FunctionCallee UnregFatbin = M.getOrInsertFunction(
539*a58f00eaSDimitry Andric       IsHIP ? "__hipUnregisterFatBinary" : "__cudaUnregisterFatBinary",
540*a58f00eaSDimitry Andric       UnregFatTy);
541*a58f00eaSDimitry Andric 
542*a58f00eaSDimitry Andric   auto *AtExitTy =
543*a58f00eaSDimitry Andric       FunctionType::get(Type::getInt32Ty(C), PtrTy, /*isVarArg=*/false);
544*a58f00eaSDimitry Andric   FunctionCallee AtExit = M.getOrInsertFunction("atexit", AtExitTy);
545*a58f00eaSDimitry Andric 
546*a58f00eaSDimitry Andric   auto *BinaryHandleGlobal = new llvm::GlobalVariable(
547*a58f00eaSDimitry Andric       M, PtrTy, false, llvm::GlobalValue::InternalLinkage,
548*a58f00eaSDimitry Andric       llvm::ConstantPointerNull::get(PtrTy),
549*a58f00eaSDimitry Andric       (IsHIP ? ".hip.binary_handle" : ".cuda.binary_handle") + Suffix);
550*a58f00eaSDimitry Andric 
551*a58f00eaSDimitry Andric   // Create the constructor to register this image with the runtime.
552*a58f00eaSDimitry Andric   IRBuilder<> CtorBuilder(BasicBlock::Create(C, "entry", CtorFunc));
553*a58f00eaSDimitry Andric   CallInst *Handle = CtorBuilder.CreateCall(
554*a58f00eaSDimitry Andric       RegFatbin,
555*a58f00eaSDimitry Andric       ConstantExpr::getPointerBitCastOrAddrSpaceCast(FatbinDesc, PtrTy));
556*a58f00eaSDimitry Andric   CtorBuilder.CreateAlignedStore(
557*a58f00eaSDimitry Andric       Handle, BinaryHandleGlobal,
558*a58f00eaSDimitry Andric       Align(M.getDataLayout().getPointerTypeSize(PtrTy)));
559*a58f00eaSDimitry Andric   CtorBuilder.CreateCall(createRegisterGlobalsFunction(M, IsHIP, EntryArray,
560*a58f00eaSDimitry Andric                                                        Suffix,
561*a58f00eaSDimitry Andric                                                        EmitSurfacesAndTextures),
562*a58f00eaSDimitry Andric                          Handle);
563*a58f00eaSDimitry Andric   if (!IsHIP)
564*a58f00eaSDimitry Andric     CtorBuilder.CreateCall(RegFatbinEnd, Handle);
565*a58f00eaSDimitry Andric   CtorBuilder.CreateCall(AtExit, DtorFunc);
566*a58f00eaSDimitry Andric   CtorBuilder.CreateRetVoid();
567*a58f00eaSDimitry Andric 
568*a58f00eaSDimitry Andric   // Create the destructor to unregister the image with the runtime. We cannot
569*a58f00eaSDimitry Andric   // use a standard global destructor after CUDA 9.2 so this must be called by
570*a58f00eaSDimitry Andric   // `atexit()` intead.
571*a58f00eaSDimitry Andric   IRBuilder<> DtorBuilder(BasicBlock::Create(C, "entry", DtorFunc));
572*a58f00eaSDimitry Andric   LoadInst *BinaryHandle = DtorBuilder.CreateAlignedLoad(
573*a58f00eaSDimitry Andric       PtrTy, BinaryHandleGlobal,
574*a58f00eaSDimitry Andric       Align(M.getDataLayout().getPointerTypeSize(PtrTy)));
575*a58f00eaSDimitry Andric   DtorBuilder.CreateCall(UnregFatbin, BinaryHandle);
576*a58f00eaSDimitry Andric   DtorBuilder.CreateRetVoid();
577*a58f00eaSDimitry Andric 
578*a58f00eaSDimitry Andric   // Add this function to constructors.
579*a58f00eaSDimitry Andric   appendToGlobalCtors(M, CtorFunc, /*Priority*/ 1);
580*a58f00eaSDimitry Andric }
581*a58f00eaSDimitry Andric } // namespace
582*a58f00eaSDimitry Andric 
wrapOpenMPBinaries(Module & M,ArrayRef<ArrayRef<char>> Images,EntryArrayTy EntryArray,llvm::StringRef Suffix)583*a58f00eaSDimitry Andric Error offloading::wrapOpenMPBinaries(Module &M, ArrayRef<ArrayRef<char>> Images,
584*a58f00eaSDimitry Andric                                      EntryArrayTy EntryArray,
585*a58f00eaSDimitry Andric                                      llvm::StringRef Suffix) {
586*a58f00eaSDimitry Andric   GlobalVariable *Desc = createBinDesc(M, Images, EntryArray, Suffix);
587*a58f00eaSDimitry Andric   if (!Desc)
588*a58f00eaSDimitry Andric     return createStringError(inconvertibleErrorCode(),
589*a58f00eaSDimitry Andric                              "No binary descriptors created.");
590*a58f00eaSDimitry Andric   createRegisterFunction(M, Desc, Suffix);
591*a58f00eaSDimitry Andric   createUnregisterFunction(M, Desc, Suffix);
592*a58f00eaSDimitry Andric   return Error::success();
593*a58f00eaSDimitry Andric }
594*a58f00eaSDimitry Andric 
wrapCudaBinary(Module & M,ArrayRef<char> Image,EntryArrayTy EntryArray,llvm::StringRef Suffix,bool EmitSurfacesAndTextures)595*a58f00eaSDimitry Andric Error offloading::wrapCudaBinary(Module &M, ArrayRef<char> Image,
596*a58f00eaSDimitry Andric                                  EntryArrayTy EntryArray,
597*a58f00eaSDimitry Andric                                  llvm::StringRef Suffix,
598*a58f00eaSDimitry Andric                                  bool EmitSurfacesAndTextures) {
599*a58f00eaSDimitry Andric   GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/false, Suffix);
600*a58f00eaSDimitry Andric   if (!Desc)
601*a58f00eaSDimitry Andric     return createStringError(inconvertibleErrorCode(),
602*a58f00eaSDimitry Andric                              "No fatbin section created.");
603*a58f00eaSDimitry Andric 
604*a58f00eaSDimitry Andric   createRegisterFatbinFunction(M, Desc, /*IsHip=*/false, EntryArray, Suffix,
605*a58f00eaSDimitry Andric                                EmitSurfacesAndTextures);
606*a58f00eaSDimitry Andric   return Error::success();
607*a58f00eaSDimitry Andric }
608*a58f00eaSDimitry Andric 
wrapHIPBinary(Module & M,ArrayRef<char> Image,EntryArrayTy EntryArray,llvm::StringRef Suffix,bool EmitSurfacesAndTextures)609*a58f00eaSDimitry Andric Error offloading::wrapHIPBinary(Module &M, ArrayRef<char> Image,
610*a58f00eaSDimitry Andric                                 EntryArrayTy EntryArray, llvm::StringRef Suffix,
611*a58f00eaSDimitry Andric                                 bool EmitSurfacesAndTextures) {
612*a58f00eaSDimitry Andric   GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/true, Suffix);
613*a58f00eaSDimitry Andric   if (!Desc)
614*a58f00eaSDimitry Andric     return createStringError(inconvertibleErrorCode(),
615*a58f00eaSDimitry Andric                              "No fatbin section created.");
616*a58f00eaSDimitry Andric 
617*a58f00eaSDimitry Andric   createRegisterFatbinFunction(M, Desc, /*IsHip=*/true, EntryArray, Suffix,
618*a58f00eaSDimitry Andric                                EmitSurfacesAndTextures);
619*a58f00eaSDimitry Andric   return Error::success();
620*a58f00eaSDimitry Andric }
621