LLVM 24.0.0git
OffloadBinary.h
Go to the documentation of this file.
1//===- OffloadBinary.h - Utilities for handling offloading code -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the binary format used for bundling device metadata with
10// an associated device image. The data can then be stored inside a host object
11// file to create a fat binary and read by the linker. This is intended to be a
12// thin wrapper around the image itself. If this format becomes sufficiently
13// complex it should be moved to a standard binary format like msgpack or ELF.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_OBJECT_OFFLOADBINARY_H
18#define LLVM_OBJECT_OFFLOADBINARY_H
19
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Object/Binary.h"
27#include "llvm/Support/Error.h"
29#include <memory>
30
31namespace llvm {
32
33namespace object {
34
35/// The producer of the associated offloading image.
38 OFK_OpenMP = (1 << 0),
39 OFK_Cuda = (1 << 1),
40 OFK_HIP = (1 << 2),
41 OFK_SYCL = (1 << 3),
42 OFK_LAST = (1 << 4),
43};
44
45/// The type of contents the offloading image contains.
56
57/// Flags associated with the Entry.
60 // Entry doesn't contain an image. Used to keep metadata only entries.
61 OIF_Metadata = (1 << 0),
62};
63
64/// A simple binary serialization of an offloading file. We use this format to
65/// embed the offloading image into the host executable so it can be extracted
66/// and used by the linker.
67///
68/// Many of these could be stored in the same section by the time the linker
69/// sees it so we mark this information with a header. The version is used to
70/// detect ABI stability and the size is used to find other offloading entries
71/// that may exist in the same section. All offsets are given as absolute byte
72/// offsets from the beginning of the file.
73class OffloadBinary : public Binary {
74public:
77
78 /// The current version of the binary used for backwards compatibility.
79 static const uint32_t Version = 3;
80
81 /// The offloading metadata that will be serialized to a memory buffer.
89
90 struct Header {
91 uint8_t Magic[4] = {0x10, 0xFF, 0x10, 0xAD}; // 0x10FF10AD magic bytes.
92 uint32_t Version = OffloadBinary::Version; // Version identifier.
93 uint64_t Size; // Size in bytes of this entire binary.
94 uint64_t EntriesOffset; // Offset in bytes to the start of entries block.
95 uint64_t EntriesCount; // Number of metadata entries in the binary.
96 uint64_t InflatedSize; // Original size of the binary if compressed.
97 };
98
99 struct Entry {
100 ImageKind TheImageKind; // The kind of the image stored.
101 OffloadKind TheOffloadKind; // The producer of this image.
102 uint32_t Flags; // Additional flags associated with the entry.
103 uint64_t StringOffset; // Offset in bytes to the string map.
104 uint64_t NumStrings; // Number of entries in the string map.
105 uint64_t ImageOffset; // Offset in bytes of the actual binary image.
106 uint64_t ImageSize; // Size in bytes of the binary image.
107 };
108
109 struct StringEntry {
112 uint64_t ValueSize; // Size of the value in bytes.
113 };
114
119
120 /// Attempt to extract and validate the header from the offloading binary in
121 /// \p Buf.
124
125 /// Attempt to parse the offloading binary stored in \p Buf.
126 /// For version 1 binaries, always returns a single OffloadBinary.
127 /// For version 2+ binaries:
128 /// - If \p Index is provided, returns the OffloadBinary at that index.
129 /// - If \p Index is std::nullopt, returns all OffloadBinary entries.
130 /// \param Buf The memory buffer containing the offload binary.
131 /// \param Index Optional index to select a specific entry. If not provided,
132 /// all entries are returned (version 2+ only).
133 /// \returns An array of unique pointers to OffloadBinary objects, or an
134 /// error.
136 create(MemoryBufferRef Buf, std::optional<uint64_t> Index = std::nullopt);
137
138 /// Serialize the contents of \p OffloadingData to a binary buffer to be read
139 /// later.
141 write(ArrayRef<OffloadingImage> OffloadingData);
142
143 /// Serialize \p OffloadingData to a compressed binary with \p Compress.
145 write(ArrayRef<OffloadingImage> OffloadingData, compression::Params Compress);
146
147 static uint64_t getAlignment() { return 8; }
148
149 ImageKind getImageKind() const { return TheEntry->TheImageKind; }
150 OffloadKind getOffloadKind() const { return TheEntry->TheOffloadKind; }
151 uint32_t getVersion() const { return TheHeader->Version; }
152 uint32_t getFlags() const { return TheEntry->Flags; }
153 uint64_t getSize() const { return TheHeader->Size; }
154 uint64_t getIndex() const { return Index; }
155
156 StringRef getTriple() const { return getString("triple"); }
157 StringRef getArch() const { return getString("arch"); }
159 return StringRef(&Buffer[TheEntry->ImageOffset], TheEntry->ImageSize);
160 }
161
162 // Iterator over all the key and value pairs in the binary.
163 string_iterator_range strings() const { return StringData; }
164
165 StringRef getString(StringRef Key) const { return StringData.lookup(Key); }
166
167 static bool classof(const Binary *V) { return V->isOffloadFile(); }
168
169private:
170 OffloadBinary(std::shared_ptr<MemoryBuffer> Owned, const Header *TheHeader,
171 const Entry *TheEntry, const uint64_t Index = 0)
172 : Binary(Binary::ID_Offload, *Owned), OwnedBuffer(std::move(Owned)),
173 Buffer(OwnedBuffer->getBufferStart()), TheHeader(TheHeader),
174 TheEntry(TheEntry), Index(Index) {
175 // StringEntryV1 and StringEntry have ABI compatible Key/ValueOffset fields,
176 // but different sizes, so we need to manually calculate offset.
177 const char *StringMapBegin = &Buffer[TheEntry->StringOffset];
178 const size_t StringEntrySize =
179 TheHeader->Version == 1 ? sizeof(StringEntryV1) : sizeof(StringEntry);
180 for (uint64_t I = 0, E = TheEntry->NumStrings; I != E; ++I) {
181 const char *StringEntryPtr = StringMapBegin + I * StringEntrySize;
182 const StringEntryV1 *EntryV1 =
183 reinterpret_cast<const StringEntryV1 *>(StringEntryPtr);
184 StringRef Key = &Buffer[EntryV1->KeyOffset];
185 if (TheHeader->Version == 1) {
186 StringData[Key] = &Buffer[EntryV1->ValueOffset];
187 } else {
188 const StringEntry *Entry =
189 reinterpret_cast<const StringEntry *>(StringEntryPtr);
190 StringData[Key] =
191 StringRef(&Buffer[Entry->ValueOffset], Entry->ValueSize);
192 }
193 }
194 }
195
196 OffloadBinary(const OffloadBinary &Other) = delete;
197
198 /// Owned uncompressed binary. Shared between entries parsed from one blob.
199 std::shared_ptr<MemoryBuffer> OwnedBuffer;
200 /// Map from keys to offsets in the binary.
201 MapVector<StringRef, StringRef> StringData;
202 /// Raw pointer to the MemoryBufferRef for convenience.
203 const char *Buffer;
204 /// Location of the header within the binary.
205 const Header *TheHeader;
206 /// Location of the metadata entries within the binary.
207 const Entry *TheEntry;
208 /// Index of the entry in the list of entries serialized in the Buffer.
209 const uint64_t Index;
210};
211
212/// A handle to a single OffloadBinary.
214public:
215 using TargetID = std::pair<StringRef, StringRef>;
216
217 OffloadFile() = default;
218 OffloadFile(std::unique_ptr<OffloadBinary> Binary)
219 : Binary(std::move(Binary)) {}
220
221 OffloadBinary *getBinary() { return Binary.get(); }
222 const OffloadBinary *getBinary() const { return Binary.get(); }
223
224 /// Make a deep copy of this offloading file.
226 auto NewBinaryOrErr = OffloadBinary::create(
227 getBinary()->getMemoryBufferRef(), getBinary()->getIndex());
228 assert(NewBinaryOrErr && "Failed to parse a copy of the binary?");
229 if (!NewBinaryOrErr)
230 llvm::consumeError(NewBinaryOrErr.takeError());
231 return OffloadFile(std::move((*NewBinaryOrErr)[0]));
232 }
233
234 /// We use the Triple and Architecture pair to group linker inputs together.
235 /// This conversion function lets us use these inputs in a hash-map.
236 operator TargetID() const {
237 return std::make_pair(getBinary()->getTriple(), getBinary()->getArch());
238 }
239
240private:
241 std::unique_ptr<OffloadBinary> Binary;
242};
243
244/// Extracts embedded device offloading code from a memory \p Buffer to a list
245/// of \p Binaries.
246LLVM_ABI Error extractOffloadBinaries(MemoryBufferRef Buffer,
248
249/// Convert a string \p Name to an image kind.
250LLVM_ABI ImageKind getImageKind(StringRef Name);
251
252/// Convert an image kind to its string representation.
253LLVM_ABI StringRef getImageKindName(ImageKind Name);
254
255/// Convert a string \p Name to an offload kind.
256LLVM_ABI OffloadKind getOffloadKind(StringRef Name);
257
258/// Convert an offload kind to its string representation.
259LLVM_ABI StringRef getOffloadKindName(OffloadKind Name);
260
261/// Returns true if an image built for target \p Provided can provide the device
262/// code for a request for target \p Requested. This is directional: a
263/// feature-unspecified or generic image serves a more specific request (e.g. a
264/// generic static-archive member pulled into a specific device-image group),
265/// but not vice versa. For AMDGPU a target id is a string conforming to the
266/// following BNF syntax:
267///
268/// target-id ::= '<arch> ( : <feature> ( '+' | '-' ) )*'
269///
270/// The features 'xnack' and 'sramecc' are currently supported. These can be in
271/// the state of on, off, and any when unspecified. A provided target marked as
272/// any can bind with either on or off.
273LLVM_ABI bool areTargetsCompatible(const OffloadFile::TargetID &Provided,
274 const OffloadFile::TargetID &Requested);
275
276/// Returns true if \p LHS and \p RHS denote the same logical target, i.e. the
277/// same processor and features.
278LLVM_ABI bool areTargetsEquivalent(const OffloadFile::TargetID &LHS,
279 const OffloadFile::TargetID &RHS);
280
281} // namespace object
282
283} // namespace llvm
284#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file defines the SmallString class.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
typename VectorType::const_iterator const_iterator
Definition MapVector.h:45
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A range adaptor for a pair of iterators.
Binary(unsigned int Type, MemoryBufferRef Source)
Definition Binary.cpp:36
A simple binary serialization of an offloading file.
static uint64_t getAlignment()
OffloadKind getOffloadKind() const
iterator_range< string_iterator > string_iterator_range
static LLVM_ABI Expected< SmallVector< std::unique_ptr< OffloadBinary > > > create(MemoryBufferRef Buf, std::optional< uint64_t > Index=std::nullopt)
Attempt to parse the offloading binary stored in Buf.
static LLVM_ABI SmallString< 0 > write(ArrayRef< OffloadingImage > OffloadingData)
Serialize the contents of OffloadingData to a binary buffer to be read later.
StringRef getString(StringRef Key) const
static LLVM_ABI Expected< const Header * > extractHeader(MemoryBufferRef Buf)
Attempt to extract and validate the header from the offloading binary in Buf.
StringRef getTriple() const
ImageKind getImageKind() const
static bool classof(const Binary *V)
string_iterator_range strings() const
static const uint32_t Version
The current version of the binary used for backwards compatibility.
MapVector< StringRef, StringRef >::const_iterator string_iterator
const OffloadBinary * getBinary() const
std::pair< StringRef, StringRef > TargetID
OffloadFile copy() const
Make a deep copy of this offloading file.
OffloadFile(std::unique_ptr< OffloadBinary > Binary)
OffloadBinary * getBinary()
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
OffloadEntryFlags
Flags associated with the Entry.
OffloadKind
The producer of the associated offloading image.
ImageKind
The type of contents the offloading image contains.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
The offloading metadata that will be serialized to a memory buffer.
std::unique_ptr< MemoryBuffer > Image
MapVector< StringRef, StringRef > StringData