1//===- OffloadWrapper.cpp ---------------------------------------*- C++ -*-===//
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#include "llvm/Frontend/Offloading/OffloadWrapper.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/BinaryFormat/Magic.h"
15#include "llvm/Frontend/Offloading/Utility.h"
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/GlobalVariable.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/LLVMContext.h"
21#include "llvm/IR/Module.h"
22#include "llvm/IR/Type.h"
23#include "llvm/Object/OffloadBinary.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/TargetParser/Triple.h"
27#include "llvm/Transforms/Utils/ModuleUtils.h"
28
29#include <utility>
30
31using namespace llvm;
32using namespace llvm::object;
33using namespace llvm::offloading;
34
35namespace {
36/// Magic number that begins the section containing the CUDA fatbinary.
37constexpr unsigned CudaFatMagic = 0x466243b1;
38constexpr unsigned HIPFatMagic = 0x48495046;
39
40IntegerType *getSizeTTy(Module &M) {
41 return M.getDataLayout().getIntPtrType(C&: M.getContext());
42}
43
44/// Returns the appropriate startup section for registration functions.
45/// Mach-O uses "__TEXT,__StaticInit"; ELF/COFF use ".text.startup".
46StringRef getStartupSection(const Triple &T) {
47 return T.isOSBinFormatMachO() ? "__TEXT,__StaticInit" : ".text.startup";
48}
49
50// struct __tgt_device_image {
51// void *ImageStart;
52// void *ImageEnd;
53// __tgt_offload_entry *EntriesBegin;
54// __tgt_offload_entry *EntriesEnd;
55// };
56StructType *getDeviceImageTy(Module &M) {
57 LLVMContext &C = M.getContext();
58 StructType *ImageTy = StructType::getTypeByName(C, Name: "__tgt_device_image");
59 if (!ImageTy)
60 ImageTy =
61 StructType::create(Name: "__tgt_device_image", elt1: PointerType::getUnqual(C),
62 elts: PointerType::getUnqual(C), elts: PointerType::getUnqual(C),
63 elts: PointerType::getUnqual(C));
64 return ImageTy;
65}
66
67PointerType *getDeviceImagePtrTy(Module &M) {
68 return PointerType::getUnqual(C&: M.getContext());
69}
70
71// struct __tgt_bin_desc {
72// int32_t NumDeviceImages;
73// __tgt_device_image *DeviceImages;
74// __tgt_offload_entry *HostEntriesBegin;
75// __tgt_offload_entry *HostEntriesEnd;
76// };
77StructType *getBinDescTy(Module &M) {
78 LLVMContext &C = M.getContext();
79 StructType *DescTy = StructType::getTypeByName(C, Name: "__tgt_bin_desc");
80 if (!DescTy)
81 DescTy = StructType::create(
82 Name: "__tgt_bin_desc", elt1: Type::getInt32Ty(C), elts: getDeviceImagePtrTy(M),
83 elts: PointerType::getUnqual(C), elts: PointerType::getUnqual(C));
84 return DescTy;
85}
86
87PointerType *getBinDescPtrTy(Module &M) {
88 return PointerType::getUnqual(C&: M.getContext());
89}
90
91/// Creates binary descriptor for the given device images. Binary descriptor
92/// is an object that is passed to the offloading runtime at program startup
93/// and it describes all device images available in the executable or shared
94/// library. It is defined as follows
95///
96/// __attribute__((visibility("hidden")))
97/// extern __tgt_offload_entry *__start_llvm_offload_entries;
98/// __attribute__((visibility("hidden")))
99/// extern __tgt_offload_entry *__stop_llvm_offload_entries;
100///
101/// static const char Image0[] = { <Bufs.front() contents> };
102/// ...
103/// static const char ImageN[] = { <Bufs.back() contents> };
104///
105/// static const __tgt_device_image Images[] = {
106/// {
107/// Image0, /*ImageStart*/
108/// Image0 + sizeof(Image0), /*ImageEnd*/
109/// __start_llvm_offload_entries, /*EntriesBegin*/
110/// __stop_llvm_offload_entries /*EntriesEnd*/
111/// },
112/// ...
113/// {
114/// ImageN, /*ImageStart*/
115/// ImageN + sizeof(ImageN), /*ImageEnd*/
116/// __start_llvm_offload_entries, /*EntriesBegin*/
117/// __stop_llvm_offload_entries /*EntriesEnd*/
118/// }
119/// };
120///
121/// static const __tgt_bin_desc BinDesc = {
122/// sizeof(Images) / sizeof(Images[0]), /*NumDeviceImages*/
123/// Images, /*DeviceImages*/
124/// __start_llvm_offload_entries, /*HostEntriesBegin*/
125/// __stop_llvm_offload_entries /*HostEntriesEnd*/
126/// };
127///
128/// Global variable that represents BinDesc is returned.
129GlobalVariable *createBinDesc(Module &M, ArrayRef<ArrayRef<char>> Bufs,
130 EntryArrayTy EntryArray, StringRef Suffix,
131 bool Relocatable) {
132 LLVMContext &C = M.getContext();
133 auto [EntriesB, EntriesE] = EntryArray;
134
135 // Create initializer for the images array.
136 SmallVector<Constant *, 4u> ImagesInits;
137 ImagesInits.reserve(N: Bufs.size());
138 for (ArrayRef<char> Buf : Bufs) {
139 // We embed the full offloading entry so the binary utilities can parse it.
140 auto *Data = ConstantDataArray::get(Context&: C, Elts: Buf);
141 auto *Image = new GlobalVariable(M, Data->getType(), /*isConstant=*/true,
142 GlobalVariable::InternalLinkage, Data,
143 ".omp_offloading.device_image" + Suffix);
144 Image->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
145 Image->setSection(Relocatable ? ".llvm.offloading.relocatable"
146 : ".llvm.offloading");
147 Image->setAlignment(Align(object::OffloadBinary::getAlignment()));
148
149 StringRef Binary(Buf.data(), Buf.size());
150
151 uint64_t BeginOffset = 0;
152 uint64_t EndOffset = Binary.size();
153
154 // Optionally use an offload binary for its offload dumping support.
155 // The device image struct contains the pointer to the beginning and end of
156 // the image stored inside of the offload binary. There should only be one
157 // of these for each buffer so we parse it out manually.
158 if (identify_magic(magic: Binary) == file_magic::offload_binary) {
159 const auto *Header =
160 reinterpret_cast<const object::OffloadBinary::Header *>(
161 Binary.bytes_begin());
162 const auto *Entry =
163 reinterpret_cast<const object::OffloadBinary::Entry *>(
164 Binary.bytes_begin() + Header->EntriesOffset);
165 BeginOffset = Entry->ImageOffset;
166 EndOffset = Entry->ImageOffset + Entry->ImageSize;
167 }
168
169 auto *Begin = ConstantInt::get(Ty: getSizeTTy(M), V: BeginOffset);
170 auto *Size = ConstantInt::get(Ty: getSizeTTy(M), V: EndOffset);
171 auto *ImageB = ConstantExpr::getPtrAdd(Ptr: Image, Offset: Begin);
172 auto *ImageE = ConstantExpr::getPtrAdd(Ptr: Image, Offset: Size);
173
174 ImagesInits.push_back(Elt: ConstantStruct::get(T: getDeviceImageTy(M), Vs: ImageB,
175 Vs: ImageE, Vs: EntriesB, Vs: EntriesE));
176 }
177
178 // Then create images array.
179 auto *ImagesData = ConstantArray::get(
180 T: ArrayType::get(ElementType: getDeviceImageTy(M), NumElements: ImagesInits.size()), V: ImagesInits);
181
182 auto *Images =
183 new GlobalVariable(M, ImagesData->getType(), /*isConstant*/ true,
184 GlobalValue::InternalLinkage, ImagesData,
185 ".omp_offloading.device_images" + Suffix);
186 Images->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
187
188 // And finally create the binary descriptor object.
189 auto *DescInit = ConstantStruct::get(
190 T: getBinDescTy(M),
191 Vs: ConstantInt::get(Ty: Type::getInt32Ty(C), V: ImagesInits.size()), Vs: Images,
192 Vs: EntriesB, Vs: EntriesE);
193
194 return new GlobalVariable(M, DescInit->getType(), /*isConstant=*/true,
195 GlobalValue::InternalLinkage, DescInit,
196 ".omp_offloading.descriptor" + Suffix);
197}
198
199Function *createUnregisterFunction(Module &M, GlobalVariable *BinDesc,
200 StringRef Suffix) {
201 LLVMContext &C = M.getContext();
202 auto *FuncTy = FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
203 auto *Func =
204 Function::Create(Ty: FuncTy, Linkage: GlobalValue::InternalLinkage,
205 N: ".omp_offloading.descriptor_unreg" + Suffix, M: &M);
206 Func->setSection(getStartupSection(T: M.getTargetTriple()));
207
208 // Get __tgt_unregister_lib function declaration.
209 auto *UnRegFuncTy = FunctionType::get(Result: Type::getVoidTy(C), Params: getBinDescPtrTy(M),
210 /*isVarArg*/ false);
211 FunctionCallee UnRegFuncC =
212 M.getOrInsertFunction(Name: "__tgt_unregister_lib", T: UnRegFuncTy);
213
214 // Construct function body
215 IRBuilder<> Builder(BasicBlock::Create(Context&: C, Name: "entry", Parent: Func));
216 Builder.CreateCall(Callee: UnRegFuncC, Args: BinDesc);
217 Builder.CreateRetVoid();
218
219 return Func;
220}
221
222void createRegisterFunction(Module &M, GlobalVariable *BinDesc,
223 StringRef Suffix) {
224 LLVMContext &C = M.getContext();
225 auto *FuncTy = FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
226 auto *Func = Function::Create(Ty: FuncTy, Linkage: GlobalValue::InternalLinkage,
227 N: ".omp_offloading.descriptor_reg" + Suffix, M: &M);
228 Func->setSection(getStartupSection(T: M.getTargetTriple()));
229
230 // Get __tgt_register_lib function declaration.
231 auto *RegFuncTy = FunctionType::get(Result: Type::getVoidTy(C), Params: getBinDescPtrTy(M),
232 /*isVarArg*/ false);
233 FunctionCallee RegFuncC =
234 M.getOrInsertFunction(Name: "__tgt_register_lib", T: RegFuncTy);
235
236 auto *AtExitTy = FunctionType::get(
237 Result: Type::getInt32Ty(C), Params: PointerType::getUnqual(C), /*isVarArg=*/false);
238 FunctionCallee AtExit = M.getOrInsertFunction(Name: "atexit", T: AtExitTy);
239
240 Function *UnregFunc = createUnregisterFunction(M, BinDesc, Suffix);
241
242 // Construct function body
243 IRBuilder<> Builder(BasicBlock::Create(Context&: C, Name: "entry", Parent: Func));
244
245 Builder.CreateCall(Callee: RegFuncC, Args: BinDesc);
246
247 // Register the destructors with 'atexit'. This is expected by the CUDA
248 // runtime and ensures that we clean up before dynamic objects are destroyed.
249 // This needs to be done after plugin initialization to ensure that it is
250 // called before the plugin runtime is destroyed.
251 Builder.CreateCall(Callee: AtExit, Args: UnregFunc);
252 Builder.CreateRetVoid();
253
254 // Add this function to constructors.
255 appendToGlobalCtors(M, F: Func, /*Priority=*/101);
256}
257
258// struct fatbin_wrapper {
259// int32_t magic;
260// int32_t version;
261// void *image;
262// void *reserved;
263//};
264StructType *getFatbinWrapperTy(Module &M) {
265 LLVMContext &C = M.getContext();
266 StructType *FatbinTy = StructType::getTypeByName(C, Name: "fatbin_wrapper");
267 if (!FatbinTy)
268 FatbinTy = StructType::create(
269 Name: "fatbin_wrapper", elt1: Type::getInt32Ty(C), elts: Type::getInt32Ty(C),
270 elts: PointerType::getUnqual(C), elts: PointerType::getUnqual(C));
271 return FatbinTy;
272}
273
274/// Embed the image \p Image into the module \p M so it can be found by the
275/// runtime.
276GlobalVariable *createFatbinDesc(Module &M, ArrayRef<char> Image, bool IsHIP,
277 StringRef Suffix) {
278 LLVMContext &C = M.getContext();
279 llvm::Type *Int8PtrTy = PointerType::getUnqual(C);
280 const llvm::Triple &Triple = M.getTargetTriple();
281
282 // Create the global string containing the fatbinary.
283 StringRef FatbinConstantSection =
284 IsHIP ? (Triple.isMacOSX() ? "__HIP,__hip_fatbin" : ".hip_fatbin")
285 : (Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin");
286 auto *Data = ConstantDataArray::get(Context&: C, Elts: Image);
287 auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
288 GlobalVariable::InternalLinkage, Data,
289 ".fatbin_image" + Suffix);
290 Fatbin->setSection(FatbinConstantSection);
291
292 // Create the fatbinary wrapper
293 StringRef FatbinWrapperSection =
294 IsHIP ? (Triple.isMacOSX() ? "__HIP,__fatbin" : ".hipFatBinSegment")
295 : (Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment");
296 Constant *FatbinWrapper[] = {
297 ConstantInt::get(Ty: Type::getInt32Ty(C), V: IsHIP ? HIPFatMagic : CudaFatMagic),
298 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 1),
299 ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: Fatbin, Ty: Int8PtrTy),
300 ConstantPointerNull::get(T: PointerType::getUnqual(C))};
301
302 Constant *FatbinInitializer =
303 ConstantStruct::get(T: getFatbinWrapperTy(M), V: FatbinWrapper);
304
305 auto *FatbinDesc =
306 new GlobalVariable(M, getFatbinWrapperTy(M),
307 /*isConstant*/ true, GlobalValue::InternalLinkage,
308 FatbinInitializer, ".fatbin_wrapper" + Suffix);
309 FatbinDesc->setSection(FatbinWrapperSection);
310 FatbinDesc->setAlignment(Align(8));
311 FatbinDesc->setNoSanitizeMetadata();
312
313 return FatbinDesc;
314}
315
316/// Create the register globals function. We will iterate all of the offloading
317/// entries stored at the begin / end symbols and register them according to
318/// their type. This creates the following function in IR:
319///
320/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
321/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
322///
323/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
324/// void *, void *, void *, void *, int *);
325/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
326/// int64_t, int32_t, int32_t);
327///
328/// void __cudaRegisterTest(void **fatbinHandle) {
329/// for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
330/// entry != &__stop_cuda_offloading_entries; ++entry) {
331/// if (entry->Kind != OFK_CUDA)
332/// continue
333///
334/// if (!entry->Size)
335/// __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
336/// entry->name, -1, 0, 0, 0, 0, 0);
337/// else
338/// __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,
339/// 0, entry->size, 0, 0);
340/// }
341/// }
342Function *createRegisterGlobalsFunction(Module &M, bool IsHIP,
343 EntryArrayTy EntryArray,
344 StringRef Suffix,
345 bool EmitSurfacesAndTextures) {
346 LLVMContext &C = M.getContext();
347 auto [EntriesB, EntriesE] = EntryArray;
348
349 // Get the __cudaRegisterFunction function declaration.
350 PointerType *Int8PtrTy = PointerType::get(C, AddressSpace: 0);
351 PointerType *Int8PtrPtrTy = PointerType::get(C, AddressSpace: 0);
352 PointerType *Int32PtrTy = PointerType::get(C, AddressSpace: 0);
353 auto *RegFuncTy = FunctionType::get(
354 Result: Type::getInt32Ty(C),
355 Params: {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
356 Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32PtrTy},
357 /*isVarArg*/ false);
358 FunctionCallee RegFunc = M.getOrInsertFunction(
359 Name: IsHIP ? "__hipRegisterFunction" : "__cudaRegisterFunction", T: RegFuncTy);
360
361 // Get the __cudaRegisterVar function declaration.
362 auto *RegVarTy = FunctionType::get(
363 Result: Type::getVoidTy(C),
364 Params: {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
365 getSizeTTy(M), Type::getInt32Ty(C), Type::getInt32Ty(C)},
366 /*isVarArg*/ false);
367 FunctionCallee RegVar = M.getOrInsertFunction(
368 Name: IsHIP ? "__hipRegisterVar" : "__cudaRegisterVar", T: RegVarTy);
369
370 // Get the __cudaRegisterSurface function declaration.
371 FunctionType *RegManagedVarTy =
372 FunctionType::get(Result: Type::getVoidTy(C),
373 Params: {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy,
374 getSizeTTy(M), Type::getInt32Ty(C)},
375 /*isVarArg=*/false);
376 FunctionCallee RegManagedVar = M.getOrInsertFunction(
377 Name: IsHIP ? "__hipRegisterManagedVar" : "__cudaRegisterManagedVar",
378 T: RegManagedVarTy);
379
380 // Get the __cudaRegisterSurface function declaration.
381 FunctionType *RegSurfaceTy =
382 FunctionType::get(Result: Type::getVoidTy(C),
383 Params: {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy,
384 Type::getInt32Ty(C), Type::getInt32Ty(C)},
385 /*isVarArg=*/false);
386 FunctionCallee RegSurface = M.getOrInsertFunction(
387 Name: IsHIP ? "__hipRegisterSurface" : "__cudaRegisterSurface", T: RegSurfaceTy);
388
389 // Get the __cudaRegisterTexture function declaration.
390 FunctionType *RegTextureTy = FunctionType::get(
391 Result: Type::getVoidTy(C),
392 Params: {Int8PtrPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Type::getInt32Ty(C),
393 Type::getInt32Ty(C), Type::getInt32Ty(C)},
394 /*isVarArg=*/false);
395 FunctionCallee RegTexture = M.getOrInsertFunction(
396 Name: IsHIP ? "__hipRegisterTexture" : "__cudaRegisterTexture", T: RegTextureTy);
397
398 auto *RegGlobalsTy = FunctionType::get(Result: Type::getVoidTy(C), Params: Int8PtrPtrTy,
399 /*isVarArg*/ false);
400 auto *RegGlobalsFn =
401 Function::Create(Ty: RegGlobalsTy, Linkage: GlobalValue::InternalLinkage,
402 N: IsHIP ? ".hip.globals_reg" : ".cuda.globals_reg", M: &M);
403 RegGlobalsFn->setSection(getStartupSection(T: M.getTargetTriple()));
404
405 // Create the loop to register all the entries.
406 IRBuilder<> Builder(BasicBlock::Create(Context&: C, Name: "entry", Parent: RegGlobalsFn));
407 auto *EntryBB = BasicBlock::Create(Context&: C, Name: "while.entry", Parent: RegGlobalsFn);
408 auto *IfKindBB = BasicBlock::Create(Context&: C, Name: "if.kind", Parent: RegGlobalsFn);
409 auto *IfThenBB = BasicBlock::Create(Context&: C, Name: "if.then", Parent: RegGlobalsFn);
410 auto *IfElseBB = BasicBlock::Create(Context&: C, Name: "if.else", Parent: RegGlobalsFn);
411 auto *SwGlobalBB = BasicBlock::Create(Context&: C, Name: "sw.global", Parent: RegGlobalsFn);
412 auto *SwManagedBB = BasicBlock::Create(Context&: C, Name: "sw.managed", Parent: RegGlobalsFn);
413 auto *SwSurfaceBB = BasicBlock::Create(Context&: C, Name: "sw.surface", Parent: RegGlobalsFn);
414 auto *SwTextureBB = BasicBlock::Create(Context&: C, Name: "sw.texture", Parent: RegGlobalsFn);
415 auto *IfEndBB = BasicBlock::Create(Context&: C, Name: "if.end", Parent: RegGlobalsFn);
416 auto *ExitBB = BasicBlock::Create(Context&: C, Name: "while.end", Parent: RegGlobalsFn);
417
418 auto *EntryCmp = Builder.CreateICmpNE(LHS: EntriesB, RHS: EntriesE);
419 Builder.CreateCondBr(Cond: EntryCmp, True: EntryBB, False: ExitBB);
420 Builder.SetInsertPoint(EntryBB);
421 auto *Entry = Builder.CreatePHI(Ty: PointerType::getUnqual(C), NumReservedValues: 2, Name: "entry");
422 auto *AddrPtr =
423 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
424 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
425 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 4)});
426 auto *Addr = Builder.CreateLoad(Ty: Int8PtrTy, Ptr: AddrPtr, Name: "addr");
427 auto *AuxAddrPtr =
428 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
429 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
430 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 8)});
431 auto *AuxAddr = Builder.CreateLoad(Ty: Int8PtrTy, Ptr: AuxAddrPtr, Name: "aux_addr");
432 auto *KindPtr =
433 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
434 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
435 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 2)});
436 auto *Kind = Builder.CreateLoad(Ty: Type::getInt16Ty(C), Ptr: KindPtr, Name: "kind");
437 auto *NamePtr =
438 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
439 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
440 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 5)});
441 auto *Name = Builder.CreateLoad(Ty: Int8PtrTy, Ptr: NamePtr, Name: "name");
442 auto *SizePtr =
443 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
444 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
445 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 6)});
446 auto *Size = Builder.CreateLoad(Ty: Type::getInt64Ty(C), Ptr: SizePtr, Name: "size");
447 auto *FlagsPtr =
448 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
449 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
450 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 3)});
451 auto *Flags = Builder.CreateLoad(Ty: Type::getInt32Ty(C), Ptr: FlagsPtr, Name: "flags");
452 auto *DataPtr =
453 Builder.CreateInBoundsGEP(Ty: offloading::getEntryTy(M), Ptr: Entry,
454 IdxList: {ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0),
455 ConstantInt::get(Ty: Type::getInt32Ty(C), V: 7)});
456 auto *Data = Builder.CreateTrunc(
457 V: Builder.CreateLoad(Ty: Type::getInt64Ty(C), Ptr: DataPtr, Name: "data"),
458 DestTy: Type::getInt32Ty(C));
459 auto *Type = Builder.CreateAnd(
460 LHS: Flags, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0x7), Name: "type");
461
462 // Extract the flags stored in the bit-field and convert them to C booleans.
463 auto *ExternBit = Builder.CreateAnd(
464 LHS: Flags, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C),
465 V: llvm::offloading::OffloadGlobalExtern));
466 auto *Extern = Builder.CreateLShr(
467 LHS: ExternBit, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C), V: 3), Name: "extern");
468 auto *ConstantBit = Builder.CreateAnd(
469 LHS: Flags, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C),
470 V: llvm::offloading::OffloadGlobalConstant));
471 auto *Const = Builder.CreateLShr(
472 LHS: ConstantBit, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C), V: 4), Name: "constant");
473 auto *NormalizedBit = Builder.CreateAnd(
474 LHS: Flags, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C),
475 V: llvm::offloading::OffloadGlobalNormalized));
476 auto *Normalized = Builder.CreateLShr(
477 LHS: NormalizedBit, RHS: ConstantInt::get(Ty: Type::getInt32Ty(C), V: 5), Name: "normalized");
478 auto *KindCond = Builder.CreateICmpEQ(
479 LHS: Kind, RHS: ConstantInt::get(Ty: Type::getInt16Ty(C),
480 V: IsHIP ? object::OffloadKind::OFK_HIP
481 : object::OffloadKind::OFK_Cuda));
482 Builder.CreateCondBr(Cond: KindCond, True: IfKindBB, False: IfEndBB);
483 Builder.SetInsertPoint(IfKindBB);
484 auto *FnCond = Builder.CreateICmpEQ(
485 LHS: Size, RHS: ConstantInt::getNullValue(Ty: Type::getInt64Ty(C)));
486 Builder.CreateCondBr(Cond: FnCond, True: IfThenBB, False: IfElseBB);
487
488 // Create kernel registration code.
489 Builder.SetInsertPoint(IfThenBB);
490 Builder.CreateCall(
491 Callee: RegFunc,
492 Args: {RegGlobalsFn->arg_begin(), Addr, Name, Name,
493 ConstantInt::getAllOnesValue(Ty: Type::getInt32Ty(C)),
494 ConstantPointerNull::get(T: Int8PtrTy), ConstantPointerNull::get(T: Int8PtrTy),
495 ConstantPointerNull::get(T: Int8PtrTy), ConstantPointerNull::get(T: Int8PtrTy),
496 ConstantPointerNull::get(T: Int32PtrTy)});
497 Builder.CreateBr(Dest: IfEndBB);
498 Builder.SetInsertPoint(IfElseBB);
499
500 auto *Switch = Builder.CreateSwitch(V: Type, Dest: IfEndBB);
501 // Create global variable registration code.
502 Builder.SetInsertPoint(SwGlobalBB);
503 Builder.CreateCall(Callee: RegVar,
504 Args: {RegGlobalsFn->arg_begin(), Addr, Name, Name, Extern, Size,
505 Const, ConstantInt::get(Ty: Type::getInt32Ty(C), V: 0)});
506 Builder.CreateBr(Dest: IfEndBB);
507 Switch->addCase(OnVal: Builder.getInt32(C: llvm::offloading::OffloadGlobalEntry),
508 Dest: SwGlobalBB);
509
510 // Create managed variable registration code.
511 Builder.SetInsertPoint(SwManagedBB);
512 Builder.CreateCall(Callee: RegManagedVar, Args: {RegGlobalsFn->arg_begin(), AuxAddr, Addr,
513 Name, Size, Data});
514 Builder.CreateBr(Dest: IfEndBB);
515 Switch->addCase(OnVal: Builder.getInt32(C: llvm::offloading::OffloadGlobalManagedEntry),
516 Dest: SwManagedBB);
517 // Create surface variable registration code.
518 Builder.SetInsertPoint(SwSurfaceBB);
519 if (EmitSurfacesAndTextures)
520 Builder.CreateCall(Callee: RegSurface, Args: {RegGlobalsFn->arg_begin(), Addr, Name, Name,
521 Data, Extern});
522 Builder.CreateBr(Dest: IfEndBB);
523 Switch->addCase(OnVal: Builder.getInt32(C: llvm::offloading::OffloadGlobalSurfaceEntry),
524 Dest: SwSurfaceBB);
525
526 // Create texture variable registration code.
527 Builder.SetInsertPoint(SwTextureBB);
528 if (EmitSurfacesAndTextures)
529 Builder.CreateCall(Callee: RegTexture, Args: {RegGlobalsFn->arg_begin(), Addr, Name, Name,
530 Data, Normalized, Extern});
531 Builder.CreateBr(Dest: IfEndBB);
532 Switch->addCase(OnVal: Builder.getInt32(C: llvm::offloading::OffloadGlobalTextureEntry),
533 Dest: SwTextureBB);
534
535 Builder.SetInsertPoint(IfEndBB);
536 auto *NewEntry = Builder.CreateInBoundsGEP(
537 Ty: offloading::getEntryTy(M), Ptr: Entry, IdxList: ConstantInt::get(Ty: getSizeTTy(M), V: 1));
538 auto *Cmp = Builder.CreateICmpEQ(LHS: NewEntry, RHS: EntriesE);
539 Entry->addIncoming(V: EntriesB, BB: &RegGlobalsFn->getEntryBlock());
540 Entry->addIncoming(V: NewEntry, BB: IfEndBB);
541 Builder.CreateCondBr(Cond: Cmp, True: ExitBB, False: EntryBB);
542 Builder.SetInsertPoint(ExitBB);
543 Builder.CreateRetVoid();
544
545 return RegGlobalsFn;
546}
547
548// Create the constructor and destructor to register the fatbinary with the CUDA
549// runtime.
550void createRegisterFatbinFunction(Module &M, GlobalVariable *FatbinDesc,
551 bool IsHIP, EntryArrayTy EntryArray,
552 StringRef Suffix,
553 bool EmitSurfacesAndTextures) {
554 LLVMContext &C = M.getContext();
555 auto *CtorFuncTy = FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
556 auto *CtorFunc = Function::Create(
557 Ty: CtorFuncTy, Linkage: GlobalValue::InternalLinkage,
558 N: (IsHIP ? ".hip.fatbin_reg" : ".cuda.fatbin_reg") + Suffix, M: &M);
559 CtorFunc->setSection(getStartupSection(T: M.getTargetTriple()));
560
561 auto *DtorFuncTy = FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
562 auto *DtorFunc = Function::Create(
563 Ty: DtorFuncTy, Linkage: GlobalValue::InternalLinkage,
564 N: (IsHIP ? ".hip.fatbin_unreg" : ".cuda.fatbin_unreg") + Suffix, M: &M);
565 DtorFunc->setSection(getStartupSection(T: M.getTargetTriple()));
566
567 auto *PtrTy = PointerType::getUnqual(C);
568
569 // Get the __cudaRegisterFatBinary function declaration.
570 auto *RegFatTy = FunctionType::get(Result: PtrTy, Params: PtrTy, /*isVarArg=*/false);
571 FunctionCallee RegFatbin = M.getOrInsertFunction(
572 Name: IsHIP ? "__hipRegisterFatBinary" : "__cudaRegisterFatBinary", T: RegFatTy);
573 // Get the __cudaRegisterFatBinaryEnd function declaration.
574 auto *RegFatEndTy =
575 FunctionType::get(Result: Type::getVoidTy(C), Params: PtrTy, /*isVarArg=*/false);
576 FunctionCallee RegFatbinEnd =
577 M.getOrInsertFunction(Name: "__cudaRegisterFatBinaryEnd", T: RegFatEndTy);
578 // Get the __cudaUnregisterFatBinary function declaration.
579 auto *UnregFatTy =
580 FunctionType::get(Result: Type::getVoidTy(C), Params: PtrTy, /*isVarArg=*/false);
581 FunctionCallee UnregFatbin = M.getOrInsertFunction(
582 Name: IsHIP ? "__hipUnregisterFatBinary" : "__cudaUnregisterFatBinary",
583 T: UnregFatTy);
584
585 auto *AtExitTy =
586 FunctionType::get(Result: Type::getInt32Ty(C), Params: PtrTy, /*isVarArg=*/false);
587 FunctionCallee AtExit = M.getOrInsertFunction(Name: "atexit", T: AtExitTy);
588
589 auto *BinaryHandleGlobal = new llvm::GlobalVariable(
590 M, PtrTy, false, llvm::GlobalValue::InternalLinkage,
591 llvm::ConstantPointerNull::get(T: PtrTy),
592 (IsHIP ? ".hip.binary_handle" : ".cuda.binary_handle") + Suffix);
593
594 // Create the constructor to register this image with the runtime.
595 IRBuilder<> CtorBuilder(BasicBlock::Create(Context&: C, Name: "entry", Parent: CtorFunc));
596 CallInst *Handle = CtorBuilder.CreateCall(
597 Callee: RegFatbin,
598 Args: ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: FatbinDesc, Ty: PtrTy));
599 CtorBuilder.CreateAlignedStore(
600 Val: Handle, Ptr: BinaryHandleGlobal,
601 Align: Align(M.getDataLayout().getPointerTypeSize(Ty: PtrTy)));
602 CtorBuilder.CreateCall(Callee: createRegisterGlobalsFunction(M, IsHIP, EntryArray,
603 Suffix,
604 EmitSurfacesAndTextures),
605 Args: Handle);
606 if (!IsHIP)
607 CtorBuilder.CreateCall(Callee: RegFatbinEnd, Args: Handle);
608 CtorBuilder.CreateCall(Callee: AtExit, Args: DtorFunc);
609 CtorBuilder.CreateRetVoid();
610
611 // Create the destructor to unregister the image with the runtime. We cannot
612 // use a standard global destructor after CUDA 9.2 so this must be called by
613 // `atexit()` instead.
614 IRBuilder<> DtorBuilder(BasicBlock::Create(Context&: C, Name: "entry", Parent: DtorFunc));
615 LoadInst *BinaryHandle = DtorBuilder.CreateAlignedLoad(
616 Ty: PtrTy, Ptr: BinaryHandleGlobal,
617 Align: Align(M.getDataLayout().getPointerTypeSize(Ty: PtrTy)));
618 DtorBuilder.CreateCall(Callee: UnregFatbin, Args: BinaryHandle);
619 DtorBuilder.CreateRetVoid();
620
621 // Add this function to constructors.
622 appendToGlobalCtors(M, F: CtorFunc, /*Priority=*/101);
623}
624
625/// SYCLWrapper helper class that creates all LLVM IRs wrapping given images.
626class SYCLWrapper {
627public:
628 SYCLWrapper(Module &M, const SYCLJITOptions &Options, bool IsFinalizedImage)
629 : M(M), C(M.getContext()), Options(Options),
630 IsFinalizedImage(IsFinalizedImage) {}
631
632 /// Embeds \p Buffer (a raw OffloadBinary) as a global constant and returns
633 /// a pair of (Start, Size), where Start points to the beginning of the
634 /// embedded data and Size is its length in bytes.
635 std::pair<Constant *, Constant *> embedBinary(ArrayRef<char> Buffer) {
636 Constant *Arr = ConstantDataArray::get(Context&: C, Elts: Buffer);
637 GlobalVariable *BinaryGV = new GlobalVariable(
638 M, Arr->getType(), /*isConstant=*/true, GlobalValue::InternalLinkage,
639 Arr, ".sycl_offloading.binary");
640 BinaryGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
641 // The linker wrapper scans ".llvm.offloading" for device code to link, so
642 // an already finalized image must go elsewhere to avoid being linked again.
643 BinaryGV->setSection(IsFinalizedImage ? ".sycl_fatbin"
644 : ".llvm.offloading");
645
646 IntegerType *Int64Ty = Type::getInt64Ty(C);
647 Constant *Size = ConstantInt::get(Ty: Int64Ty, V: Buffer.size());
648 return {BinaryGV, Size};
649 }
650
651 Function *createRegisterFatbinFunction(Constant *Start, Constant *Size) {
652 FunctionType *FuncTy =
653 FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
654 Function *Func = Function::Create(Ty: FuncTy, Linkage: GlobalValue::InternalLinkage,
655 N: Twine("sycl") + ".descriptor_reg", M: &M);
656 Func->setSection(getStartupSection(T: M.getTargetTriple()));
657
658 PointerType *PtrTy = PointerType::getUnqual(C);
659 IntegerType *Int64Ty = Type::getInt64Ty(C);
660 FunctionType *RegFuncTy =
661 FunctionType::get(Result: Type::getVoidTy(C), Params: {PtrTy, Int64Ty},
662 /*isVarArg=*/false);
663 FunctionCallee RegFuncC =
664 M.getOrInsertFunction(Name: "__sycl_register_lib", T: RegFuncTy);
665
666 FunctionType *AtExitTy =
667 FunctionType::get(Result: Type::getInt32Ty(C), Params: PtrTy, /*isVarArg=*/false);
668 FunctionCallee AtExit = M.getOrInsertFunction(Name: "atexit", T: AtExitTy);
669
670 Function *UnregFunc = createUnregisterFunction(Start, Size);
671
672 IRBuilder<> Builder(BasicBlock::Create(Context&: C, Name: "entry", Parent: Func));
673 Builder.CreateCall(Callee: RegFuncC, Args: {Start, Size});
674
675 // Unregister with 'atexit'. The handler is installed after
676 // __sycl_register_lib has brought the runtime's own exit-time cleanup into
677 // the atexit chain, so it is ordered ahead of that cleanup.
678 Builder.CreateCall(Callee: AtExit, Args: UnregFunc);
679 Builder.CreateRetVoid();
680
681 return Func;
682 }
683
684private:
685 Function *createUnregisterFunction(Constant *Start, Constant *Size) {
686 FunctionType *FuncTy =
687 FunctionType::get(Result: Type::getVoidTy(C), /*isVarArg*/ false);
688 Function *Func = Function::Create(Ty: FuncTy, Linkage: GlobalValue::InternalLinkage,
689 N: "sycl.descriptor_unreg", M: &M);
690 Func->setSection(getStartupSection(T: M.getTargetTriple()));
691
692 PointerType *PtrTy = PointerType::getUnqual(C);
693 IntegerType *Int64Ty = Type::getInt64Ty(C);
694 FunctionType *UnRegFuncTy =
695 FunctionType::get(Result: Type::getVoidTy(C), Params: {PtrTy, Int64Ty},
696 /*isVarArg=*/false);
697 FunctionCallee UnRegFuncC =
698 M.getOrInsertFunction(Name: "__sycl_unregister_lib", T: UnRegFuncTy);
699
700 IRBuilder<> Builder(BasicBlock::Create(Context&: C, Name: "entry", Parent: Func));
701 Builder.CreateCall(Callee: UnRegFuncC, Args: {Start, Size});
702 Builder.CreateRetVoid();
703
704 return Func;
705 }
706
707 Module &M;
708 LLVMContext &C;
709 SYCLJITOptions Options;
710 bool IsFinalizedImage;
711}; // end of SYCLWrapper
712
713} // namespace
714
715Error offloading::wrapOpenMPBinaries(Module &M, ArrayRef<ArrayRef<char>> Images,
716 EntryArrayTy EntryArray,
717 llvm::StringRef Suffix, bool Relocatable) {
718 GlobalVariable *Desc =
719 createBinDesc(M, Bufs: Images, EntryArray, Suffix, Relocatable);
720 if (!Desc)
721 return createStringError(EC: inconvertibleErrorCode(),
722 S: "No binary descriptors created.");
723 createRegisterFunction(M, BinDesc: Desc, Suffix);
724 return Error::success();
725}
726
727Error offloading::wrapCudaBinary(Module &M, ArrayRef<char> Image,
728 EntryArrayTy EntryArray,
729 llvm::StringRef Suffix,
730 bool EmitSurfacesAndTextures) {
731 GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/IsHIP: false, Suffix);
732 if (!Desc)
733 return createStringError(EC: inconvertibleErrorCode(),
734 S: "No fatbin section created.");
735
736 createRegisterFatbinFunction(M, FatbinDesc: Desc, /*IsHip=*/IsHIP: false, EntryArray, Suffix,
737 EmitSurfacesAndTextures);
738 return Error::success();
739}
740
741Error offloading::wrapHIPBinary(Module &M, ArrayRef<char> Image,
742 EntryArrayTy EntryArray, llvm::StringRef Suffix,
743 bool EmitSurfacesAndTextures) {
744 GlobalVariable *Desc = createFatbinDesc(M, Image, /*IsHip=*/IsHIP: true, Suffix);
745 if (!Desc)
746 return createStringError(EC: inconvertibleErrorCode(),
747 S: "No fatbin section created.");
748
749 createRegisterFatbinFunction(M, FatbinDesc: Desc, /*IsHip=*/IsHIP: true, EntryArray, Suffix,
750 EmitSurfacesAndTextures);
751 return Error::success();
752}
753
754Error llvm::offloading::wrapSYCLBinaries(llvm::Module &M, ArrayRef<char> Buffer,
755 SYCLJITOptions Options,
756 bool IsFinalizedImage,
757 Function **RegistrationFunc) {
758 SYCLWrapper W(M, Options, IsFinalizedImage);
759 auto [Start, Size] = W.embedBinary(Buffer);
760 Function *RegisterFunc = W.createRegisterFatbinFunction(Start, Size);
761 if (RegistrationFunc) {
762 *RegistrationFunc = RegisterFunc;
763 return Error::success();
764 }
765
766 appendToGlobalCtors(M, F: RegisterFunc, /*Priority=*/101);
767 return Error::success();
768}
769