LLVM 20.0.0git
Utility.cpp
Go to the documentation of this file.
1//===- Utility.cpp ------ Collection of generic offloading utilities ------===//
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
13#include "llvm/IR/Constants.h"
14#include "llvm/IR/GlobalValue.h"
16#include "llvm/IR/Value.h"
20
21using namespace llvm;
22using namespace llvm::offloading;
23
25 LLVMContext &C = M.getContext();
27 StructType::getTypeByName(C, "struct.__tgt_offload_entry");
28 if (!EntryTy)
30 "struct.__tgt_offload_entry", PointerType::getUnqual(C),
31 PointerType::getUnqual(C), M.getDataLayout().getIntPtrType(C),
33 return EntryTy;
34}
35
37 LLVMContext &C = M.getContext();
38 StructType *StructTy = StructType::getTypeByName(C, "struct.__managed_var");
39 if (!StructTy)
40 StructTy = llvm::StructType::create("struct.__managed_var",
41 PointerType::getUnqual(M.getContext()),
42 PointerType::getUnqual(M.getContext()));
43 return StructTy;
44}
45
46// TODO: Rework this interface to be more generic.
47std::pair<Constant *, GlobalVariable *>
50 int32_t Flags, int32_t Data) {
51 llvm::Triple Triple(M.getTargetTriple());
52 Type *Int8PtrTy = PointerType::getUnqual(M.getContext());
53 Type *Int32Ty = Type::getInt32Ty(M.getContext());
54 Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
55
56 Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
57
58 StringRef Prefix =
59 Triple.isNVPTX() ? "$offloading$entry_name" : ".offloading.entry_name";
60
61 // Create the constant string used to look up the symbol in the device.
62 auto *Str =
63 new GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
64 GlobalValue::InternalLinkage, AddrName, Prefix);
65 StringRef SectionName = ".llvm.rodata.offloading";
66 Str->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
67 Str->setSection(SectionName);
68 Str->setAlignment(Align(1));
69
70 // Make a metadata node for these constants so it can be queried from IR.
71 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.offloading.symbols");
72 Metadata *MDVals[] = {ConstantAsMetadata::get(Str)};
73 MD->addOperand(llvm::MDNode::get(M.getContext(), MDVals));
74
75 // Construct the offloading entry.
76 Constant *EntryData[] = {
79 ConstantInt::get(SizeTy, Size),
80 ConstantInt::get(Int32Ty, Flags),
81 ConstantInt::get(Int32Ty, Data),
82 };
83 Constant *EntryInitializer = ConstantStruct::get(getEntryTy(M), EntryData);
84 return {EntryInitializer, Str};
85}
86
88 uint64_t Size, int32_t Flags, int32_t Data,
90 llvm::Triple Triple(M.getTargetTriple());
91
92 auto [EntryInitializer, NameGV] =
94
95 StringRef Prefix =
96 Triple.isNVPTX() ? "$offloading$entry$" : ".offloading.entry.";
97 auto *Entry = new GlobalVariable(
98 M, getEntryTy(M),
99 /*isConstant=*/true, GlobalValue::WeakAnyLinkage, EntryInitializer,
100 Prefix + Name, nullptr, GlobalValue::NotThreadLocal,
101 M.getDataLayout().getDefaultGlobalsAddressSpace());
102
103 // The entry has to be created in the section the linker expects it to be.
105 Entry->setSection((SectionName + "$OE").str());
106 else
107 Entry->setSection(SectionName);
108 Entry->setAlignment(Align(1));
109}
110
111std::pair<GlobalVariable *, GlobalVariable *>
113 llvm::Triple Triple(M.getTargetTriple());
114
115 auto *ZeroInitilaizer =
116 ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
117 auto *EntryInit = Triple.isOSBinFormatCOFF() ? ZeroInitilaizer : nullptr;
118 auto *EntryType = ArrayType::get(getEntryTy(M), 0);
121
122 auto *EntriesB =
123 new GlobalVariable(M, EntryType, /*isConstant=*/true, Linkage, EntryInit,
124 "__start_" + SectionName);
125 EntriesB->setVisibility(GlobalValue::HiddenVisibility);
126 auto *EntriesE =
127 new GlobalVariable(M, EntryType, /*isConstant=*/true, Linkage, EntryInit,
128 "__stop_" + SectionName);
129 EntriesE->setVisibility(GlobalValue::HiddenVisibility);
130
131 if (Triple.isOSBinFormatELF()) {
132 // We assume that external begin/end symbols that we have created above will
133 // be defined by the linker. This is done whenever a section name with a
134 // valid C-identifier is present. We define a dummy variable here to force
135 // the linker to always provide these symbols.
136 auto *DummyEntry = new GlobalVariable(
137 M, ZeroInitilaizer->getType(), true, GlobalVariable::InternalLinkage,
138 ZeroInitilaizer, "__dummy." + SectionName);
139 DummyEntry->setSection(SectionName);
140 appendToCompilerUsed(M, DummyEntry);
141 } else {
142 // The COFF linker will merge sections containing a '$' together into a
143 // single section. The order of entries in this section will be sorted
144 // alphabetically by the characters following the '$' in the name. Set the
145 // sections here to ensure that the beginning and end symbols are sorted.
146 EntriesB->setSection((SectionName + "$OA").str());
147 EntriesE->setSection((SectionName + "$OZ").str());
148 }
149
150 return std::make_pair(EntriesB, EntriesE);
151}
152
154 uint32_t ImageFlags,
155 StringRef EnvTargetID) {
156 using namespace llvm::ELF;
157 StringRef EnvArch = EnvTargetID.split(":").first;
158
159 // Trivial check if the base processors match.
160 if (EnvArch != ImageArch)
161 return false;
162
163 // Check if the image is requesting xnack on or off.
164 switch (ImageFlags & EF_AMDGPU_FEATURE_XNACK_V4) {
165 case EF_AMDGPU_FEATURE_XNACK_OFF_V4:
166 // The image is 'xnack-' so the environment must be 'xnack-'.
167 if (!EnvTargetID.contains("xnack-"))
168 return false;
169 break;
170 case EF_AMDGPU_FEATURE_XNACK_ON_V4:
171 // The image is 'xnack+' so the environment must be 'xnack+'.
172 if (!EnvTargetID.contains("xnack+"))
173 return false;
174 break;
175 case EF_AMDGPU_FEATURE_XNACK_UNSUPPORTED_V4:
176 case EF_AMDGPU_FEATURE_XNACK_ANY_V4:
177 default:
178 break;
179 }
180
181 // Check if the image is requesting sramecc on or off.
182 switch (ImageFlags & EF_AMDGPU_FEATURE_SRAMECC_V4) {
183 case EF_AMDGPU_FEATURE_SRAMECC_OFF_V4:
184 // The image is 'sramecc-' so the environment must be 'sramecc-'.
185 if (!EnvTargetID.contains("sramecc-"))
186 return false;
187 break;
188 case EF_AMDGPU_FEATURE_SRAMECC_ON_V4:
189 // The image is 'sramecc+' so the environment must be 'sramecc+'.
190 if (!EnvTargetID.contains("sramecc+"))
191 return false;
192 break;
193 case EF_AMDGPU_FEATURE_SRAMECC_UNSUPPORTED_V4:
194 case EF_AMDGPU_FEATURE_SRAMECC_ANY_V4:
195 break;
196 }
197
198 return true;
199}
200
201namespace {
202/// Reads the AMDGPU specific per-kernel-metadata from an image.
203class KernelInfoReader {
204public:
206 : KernelInfoMap(KIM) {}
207
208 /// Process ELF note to read AMDGPU metadata from respective information
209 /// fields.
210 Error processNote(const llvm::object::ELF64LE::Note &Note, size_t Align) {
211 if (Note.getName() != "AMDGPU")
212 return Error::success(); // We are not interested in other things
213
214 assert(Note.getType() == ELF::NT_AMDGPU_METADATA &&
215 "Parse AMDGPU MetaData");
216 auto Desc = Note.getDesc(Align);
217 StringRef MsgPackString =
218 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
219 msgpack::Document MsgPackDoc;
220 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
221 return Error::success();
222
224 if (!Verifier.verify(MsgPackDoc.getRoot()))
225 return Error::success();
226
227 auto RootMap = MsgPackDoc.getRoot().getMap(true);
228
229 if (auto Err = iterateAMDKernels(RootMap))
230 return Err;
231
232 return Error::success();
233 }
234
235private:
236 /// Extracts the relevant information via simple string look-up in the msgpack
237 /// document elements.
238 Error
239 extractKernelData(msgpack::MapDocNode::MapTy::value_type V,
240 std::string &KernelName,
242 if (!V.first.isString())
243 return Error::success();
244
245 const auto IsKey = [](const msgpack::DocNode &DK, StringRef SK) {
246 return DK.getString() == SK;
247 };
248
249 const auto GetSequenceOfThreeInts = [](msgpack::DocNode &DN,
250 uint32_t *Vals) {
251 assert(DN.isArray() && "MsgPack DocNode is an array node");
252 auto DNA = DN.getArray();
253 assert(DNA.size() == 3 && "ArrayNode has at most three elements");
254
255 int I = 0;
256 for (auto DNABegin = DNA.begin(), DNAEnd = DNA.end(); DNABegin != DNAEnd;
257 ++DNABegin) {
258 Vals[I++] = DNABegin->getUInt();
259 }
260 };
261
262 if (IsKey(V.first, ".name")) {
263 KernelName = V.second.toString();
264 } else if (IsKey(V.first, ".sgpr_count")) {
265 KernelData.SGPRCount = V.second.getUInt();
266 } else if (IsKey(V.first, ".sgpr_spill_count")) {
267 KernelData.SGPRSpillCount = V.second.getUInt();
268 } else if (IsKey(V.first, ".vgpr_count")) {
269 KernelData.VGPRCount = V.second.getUInt();
270 } else if (IsKey(V.first, ".vgpr_spill_count")) {
271 KernelData.VGPRSpillCount = V.second.getUInt();
272 } else if (IsKey(V.first, ".agpr_count")) {
273 KernelData.AGPRCount = V.second.getUInt();
274 } else if (IsKey(V.first, ".private_segment_fixed_size")) {
275 KernelData.PrivateSegmentSize = V.second.getUInt();
276 } else if (IsKey(V.first, ".group_segment_fixed_size")) {
277 KernelData.GroupSegmentList = V.second.getUInt();
278 } else if (IsKey(V.first, ".reqd_workgroup_size")) {
279 GetSequenceOfThreeInts(V.second, KernelData.RequestedWorkgroupSize);
280 } else if (IsKey(V.first, ".workgroup_size_hint")) {
281 GetSequenceOfThreeInts(V.second, KernelData.WorkgroupSizeHint);
282 } else if (IsKey(V.first, ".wavefront_size")) {
283 KernelData.WavefrontSize = V.second.getUInt();
284 } else if (IsKey(V.first, ".max_flat_workgroup_size")) {
285 KernelData.MaxFlatWorkgroupSize = V.second.getUInt();
286 }
287
288 return Error::success();
289 }
290
291 /// Get the "amdhsa.kernels" element from the msgpack Document
293 auto Res = MDN.find("amdhsa.kernels");
294 if (Res == MDN.end())
296 "Could not find amdhsa.kernels key");
297
298 auto Pair = *Res;
299 assert(Pair.second.isArray() &&
300 "AMDGPU kernel entries are arrays of entries");
301
302 return Pair.second.getArray();
303 }
304
305 /// Iterate all entries for one "amdhsa.kernels" entry. Each entry is a
306 /// MapDocNode that either maps a string to a single value (most of them) or
307 /// to another array of things. Currently, we only handle the case that maps
308 /// to scalar value.
309 Error generateKernelInfo(msgpack::ArrayDocNode::ArrayTy::iterator It) {
311 std::string KernelName;
312 auto Entry = (*It).getMap();
313 for (auto MI = Entry.begin(), E = Entry.end(); MI != E; ++MI)
314 if (auto Err = extractKernelData(*MI, KernelName, KernelData))
315 return Err;
316
317 KernelInfoMap.insert({KernelName, KernelData});
318 return Error::success();
319 }
320
321 /// Go over the list of AMD kernels in the "amdhsa.kernels" entry
322 Error iterateAMDKernels(msgpack::MapDocNode &MDN) {
323 auto KernelsOrErr = getAMDKernelsArray(MDN);
324 if (auto Err = KernelsOrErr.takeError())
325 return Err;
326
327 auto KernelsArr = *KernelsOrErr;
328 for (auto It = KernelsArr.begin(), E = KernelsArr.end(); It != E; ++It) {
329 if (!It->isMap())
330 continue; // we expect <key,value> pairs
331
332 // Obtain the value for the different entries. Each array entry is a
333 // MapDocNode
334 if (auto Err = generateKernelInfo(It))
335 return Err;
336 }
337 return Error::success();
338 }
339
340 // Kernel names are the keys
342};
343} // namespace
344
346 MemoryBufferRef MemBuffer,
348 uint16_t &ELFABIVersion) {
349 Error Err = Error::success(); // Used later as out-parameter
350
351 auto ELFOrError = object::ELF64LEFile::create(MemBuffer.getBuffer());
352 if (auto Err = ELFOrError.takeError())
353 return Err;
354
355 const object::ELF64LEFile ELFObj = ELFOrError.get();
357 if (!Sections)
358 return Sections.takeError();
359 KernelInfoReader Reader(KernelInfoMap);
360
361 // Read the code object version from ELF image header
362 auto Header = ELFObj.getHeader();
363 ELFABIVersion = (uint8_t)(Header.e_ident[ELF::EI_ABIVERSION]);
364 for (const auto &S : *Sections) {
365 if (S.sh_type != ELF::SHT_NOTE)
366 continue;
367
368 for (const auto N : ELFObj.notes(S, Err)) {
369 if (Err)
370 return Err;
371 // Fills the KernelInfoTabel entries in the reader
372 if ((Err = Reader.processNote(N, S.sh_addralign)))
373 return Err;
374 }
375 }
376 return Error::success();
377}
This is a verifier for AMDGPU HSA metadata, which can verify both well-typed metadata and untyped met...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
uint64_t Addr
std::string Name
uint64_t Size
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares a class that exposes a simple in-memory representation of a document of MsgPack ob...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
verify safepoint Safepoint IR Verifier
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1672
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:532
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2991
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2268
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1378
This is an important base class in LLVM.
Definition: Constant.h:42
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1549
StringRef getBuffer() const
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1737
void addOperand(MDNode *M)
Definition: Metadata.cpp:1431
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:424
Class to represent struct types.
Definition: DerivedTypes.h:218
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition: Type.cpp:731
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:612
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:752
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
Definition: Triple.h:875
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:747
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt32Ty(LLVMContext &C)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
A node in a MsgPack Document.
MapDocNode & getMap(bool Convert=false)
Get a MapDocNode for a map node.
ArrayDocNode & getArray(bool Convert=false)
Get an ArrayDocNode for an array node.
StringRef getString() const
Simple in-memory representation of a document of msgpack objects with ability to find and create arra...
DocNode & getRoot()
Get ref to the document's root element.
bool readFromBlob(StringRef Blob, bool Multi, function_ref< int(DocNode *DestNode, DocNode SrcNode, DocNode MapKey)> Merger=[](DocNode *DestNode, DocNode SrcNode, DocNode MapKey) { return -1;})
Read a document from a binary msgpack blob, merging into anything already in the Document.
A DocNode that is a map.
MapTy::iterator find(DocNode Key)
const Elf_Ehdr & getHeader() const
Definition: ELF.h:279
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:888
iterator_range< Elf_Note_Iterator > notes(const Elf_Phdr &Phdr, Error &Err) const
Get an iterator range over notes of a program header.
Definition: ELF.h:462
Expected< Elf_Shdr_Range > sections() const
Definition: ELF.h:925
@ Entry
Definition: COFF.h:844
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Definition: ELF.h:28
@ EI_ABIVERSION
Definition: ELF.h:57
@ SHT_NOTE
Definition: ELF.h:1104
@ NT_AMDGPU_METADATA
Definition: ELF.h:1923
Error getAMDGPUMetaDataFromImage(MemoryBufferRef MemBuffer, StringMap< AMDGPUKernelMetaData > &KernelInfoMap, uint16_t &ELFABIVersion)
Reads AMDGPU specific metadata from the ELF file and propagates the KernelInfoMap.
Definition: Utility.cpp:345
bool isImageCompatibleWithEnv(StringRef ImageArch, uint32_t ImageFlags, StringRef EnvTargetID)
Check if an image is compatible with current system's environment.
Definition: Utility.cpp:153
StructType * getManagedTy(Module &M)
Returns the struct type we store the two pointers for CUDA / HIP managed variables in.
Definition: Utility.cpp:36
std::pair< Constant *, GlobalVariable * > getOffloadingEntryInitializer(Module &M, Constant *Addr, StringRef Name, uint64_t Size, int32_t Flags, int32_t Data)
Create a constant struct initializer used to register this global at runtime.
Definition: Utility.cpp:48
StructType * getEntryTy(Module &M)
Returns the type of the offloading entry we use to store kernels and globals that will be registered ...
Definition: Utility.cpp:24
void emitOffloadingEntry(Module &M, Constant *Addr, StringRef Name, uint64_t Size, int32_t Flags, int32_t Data, StringRef SectionName)
Create an offloading section struct used to register this global at runtime.
Definition: Utility.cpp:87
std::pair< GlobalVariable *, GlobalVariable * > getOffloadEntryArray(Module &M, StringRef SectionName)
Creates a pair of globals used to iterate the array of offloading entries by accessing the section va...
Definition: Utility.cpp:112
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1291
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Description of the encoding of one expression Op.
This is the record of an object that just be registered with the offloading runtime.
Definition: Utility.h:26
Struct for holding metadata related to AMDGPU kernels, for more information about the metadata and it...
Definition: Utility.h:103
uint32_t SGPRSpillCount
Number of stores from a scalar register to a register allocator created spill location.
Definition: Utility.h:118
uint32_t SGPRCount
Number of scalar registers required by a wavefront.
Definition: Utility.h:113
uint32_t VGPRSpillCount
Number of stores from a vector register to a register allocator created spill location.
Definition: Utility.h:121
uint32_t VGPRCount
Number of vector registers required by each work-item.
Definition: Utility.h:115
uint32_t PrivateSegmentSize
The amount of fixed private address space memory required for a work-item in bytes.
Definition: Utility.h:111
uint32_t GroupSegmentList
The amount of group segment memory required by a work-group in bytes.
Definition: Utility.h:108
uint32_t MaxFlatWorkgroupSize
Maximum flat work-group size supported by the kernel in work-items.
Definition: Utility.h:132
uint32_t WorkgroupSizeHint[3]
Corresponds to the OpenCL work_group_size_hint attribute.
Definition: Utility.h:128
uint32_t AGPRCount
Number of accumulator registers required by each work-item.
Definition: Utility.h:123
uint32_t RequestedWorkgroupSize[3]
Corresponds to the OpenCL reqd_work_group_size attribute.
Definition: Utility.h:125