clang 24.0.0git
OffloadBundler.cpp
Go to the documentation of this file.
1//===- OffloadBundler.cpp - File Bundling and Unbundling ------------------===//
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/// \file
10/// This file implements an offload bundling API that bundles different files
11/// that relate with the same source code but different targets into a single
12/// one. Also the implements the opposite functionality, i.e. unbundle files
13/// previous created by this API.
14///
15//===----------------------------------------------------------------------===//
16
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/BinaryFormat/Magic.h"
27#include "llvm/Object/Archive.h"
28#include "llvm/Object/ArchiveWriter.h"
29#include "llvm/Object/Binary.h"
30#include "llvm/Object/ObjectFile.h"
31#include "llvm/Object/OffloadBundle.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/Compression.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/EndianStream.h"
37#include "llvm/Support/Errc.h"
38#include "llvm/Support/Error.h"
39#include "llvm/Support/ErrorOr.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/MD5.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Program.h"
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/StringSaver.h"
47#include "llvm/Support/Timer.h"
48#include "llvm/Support/WithColor.h"
49#include "llvm/Support/raw_ostream.h"
50#include "llvm/TargetParser/Host.h"
51#include "llvm/TargetParser/Triple.h"
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <forward_list>
56#include <llvm/Support/Process.h>
57#include <memory>
58#include <set>
59#include <string>
60#include <system_error>
61#include <utility>
62
63using namespace llvm;
64using namespace llvm::object;
65using namespace clang;
66
67/// Magic string that marks the existence of offloading data.
68#define OFFLOAD_BUNDLER_MAGIC_STR "__CLANG_OFFLOAD_BUNDLE__"
69
71 const OffloadBundlerConfig &BC)
72 : BundlerConfig(BC) {
73
74 // <kind>-<triple>[-<target id>[:target features]]
75 // <triple> := <arch>-<vendor>-<os>-<env>
77 Target.split(Components, '-', /*MaxSplit=*/5);
78 assert((Components.size() == 5 || Components.size() == 6) &&
79 "malformed target string");
80
81 StringRef TargetIdWithFeature =
82 Components.size() == 6 ? Components.back() : "";
83 StringRef TargetId = TargetIdWithFeature.split(':').first;
84 if (!TargetId.empty() && !clang::StringToOffloadArch(TargetId).isUnknown())
85 this->TargetID = TargetIdWithFeature;
86 else
87 this->TargetID = "";
88
89 this->OffloadKind = Components.front();
90 ArrayRef<StringRef> TripleSlice{&Components[1], /*length=*/4};
91 this->Triple = llvm::Triple(llvm::join(TripleSlice, "-"));
92}
93
95 return this->OffloadKind == "host";
96}
97
99 return OffloadKind == "host" || OffloadKind == "openmp" ||
100 OffloadKind == "hip" || OffloadKind == "hipv4";
101}
102
104 const StringRef TargetOffloadKind) const {
105 if ((OffloadKind == TargetOffloadKind) ||
106 (OffloadKind == "hip" && TargetOffloadKind == "hipv4") ||
107 (OffloadKind == "hipv4" && TargetOffloadKind == "hip"))
108 return true;
109
110 if (BundlerConfig.HipOpenmpCompatible) {
111 bool HIPCompatibleWithOpenMP = OffloadKind.starts_with_insensitive("hip") &&
112 TargetOffloadKind == "openmp";
113 bool OpenMPCompatibleWithHIP =
114 OffloadKind == "openmp" &&
115 TargetOffloadKind.starts_with_insensitive("hip");
116 return HIPCompatibleWithOpenMP || OpenMPCompatibleWithHIP;
117 }
118 return false;
119}
120
122 return !Triple.str().empty() && Triple.getArch() != Triple::UnknownArch;
123}
124
126 return OffloadKind == Target.OffloadKind &&
127 Triple.isCompatibleWith(Target.Triple) && TargetID == Target.TargetID;
128}
129
130std::string OffloadTargetInfo::str() const {
131 std::string NormalizedTriple;
132 // Unfortunately we need some special sauce for AMDHSA because all the runtime
133 // assumes the triple to be "amdgcn/spirv64-amd-amdhsa-" (empty environment)
134 // instead of "amdgcn/spirv64-amd-amdhsa-unknown". It's gonna be very tricky
135 // to patch different layers of runtime.
136 if (Triple.getOS() == Triple::OSType::AMDHSA) {
137 NormalizedTriple = Triple.normalize(Triple::CanonicalForm::THREE_IDENT);
138 NormalizedTriple.push_back('-');
139 } else {
140 NormalizedTriple = Triple.normalize(Triple::CanonicalForm::FOUR_IDENT);
141 }
142 return Twine(OffloadKind + "-" + NormalizedTriple + "-" + TargetID).str();
143}
144
145static StringRef getDeviceFileExtension(StringRef Device,
146 StringRef BundleFileName) {
147 if (Device.contains("gfx"))
148 return ".bc";
149 if (Device.contains("sm_"))
150 return ".cubin";
151 return sys::path::extension(BundleFileName);
152}
153
154static std::string getDeviceLibraryFileName(StringRef BundleFileName,
155 StringRef Device) {
156 StringRef LibName = sys::path::stem(BundleFileName);
157 StringRef Extension = getDeviceFileExtension(Device, BundleFileName);
158
159 std::string Result;
160 Result += LibName;
161 Result += Extension;
162 return Result;
163}
164
165namespace {
166/// Generic file handler interface.
167class FileHandler {
168public:
169 struct BundleInfo {
170 StringRef BundleID;
171 };
172
173 FileHandler() {}
174
175 virtual ~FileHandler() {}
176
177 /// Update the file handler with information from the header of the bundled
178 /// file.
179 virtual Error ReadHeader(StringRef FC) = 0;
180
181 /// Read the marker of the next bundled to be read in the file. The bundle
182 /// name is returned if there is one in the file, or `std::nullopt` if there
183 /// are no more bundles to be read.
184 virtual Expected<std::optional<StringRef>>
185 ReadBundleStart(StringRef Input) = 0;
186
187 /// Read the marker that closes the current bundle.
188 virtual Error ReadBundleEnd(MemoryBuffer &Input) = 0;
189
190 /// Read the current bundle and write the result into the stream \a OS.
191 virtual Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) = 0;
192
193 /// Write the header of the bundled file to \a OS based on the information
194 /// gathered from \a Inputs.
195 virtual Error WriteHeader(raw_ostream &OS,
196 ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) = 0;
197
198 /// Write the marker that initiates a bundle for the triple \a TargetTriple to
199 /// \a OS.
200 virtual Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) = 0;
201
202 /// Write the marker that closes a bundle for the triple \a TargetTriple to \a
203 /// OS.
204 virtual Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) = 0;
205
206 /// Write the bundle from \a Input into \a OS.
207 virtual Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) = 0;
208
209 /// Finalize output file.
210 virtual Error finalizeOutputFile() { return Error::success(); }
211
212 /// List bundle IDs in \a Input.
213 virtual Error listBundleIDs(MemoryBuffer &Input) {
214 size_t NextBundleStart = 0;
215 StringRef BufferString = Input.getBuffer();
216 while (NextBundleStart != StringRef::npos) {
217
218 // Drop the data that has already been processed/read.
219 BufferString = BufferString.drop_front(NextBundleStart);
220
221 // Read the header.
222 Error Err = ReadHeader(BufferString);
223 if (Err)
224 return Err;
225
226 Err = forEachBundle(BufferString, [&](const BundleInfo &Info) -> Error {
227 llvm::outs() << Info.BundleID << '\n';
228 Error Err = listBundleIDsCallback(Input, Info);
229 if (Err)
230 return Err;
231 return Error::success();
232 });
233
234 if (Err)
235 return Err;
236
237 // Find the beginning of the next Bundle, if it exists.
238 NextBundleStart = BufferString.find(StringRef(OFFLOAD_BUNDLER_MAGIC_STR),
240 }
241 return Error::success();
242 }
243
244 /// Get bundle IDs in \a Input in \a BundleIds.
245 virtual Error getBundleIDs(MemoryBuffer &Input,
246 std::set<StringRef> &BundleIds) {
247
248 if (Error Err = ReadHeader(Input.getBuffer()))
249 return Err;
250 return forEachBundle(Input.getBuffer(),
251 [&](const BundleInfo &Info) -> Error {
252 BundleIds.insert(Info.BundleID);
253 Error Err = listBundleIDsCallback(Input, Info);
254 if (Err)
255 return Err;
256 return Error::success();
257 });
258 }
259
260 /// For each bundle in \a Input, do \a Func.
261 Error forEachBundle(StringRef Input,
262 std::function<Error(const BundleInfo &)> Func) {
263 while (true) {
264 Expected<std::optional<StringRef>> CurTripleOrErr =
265 ReadBundleStart(Input);
266 if (!CurTripleOrErr)
267 return CurTripleOrErr.takeError();
268
269 // No more bundles.
270 if (!*CurTripleOrErr)
271 break;
272
273 StringRef CurTriple = **CurTripleOrErr;
274 assert(!CurTriple.empty());
275
276 BundleInfo Info{CurTriple};
277 if (Error Err = Func(Info))
278 return Err;
279 }
280 return Error::success();
281 }
282
283protected:
284 virtual Error listBundleIDsCallback(MemoryBuffer &Input,
285 const BundleInfo &Info) {
286 return Error::success();
287 }
288};
289
290/// Handler for binary files. The bundled file will have the following format
291/// (all integers are stored in little-endian format):
292///
293/// "OFFLOAD_BUNDLER_MAGIC_STR" (ASCII encoding of the string)
294///
295/// NumberOfOffloadBundles (8-byte integer)
296///
297/// OffsetOfBundle1 (8-byte integer)
298/// SizeOfBundle1 (8-byte integer)
299/// NumberOfBytesInTripleOfBundle1 (8-byte integer)
300/// TripleOfBundle1 (byte length defined before)
301///
302/// ...
303///
304/// OffsetOfBundleN (8-byte integer)
305/// SizeOfBundleN (8-byte integer)
306/// NumberOfBytesInTripleOfBundleN (8-byte integer)
307/// TripleOfBundleN (byte length defined before)
308///
309/// Bundle1
310/// ...
311/// BundleN
312
313/// Read 8-byte integers from a buffer in little-endian format.
314static uint64_t Read8byteIntegerFromBuffer(StringRef Buffer, size_t pos) {
315 return llvm::support::endian::read64le(Buffer.data() + pos);
316}
317
318/// Write 8-byte integers to a buffer in little-endian format.
319static void Write8byteIntegerToBuffer(raw_ostream &OS, uint64_t Val) {
320 llvm::support::endian::write(OS, Val, llvm::endianness::little);
321}
322
323class BinaryFileHandler final : public FileHandler {
324 /// Information about the bundles extracted from the header.
325 struct BinaryBundleInfo final : public BundleInfo {
326 /// Size of the bundle.
327 uint64_t Size = 0u;
328 /// Offset at which the bundle starts in the bundled file.
329 uint64_t Offset = 0u;
330
331 BinaryBundleInfo() {}
332 BinaryBundleInfo(uint64_t Size, uint64_t Offset)
333 : Size(Size), Offset(Offset) {}
334 };
335
336 /// Map between a triple and the corresponding bundle information.
337 StringMap<BinaryBundleInfo> BundlesInfo;
338
339 /// Iterator for the bundle information that is being read.
340 StringMap<BinaryBundleInfo>::iterator CurBundleInfo;
341 StringMap<BinaryBundleInfo>::iterator NextBundleInfo;
342
343 /// Current bundle target to be written.
344 std::string CurWriteBundleTarget;
345
346 /// Configuration options and arrays for this bundler job
347 const OffloadBundlerConfig &BundlerConfig;
348
349public:
350 // TODO: Add error checking from ClangOffloadBundler.cpp
351 BinaryFileHandler(const OffloadBundlerConfig &BC) : BundlerConfig(BC) {}
352
353 ~BinaryFileHandler() final {}
354
355 Error ReadHeader(StringRef FC) final {
356 // Ensure iterators indicate an empty bundle range in case header parsing
357 // exits early.
358 CurBundleInfo = BundlesInfo.end();
359 NextBundleInfo = BundlesInfo.end();
360
361 // Check if buffer is smaller than magic string.
362 size_t ReadChars = sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1;
363 if (ReadChars > FC.size())
364 return Error::success();
365
366 // Check if no magic was found.
367 if (llvm::identify_magic(FC) != llvm::file_magic::offload_bundle)
368 return Error::success();
369
370 // Read number of bundles.
371 if (ReadChars + 8 > FC.size())
372 return Error::success();
373
374 uint64_t NumberOfBundles = Read8byteIntegerFromBuffer(FC, ReadChars);
375 ReadChars += 8;
376
377 // Read bundle offsets, sizes and triples.
378 for (uint64_t i = 0; i < NumberOfBundles; ++i) {
379
380 // Read offset.
381 if (ReadChars + 8 > FC.size())
382 return Error::success();
383
384 uint64_t Offset = Read8byteIntegerFromBuffer(FC, ReadChars);
385 ReadChars += 8;
386
387 // Read size.
388 if (ReadChars + 8 > FC.size())
389 return Error::success();
390
391 uint64_t Size = Read8byteIntegerFromBuffer(FC, ReadChars);
392 ReadChars += 8;
393
394 // Read triple size.
395 if (ReadChars + 8 > FC.size())
396 return Error::success();
397
398 uint64_t TripleSize = Read8byteIntegerFromBuffer(FC, ReadChars);
399 ReadChars += 8;
400
401 // Read triple.
402 if (ReadChars + TripleSize > FC.size())
403 return Error::success();
404
405 StringRef Triple(&FC.data()[ReadChars], TripleSize);
406 ReadChars += TripleSize;
407
408 // Check if the offset and size make sense.
409 if (!Offset || Offset + Size > FC.size())
410 return Error::success();
411
412 BundlesInfo[Triple] = BinaryBundleInfo(Size, Offset);
413 }
414 // Set the iterator to where we will start to read.
415 CurBundleInfo = BundlesInfo.end();
416 NextBundleInfo = BundlesInfo.begin();
417 return Error::success();
418 }
419
420 Expected<std::optional<StringRef>> ReadBundleStart(StringRef Input) final {
421 if (NextBundleInfo == BundlesInfo.end())
422 return std::nullopt;
423 CurBundleInfo = NextBundleInfo++;
424 return CurBundleInfo->first();
425 }
426
427 Error ReadBundleEnd(MemoryBuffer &Input) final {
428 assert(CurBundleInfo != BundlesInfo.end() && "Invalid reader info!");
429 return Error::success();
430 }
431
432 Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
433 assert(CurBundleInfo != BundlesInfo.end() && "Invalid reader info!");
434 StringRef FC = Input.getBuffer();
435 OS.write(FC.data() + CurBundleInfo->second.Offset,
436 CurBundleInfo->second.Size);
437 return Error::success();
438 }
439
440 Error WriteHeader(raw_ostream &OS,
441 ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) final {
442
443 // Compute size of the header.
444 uint64_t HeaderSize = 0;
445
446 HeaderSize += sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1;
447 HeaderSize += 8; // Number of Bundles
448
449 for (auto &T : BundlerConfig.TargetNames) {
450 HeaderSize += 3 * 8; // Bundle offset, Size of bundle and size of triple.
451 HeaderSize += T.size(); // The triple.
452 }
453
454 // Write to the buffer the header.
456
457 Write8byteIntegerToBuffer(OS, BundlerConfig.TargetNames.size());
458
459 unsigned Idx = 0;
460 for (auto &T : BundlerConfig.TargetNames) {
461 MemoryBuffer &MB = *Inputs[Idx++];
462 HeaderSize = alignTo(HeaderSize, BundlerConfig.BundleAlignment);
463 // Bundle offset.
464 Write8byteIntegerToBuffer(OS, HeaderSize);
465 // Size of the bundle (adds to the next bundle's offset)
466 Write8byteIntegerToBuffer(OS, MB.getBufferSize());
467 BundlesInfo[T] = BinaryBundleInfo(MB.getBufferSize(), HeaderSize);
468 HeaderSize += MB.getBufferSize();
469 // Size of the triple
470 Write8byteIntegerToBuffer(OS, T.size());
471 // Triple
472 OS << T;
473 }
474 return Error::success();
475 }
476
477 Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) final {
478 CurWriteBundleTarget = TargetTriple.str();
479 return Error::success();
480 }
481
482 Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) final {
483 return Error::success();
484 }
485
486 Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) final {
487 auto BI = BundlesInfo[CurWriteBundleTarget];
488
489 // Pad with 0 to reach specified offset.
490 size_t CurrentPos = OS.tell();
491 size_t PaddingSize = BI.Offset > CurrentPos ? BI.Offset - CurrentPos : 0;
492 for (size_t I = 0; I < PaddingSize; ++I)
493 OS.write('\0');
494 assert(OS.tell() == BI.Offset);
495
496 OS.write(Input.getBufferStart(), Input.getBufferSize());
497
498 return Error::success();
499 }
500};
501
502// This class implements a list of temporary files that are removed upon
503// object destruction.
504class TempFileHandlerRAII {
505public:
506 ~TempFileHandlerRAII() {
507 for (const auto &File : Files)
508 sys::fs::remove(File);
509 }
510
511 // Creates temporary file with given contents.
512 Expected<StringRef> Create(std::optional<ArrayRef<char>> Contents) {
513 SmallString<128u> File;
514 if (std::error_code EC =
515 sys::fs::createTemporaryFile("clang-offload-bundler", "tmp", File))
516 return createFileError(File, EC);
517 Files.push_front(File);
518
519 if (Contents) {
520 std::error_code EC;
521 raw_fd_ostream OS(File, EC);
522 if (EC)
523 return createFileError(File, EC);
524 OS.write(Contents->data(), Contents->size());
525 }
526 return Files.front().str();
527 }
528
529private:
530 std::forward_list<SmallString<128u>> Files;
531};
532
533/// Handler for object files. The bundles are organized by sections with a
534/// designated name.
535///
536/// To unbundle, we just copy the contents of the designated section.
537class ObjectFileHandler final : public FileHandler {
538
539 /// The object file we are currently dealing with.
540 std::unique_ptr<ObjectFile> Obj;
541
542 /// Return the input file contents.
543 StringRef getInputFileContents() const { return Obj->getData(); }
544
545 /// Return bundle name (<kind>-<triple>) if the provided section is an offload
546 /// section.
547 static Expected<std::optional<StringRef>>
548 IsOffloadSection(SectionRef CurSection) {
549 Expected<StringRef> NameOrErr = CurSection.getName();
550 if (!NameOrErr)
551 return NameOrErr.takeError();
552
553 // If it does not start with the reserved suffix, just skip this section.
554 if (llvm::identify_magic(*NameOrErr) != llvm::file_magic::offload_bundle)
555 return std::nullopt;
556
557 // Return the triple that is right after the reserved prefix.
558 return NameOrErr->substr(sizeof(OFFLOAD_BUNDLER_MAGIC_STR) - 1);
559 }
560
561 /// Total number of inputs.
562 unsigned NumberOfInputs = 0;
563
564 /// Total number of processed inputs, i.e, inputs that were already
565 /// read from the buffers.
566 unsigned NumberOfProcessedInputs = 0;
567
568 /// Iterator of the current and next section.
569 section_iterator CurrentSection;
570 section_iterator NextSection;
571
572 /// Configuration options and arrays for this bundler job
573 const OffloadBundlerConfig &BundlerConfig;
574
575public:
576 // TODO: Add error checking from ClangOffloadBundler.cpp
577 ObjectFileHandler(std::unique_ptr<ObjectFile> ObjIn,
578 const OffloadBundlerConfig &BC)
579 : Obj(std::move(ObjIn)), CurrentSection(Obj->section_begin()),
580 NextSection(Obj->section_begin()), BundlerConfig(BC) {}
581
582 ~ObjectFileHandler() final {}
583
584 Error ReadHeader(StringRef Input) final { return Error::success(); }
585
586 Expected<std::optional<StringRef>> ReadBundleStart(StringRef Input) final {
587 while (NextSection != Obj->section_end()) {
588 CurrentSection = NextSection;
589 ++NextSection;
590
591 // Check if the current section name starts with the reserved prefix. If
592 // so, return the triple.
593 Expected<std::optional<StringRef>> TripleOrErr =
594 IsOffloadSection(*CurrentSection);
595 if (!TripleOrErr)
596 return TripleOrErr.takeError();
597 if (*TripleOrErr)
598 return **TripleOrErr;
599 }
600 return std::nullopt;
601 }
602
603 Error ReadBundleEnd(MemoryBuffer &Input) final { return Error::success(); }
604
605 Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
606 Expected<StringRef> ContentOrErr = CurrentSection->getContents();
607 if (!ContentOrErr)
608 return ContentOrErr.takeError();
609 StringRef Content = *ContentOrErr;
610
611 // Copy fat object contents to the output when extracting host bundle.
612 std::string ModifiedContent;
613 if (Content.size() == 1u && Content.front() == 0) {
614 auto HostBundleOrErr = getHostBundle(
615 StringRef(Input.getBufferStart(), Input.getBufferSize()));
616 if (!HostBundleOrErr)
617 return HostBundleOrErr.takeError();
618
619 ModifiedContent = std::move(*HostBundleOrErr);
620 Content = ModifiedContent;
621 }
622
623 OS.write(Content.data(), Content.size());
624 return Error::success();
625 }
626
627 Error WriteHeader(raw_ostream &OS,
628 ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) final {
629 assert(BundlerConfig.HostInputIndex != ~0u &&
630 "Host input index not defined.");
631
632 // Record number of inputs.
633 NumberOfInputs = Inputs.size();
634 return Error::success();
635 }
636
637 Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) final {
638 ++NumberOfProcessedInputs;
639 return Error::success();
640 }
641
642 Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) final {
643 return Error::success();
644 }
645
646 Error finalizeOutputFile() final {
647 assert(NumberOfProcessedInputs <= NumberOfInputs &&
648 "Processing more inputs that actually exist!");
649 assert(BundlerConfig.HostInputIndex != ~0u &&
650 "Host input index not defined.");
651
652 // If this is not the last output, we don't have to do anything.
653 if (NumberOfProcessedInputs != NumberOfInputs)
654 return Error::success();
655
656 // We will use llvm-objcopy to add target objects sections to the output
657 // fat object. These sections should have 'exclude' flag set which tells
658 // link editor to remove them from linker inputs when linking executable or
659 // shared library.
660
661 assert(BundlerConfig.ObjcopyPath != "" &&
662 "llvm-objcopy path not specified");
663
664 // Temporary files that need to be removed.
665 TempFileHandlerRAII TempFiles;
666
667 // Compose llvm-objcopy command line for add target objects' sections with
668 // appropriate flags.
669 BumpPtrAllocator Alloc;
670 StringSaver SS{Alloc};
671 SmallVector<StringRef, 8u> ObjcopyArgs{"llvm-objcopy"};
672
673 for (unsigned I = 0; I < NumberOfInputs; ++I) {
674 StringRef InputFile = BundlerConfig.InputFileNames[I];
675 if (I == BundlerConfig.HostInputIndex) {
676 // Special handling for the host bundle. We do not need to add a
677 // standard bundle for the host object since we are going to use fat
678 // object as a host object. Therefore use dummy contents (one zero byte)
679 // when creating section for the host bundle.
680 Expected<StringRef> TempFileOrErr = TempFiles.Create(ArrayRef<char>(0));
681 if (!TempFileOrErr)
682 return TempFileOrErr.takeError();
683 InputFile = *TempFileOrErr;
684 }
685
686 ObjcopyArgs.push_back(
687 SS.save(Twine("--add-section=") + OFFLOAD_BUNDLER_MAGIC_STR +
688 BundlerConfig.TargetNames[I] + "=" + InputFile));
689 ObjcopyArgs.push_back(
690 SS.save(Twine("--set-section-flags=") + OFFLOAD_BUNDLER_MAGIC_STR +
691 BundlerConfig.TargetNames[I] + "=readonly,exclude"));
692 }
693 ObjcopyArgs.push_back("--");
694 ObjcopyArgs.push_back(
695 BundlerConfig.InputFileNames[BundlerConfig.HostInputIndex]);
696 ObjcopyArgs.push_back(BundlerConfig.OutputFileNames.front());
697
698 if (Error Err = executeObjcopy(BundlerConfig.ObjcopyPath, ObjcopyArgs))
699 return Err;
700
701 return Error::success();
702 }
703
704 Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) final {
705 return Error::success();
706 }
707
708private:
709 Error executeObjcopy(StringRef Objcopy, ArrayRef<StringRef> Args) {
710 // If the user asked for the commands to be printed out, we do that
711 // instead of executing it.
712 if (BundlerConfig.PrintExternalCommands) {
713 errs() << "\"" << Objcopy << "\"";
714 for (StringRef Arg : drop_begin(Args, 1))
715 errs() << " \"" << Arg << "\"";
716 errs() << "\n";
717 } else {
718 if (sys::ExecuteAndWait(Objcopy, Args))
719 return createStringError(inconvertibleErrorCode(),
720 "'llvm-objcopy' tool failed");
721 }
722 return Error::success();
723 }
724
725 Expected<std::string> getHostBundle(StringRef Input) {
726 TempFileHandlerRAII TempFiles;
727
728 auto ModifiedObjPathOrErr = TempFiles.Create(std::nullopt);
729 if (!ModifiedObjPathOrErr)
730 return ModifiedObjPathOrErr.takeError();
731 StringRef ModifiedObjPath = *ModifiedObjPathOrErr;
732
733 BumpPtrAllocator Alloc;
734 StringSaver SS{Alloc};
735 SmallVector<StringRef, 16> ObjcopyArgs{"llvm-objcopy"};
736
737 ObjcopyArgs.push_back("--regex");
738 ObjcopyArgs.push_back("--remove-section=__CLANG_OFFLOAD_BUNDLE__.*");
739 ObjcopyArgs.push_back("--");
740
741 StringRef ObjcopyInputFileName;
742 // When unbundling an archive, the content of each object file in the
743 // archive is passed to this function by parameter Input, which is different
744 // from the content of the original input archive file, therefore it needs
745 // to be saved to a temporary file before passed to llvm-objcopy. Otherwise,
746 // Input is the same as the content of the original input file, therefore
747 // temporary file is not needed.
748 if (StringRef(BundlerConfig.FilesType).starts_with("a")) {
749 auto InputFileOrErr = TempFiles.Create(ArrayRef<char>(Input));
750 if (!InputFileOrErr)
751 return InputFileOrErr.takeError();
752 ObjcopyInputFileName = *InputFileOrErr;
753 } else
754 ObjcopyInputFileName = BundlerConfig.InputFileNames.front();
755
756 ObjcopyArgs.push_back(ObjcopyInputFileName);
757 ObjcopyArgs.push_back(ModifiedObjPath);
758
759 if (Error Err = executeObjcopy(BundlerConfig.ObjcopyPath, ObjcopyArgs))
760 return std::move(Err);
761
762 auto BufOrErr = MemoryBuffer::getFile(ModifiedObjPath);
763 if (!BufOrErr)
764 return createStringError(BufOrErr.getError(),
765 "Failed to read back the modified object file");
766
767 return BufOrErr->get()->getBuffer().str();
768 }
769};
770
771/// Handler for text files. The bundled file will have the following format.
772///
773/// "Comment OFFLOAD_BUNDLER_MAGIC_STR__START__ triple"
774/// Bundle 1
775/// "Comment OFFLOAD_BUNDLER_MAGIC_STR__END__ triple"
776/// ...
777/// "Comment OFFLOAD_BUNDLER_MAGIC_STR__START__ triple"
778/// Bundle N
779/// "Comment OFFLOAD_BUNDLER_MAGIC_STR__END__ triple"
780class TextFileHandler final : public FileHandler {
781 /// String that begins a line comment.
782 StringRef Comment;
783
784 /// String that initiates a bundle.
785 std::string BundleStartString;
786
787 /// String that closes a bundle.
788 std::string BundleEndString;
789
790 /// Number of chars read from input.
791 size_t ReadChars = 0u;
792
793protected:
794 Error ReadHeader(StringRef Input) final { return Error::success(); }
795
796 Expected<std::optional<StringRef>> ReadBundleStart(StringRef FC) final {
797
798 // Find start of the bundle.
799 ReadChars = FC.find(BundleStartString, ReadChars);
800 if (ReadChars == FC.npos)
801 return std::nullopt;
802
803 // Get position of the triple.
804 size_t TripleStart = ReadChars = ReadChars + BundleStartString.size();
805
806 // Get position that closes the triple.
807 size_t TripleEnd = ReadChars = FC.find("\n", ReadChars);
808 if (TripleEnd == FC.npos)
809 return std::nullopt;
810
811 // Next time we read after the new line.
812 ++ReadChars;
813
814 return StringRef(&FC.data()[TripleStart], TripleEnd - TripleStart);
815 }
816
817 Error ReadBundleEnd(MemoryBuffer &Input) final {
818 StringRef FC = Input.getBuffer();
819
820 // Read up to the next new line.
821 assert(FC[ReadChars] == '\n' && "The bundle should end with a new line.");
822
823 size_t TripleEnd = ReadChars = FC.find("\n", ReadChars + 1);
824 if (TripleEnd != FC.npos)
825 // Next time we read after the new line.
826 ++ReadChars;
827
828 return Error::success();
829 }
830
831 Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
832 StringRef FC = Input.getBuffer();
833 size_t BundleStart = ReadChars;
834
835 // Find end of the bundle.
836 size_t BundleEnd = ReadChars = FC.find(BundleEndString, ReadChars);
837
838 StringRef Bundle(&FC.data()[BundleStart], BundleEnd - BundleStart);
839 OS << Bundle;
840
841 return Error::success();
842 }
843
844 Error WriteHeader(raw_ostream &OS,
845 ArrayRef<std::unique_ptr<MemoryBuffer>> Inputs) final {
846 return Error::success();
847 }
848
849 Error WriteBundleStart(raw_ostream &OS, StringRef TargetTriple) final {
850 OS << BundleStartString << TargetTriple << "\n";
851 return Error::success();
852 }
853
854 Error WriteBundleEnd(raw_ostream &OS, StringRef TargetTriple) final {
855 OS << BundleEndString << TargetTriple << "\n";
856 return Error::success();
857 }
858
859 Error WriteBundle(raw_ostream &OS, MemoryBuffer &Input) final {
860 OS << Input.getBuffer();
861 return Error::success();
862 }
863
864public:
865 TextFileHandler(StringRef Comment) : Comment(Comment), ReadChars(0) {
866 BundleStartString =
867 "\n" + Comment.str() + " " OFFLOAD_BUNDLER_MAGIC_STR "__START__ ";
868 BundleEndString =
869 "\n" + Comment.str() + " " OFFLOAD_BUNDLER_MAGIC_STR "__END__ ";
870 }
871
872 Error listBundleIDsCallback(MemoryBuffer &Input,
873 const BundleInfo &Info) final {
874 // TODO: To list bundle IDs in a bundled text file we need to go through
875 // all bundles. The format of bundled text file may need to include a
876 // header if the performance of listing bundle IDs of bundled text file is
877 // important.
878 ReadChars = Input.getBuffer().find(BundleEndString, ReadChars);
879 if (Error Err = ReadBundleEnd(Input))
880 return Err;
881 return Error::success();
882 }
883};
884} // namespace
885
886/// Return an appropriate object file handler. We use the specific object
887/// handler if we know how to deal with that format, otherwise we use a default
888/// binary file handler.
889static std::unique_ptr<FileHandler>
890CreateObjectFileHandler(MemoryBuffer &FirstInput,
891 const OffloadBundlerConfig &BundlerConfig) {
892 // Check if the input file format is one that we know how to deal with.
893 Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary(FirstInput);
894
895 // We only support regular object files. If failed to open the input as a
896 // known binary or this is not an object file use the default binary handler.
897 if (errorToBool(BinaryOrErr.takeError()) || !isa<ObjectFile>(*BinaryOrErr))
898 return std::make_unique<BinaryFileHandler>(BundlerConfig);
899
900 // Otherwise create an object file handler. The handler will be owned by the
901 // client of this function.
902 return std::make_unique<ObjectFileHandler>(
903 std::unique_ptr<ObjectFile>(cast<ObjectFile>(BinaryOrErr->release())),
904 BundlerConfig);
905}
906
907/// Return an appropriate handler given the input files and options.
909CreateFileHandler(MemoryBuffer &FirstInput,
910 const OffloadBundlerConfig &BundlerConfig) {
911 std::string FilesType = BundlerConfig.FilesType;
912
913 if (FilesType == "i" || FilesType == "ii" || FilesType == "cui" ||
914 FilesType == "hipi")
915 return std::make_unique<TextFileHandler>(/*Comment=*/"//");
916 // TODO: `.d` should be eventually removed once `-M` and its variants are
917 // handled properly in offload compilation.
918 if (FilesType == "d" || FilesType == "s")
919 return std::make_unique<TextFileHandler>(/*Comment=*/"#");
920 if (FilesType == "ll")
921 return std::make_unique<TextFileHandler>(/*Comment=*/";");
922 if (FilesType == "bc" || FilesType == "gch" || FilesType == "ast")
923 return std::make_unique<BinaryFileHandler>(BundlerConfig);
924 if (FilesType == "o" || FilesType == "a")
925 return CreateObjectFileHandler(FirstInput, BundlerConfig);
926
927 return createStringError(errc::invalid_argument,
928 "'" + FilesType + "': invalid file type specified");
929}
930
932 : CompressedBundleVersion(CompressedOffloadBundle::DefaultVersion) {
933 if (llvm::compression::zstd::isAvailable()) {
934 CompressionFormat = llvm::compression::Format::Zstd;
935 // Compression level 3 is usually sufficient for zstd since long distance
936 // matching is enabled.
938 } else if (llvm::compression::zlib::isAvailable()) {
939 CompressionFormat = llvm::compression::Format::Zlib;
940 // Use default level for zlib since higher level does not have significant
941 // improvement.
942 CompressionLevel = llvm::compression::zlib::DefaultCompression;
943 }
944 auto IgnoreEnvVarOpt =
945 llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_IGNORE_ENV_VAR");
946 if (IgnoreEnvVarOpt.has_value() && IgnoreEnvVarOpt.value() == "1")
947 return;
948 auto VerboseEnvVarOpt = llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_VERBOSE");
949 if (VerboseEnvVarOpt.has_value())
950 Verbose = VerboseEnvVarOpt.value() == "1";
951 auto CompressEnvVarOpt =
952 llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_COMPRESS");
953 if (CompressEnvVarOpt.has_value())
954 Compress = CompressEnvVarOpt.value() == "1";
955 auto CompressionLevelEnvVarOpt =
956 llvm::sys::Process::GetEnv("OFFLOAD_BUNDLER_COMPRESSION_LEVEL");
957 if (CompressionLevelEnvVarOpt.has_value()) {
958 llvm::StringRef CompressionLevelStr = CompressionLevelEnvVarOpt.value();
959 int Level;
960 if (!CompressionLevelStr.getAsInteger(10, Level))
961 CompressionLevel = Level;
962 else
963 llvm::errs()
964 << "Warning: Invalid value for OFFLOAD_BUNDLER_COMPRESSION_LEVEL: "
965 << CompressionLevelStr.str() << ". Ignoring it.\n";
966 }
967 auto CompressedBundleFormatVersionOpt =
968 llvm::sys::Process::GetEnv("COMPRESSED_BUNDLE_FORMAT_VERSION");
969 if (CompressedBundleFormatVersionOpt.has_value()) {
970 llvm::StringRef VersionStr = CompressedBundleFormatVersionOpt.value();
971 uint16_t Version;
972 if (!VersionStr.getAsInteger(10, Version)) {
973 if (Version >= 2 && Version <= 3)
974 CompressedBundleVersion = Version;
975 else
976 llvm::errs()
977 << "Warning: Invalid value for COMPRESSED_BUNDLE_FORMAT_VERSION: "
978 << VersionStr.str()
979 << ". Valid values are 2 or 3. Using default version "
980 << CompressedBundleVersion << ".\n";
981 } else
982 llvm::errs()
983 << "Warning: Invalid value for COMPRESSED_BUNDLE_FORMAT_VERSION: "
984 << VersionStr.str() << ". Using default version "
985 << CompressedBundleVersion << ".\n";
986 }
987}
988
989// Returns the on-disk size recorded in the compressed offload bundle header at
990// the start of \p Blob, or std::nullopt if the header carries no size field.
991static std::optional<size_t> getCompressedBundleSize(StringRef Blob) {
993 CompressedOffloadBundle::CompressedBundleHeader::tryParse(Blob);
994 if (!HeaderOrErr) {
995 consumeError(HeaderOrErr.takeError());
996 return std::nullopt;
997 }
998 return HeaderOrErr->FileSize;
999}
1000
1001// List bundle IDs. Return true if an error was found.
1003 StringRef InputFileName, const OffloadBundlerConfig &BundlerConfig) {
1004
1005 size_t Offset = 0;
1006 size_t NextBundleStart = 0;
1007 std::unique_ptr<MemoryBuffer> Buffer;
1008
1009 // Open Input file.
1010 ErrorOr<std::unique_ptr<MemoryBuffer>> Contents =
1011 MemoryBuffer::getFileOrSTDIN(InputFileName, /*IsText=*/true);
1012 if (std::error_code EC = Contents.getError())
1013 return createFileError(InputFileName, EC);
1014
1015 // There may be multiple bundles.
1016 while ((NextBundleStart != StringRef::npos) &&
1017 (Offset < (**Contents).getBufferSize())) {
1018 Buffer = MemoryBuffer::getMemBuffer(
1019 (**Contents).getBuffer().drop_front(Offset), "",
1020 /*RequiresNullTerminator=*/false);
1021
1022 size_t CurBundleEnd = StringRef::npos;
1023 if (identify_magic((*Buffer).getBuffer()) ==
1024 file_magic::offload_bundle_compressed) {
1025 // Locate this bundle's end and the next bundle from the header size.
1026 if (std::optional<size_t> Size =
1027 getCompressedBundleSize((*Buffer).getBuffer())) {
1028 CurBundleEnd = *Size;
1029 NextBundleStart = (*Buffer).getBuffer().find("CCOB", *Size);
1030 } else {
1031 // Legacy bundle without a recorded size: fall back to magic scanning.
1032 NextBundleStart = (*Buffer).getBuffer().find("CCOB", 4);
1033 CurBundleEnd = NextBundleStart;
1034 }
1035 } else
1036 NextBundleStart = StringRef::npos;
1037
1038 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
1039 MemoryBuffer::getMemBuffer(
1040 (*Buffer).getBuffer().take_front(CurBundleEnd),
1041 InputFileName, // FileName,
1042 false);
1043 if (std::error_code EC = CodeOrErr.getError())
1044 return createFileError(InputFileName, EC);
1045
1046 // Decompress the input if necessary.
1047 Expected<std::unique_ptr<MemoryBuffer>> DecompressedBufferOrErr =
1048 CompressedOffloadBundle::decompress(
1049 **CodeOrErr, BundlerConfig.Verbose ? &llvm::errs() : nullptr);
1050 if (!DecompressedBufferOrErr)
1051 return createStringError(
1052 inconvertibleErrorCode(),
1053 "Failed to decompress input: " +
1054 llvm::toString(DecompressedBufferOrErr.takeError()));
1055
1056 MemoryBuffer &DecompressedInput = **DecompressedBufferOrErr;
1057
1058 // Select the right files handler.
1059 Expected<std::unique_ptr<FileHandler>> FileHandlerOrErr =
1060 CreateFileHandler(DecompressedInput, BundlerConfig);
1061 if (!FileHandlerOrErr)
1062 return FileHandlerOrErr.takeError();
1063 std::unique_ptr<FileHandler> &FH = *FileHandlerOrErr;
1064 assert(FH);
1065 Error E = FH->listBundleIDs(DecompressedInput);
1066 if (E)
1067 return E;
1068
1069 if (NextBundleStart != StringRef::npos)
1070 Offset += NextBundleStart;
1071 }
1072 return Error::success();
1073}
1074
1075/// @brief Checks if a code object \p CodeObjectInfo is compatible with a given
1076/// target \p TargetInfo.
1077/// @link https://clang.llvm.org/docs/ClangOffloadBundler.html#bundle-entry-id
1080
1081 // Compatible in case of exact match.
1082 if (CodeObjectInfo == TargetInfo) {
1083 DEBUG_WITH_TYPE("CodeObjectCompatibility",
1084 dbgs() << "Compatible: Exact match: \t[CodeObject: "
1085 << CodeObjectInfo.str()
1086 << "]\t:\t[Target: " << TargetInfo.str() << "]\n");
1087 return true;
1088 }
1089
1090 // Incompatible if Kinds or Triples mismatch.
1091 if (!CodeObjectInfo.isOffloadKindCompatible(TargetInfo.OffloadKind) ||
1092 !CodeObjectInfo.Triple.isCompatibleWith(TargetInfo.Triple)) {
1093 DEBUG_WITH_TYPE(
1094 "CodeObjectCompatibility",
1095 dbgs() << "Incompatible: Kind/Triple mismatch \t[CodeObject: "
1096 << CodeObjectInfo.str() << "]\t:\t[Target: " << TargetInfo.str()
1097 << "]\n");
1098 return false;
1099 }
1100
1101 // Incompatible if Processors mismatch.
1102 llvm::StringMap<bool> CodeObjectFeatureMap, TargetFeatureMap;
1103 std::optional<StringRef> CodeObjectProc = clang::parseTargetID(
1104 CodeObjectInfo.Triple, CodeObjectInfo.TargetID, &CodeObjectFeatureMap);
1105 std::optional<StringRef> TargetProc = clang::parseTargetID(
1106 TargetInfo.Triple, TargetInfo.TargetID, &TargetFeatureMap);
1107
1108 // Both TargetProc and CodeObjectProc can't be empty here.
1109 if (!TargetProc || !CodeObjectProc ||
1110 CodeObjectProc.value() != TargetProc.value()) {
1111 DEBUG_WITH_TYPE("CodeObjectCompatibility",
1112 dbgs() << "Incompatible: Processor mismatch \t[CodeObject: "
1113 << CodeObjectInfo.str()
1114 << "]\t:\t[Target: " << TargetInfo.str() << "]\n");
1115 return false;
1116 }
1117
1118 // Incompatible if CodeObject has more features than Target, irrespective of
1119 // type or sign of features.
1120 if (CodeObjectFeatureMap.getNumItems() > TargetFeatureMap.getNumItems()) {
1121 DEBUG_WITH_TYPE("CodeObjectCompatibility",
1122 dbgs() << "Incompatible: CodeObject has more features "
1123 "than target \t[CodeObject: "
1124 << CodeObjectInfo.str()
1125 << "]\t:\t[Target: " << TargetInfo.str() << "]\n");
1126 return false;
1127 }
1128
1129 // Compatible if each target feature specified by target is compatible with
1130 // target feature of code object. The target feature is compatible if the
1131 // code object does not specify it (meaning Any), or if it specifies it
1132 // with the same value (meaning On or Off).
1133 for (const auto &CodeObjectFeature : CodeObjectFeatureMap) {
1134 auto TargetFeature = TargetFeatureMap.find(CodeObjectFeature.getKey());
1135 if (TargetFeature == TargetFeatureMap.end()) {
1136 DEBUG_WITH_TYPE(
1137 "CodeObjectCompatibility",
1138 dbgs()
1139 << "Incompatible: Value of CodeObject's non-ANY feature is "
1140 "not matching with Target feature's ANY value \t[CodeObject: "
1141 << CodeObjectInfo.str() << "]\t:\t[Target: " << TargetInfo.str()
1142 << "]\n");
1143 return false;
1144 } else if (TargetFeature->getValue() != CodeObjectFeature.getValue()) {
1145 DEBUG_WITH_TYPE(
1146 "CodeObjectCompatibility",
1147 dbgs() << "Incompatible: Value of CodeObject's non-ANY feature is "
1148 "not matching with Target feature's non-ANY value "
1149 "\t[CodeObject: "
1150 << CodeObjectInfo.str()
1151 << "]\t:\t[Target: " << TargetInfo.str() << "]\n");
1152 return false;
1153 }
1154 }
1155
1156 // CodeObject is compatible if all features of Target are:
1157 // - either, present in the Code Object's features map with the same sign,
1158 // - or, the feature is missing from CodeObjects's features map i.e. it is
1159 // set to ANY
1160 DEBUG_WITH_TYPE(
1161 "CodeObjectCompatibility",
1162 dbgs() << "Compatible: Target IDs are compatible \t[CodeObject: "
1163 << CodeObjectInfo.str() << "]\t:\t[Target: " << TargetInfo.str()
1164 << "]\n");
1165 return true;
1166}
1167
1168/// Bundle the files. Return true if an error was found.
1170 std::error_code EC;
1171
1172 // Create a buffer to hold the content before compressing.
1173 SmallVector<char, 0> Buffer;
1174 llvm::raw_svector_ostream BufferStream(Buffer);
1175
1176 // Open input files.
1178 InputBuffers.reserve(BundlerConfig.InputFileNames.size());
1179 for (auto &I : BundlerConfig.InputFileNames) {
1180 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
1181 MemoryBuffer::getFileOrSTDIN(I, /*IsText=*/true);
1182 if (std::error_code EC = CodeOrErr.getError())
1183 return createFileError(I, EC);
1184 InputBuffers.emplace_back(std::move(*CodeOrErr));
1185 }
1186
1187 // Get the file handler. We use the host buffer as reference.
1188 assert((BundlerConfig.HostInputIndex != ~0u || BundlerConfig.AllowNoHost) &&
1189 "Host input index undefined??");
1191 *InputBuffers[BundlerConfig.AllowNoHost ? 0
1192 : BundlerConfig.HostInputIndex],
1194 if (!FileHandlerOrErr)
1195 return FileHandlerOrErr.takeError();
1196
1197 std::unique_ptr<FileHandler> &FH = *FileHandlerOrErr;
1198 assert(FH);
1199
1200 // Write header.
1201 if (Error Err = FH->WriteHeader(BufferStream, InputBuffers))
1202 return Err;
1203
1204 // Write all bundles along with the start/end markers. If an error was found
1205 // writing the end of the bundle component, abort the bundle writing.
1206 auto Input = InputBuffers.begin();
1207 for (auto &Triple : BundlerConfig.TargetNames) {
1208 if (Error Err = FH->WriteBundleStart(BufferStream, Triple))
1209 return Err;
1210 if (Error Err = FH->WriteBundle(BufferStream, **Input))
1211 return Err;
1212 if (Error Err = FH->WriteBundleEnd(BufferStream, Triple))
1213 return Err;
1214 ++Input;
1215 }
1216
1217 raw_fd_ostream OutputFile(BundlerConfig.OutputFileNames.front(), EC,
1218 sys::fs::OF_None);
1219 if (EC)
1220 return createFileError(BundlerConfig.OutputFileNames.front(), EC);
1221
1222 SmallVector<char, 0> CompressedBuffer;
1223 if (BundlerConfig.Compress) {
1224 std::unique_ptr<llvm::MemoryBuffer> BufferMemory =
1225 llvm::MemoryBuffer::getMemBufferCopy(
1226 llvm::StringRef(Buffer.data(), Buffer.size()));
1227 auto CompressionResult = CompressedOffloadBundle::compress(
1228 {BundlerConfig.CompressionFormat, BundlerConfig.CompressionLevel,
1229 /*zstdEnableLdm=*/true},
1230 *BufferMemory, BundlerConfig.CompressedBundleVersion,
1231 BundlerConfig.Verbose ? &llvm::errs() : nullptr);
1232 if (auto Error = CompressionResult.takeError())
1233 return Error;
1234
1235 auto CompressedMemBuffer = std::move(CompressionResult.get());
1236 CompressedBuffer.assign(CompressedMemBuffer->getBufferStart(),
1237 CompressedMemBuffer->getBufferEnd());
1238 } else
1239 CompressedBuffer = std::move(Buffer);
1240
1241 OutputFile.write(CompressedBuffer.data(), CompressedBuffer.size());
1242
1243 return FH->finalizeOutputFile();
1244}
1245
1246// Unbundle the files. Return true if an error was found.
1248 // Open Input file.
1249 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
1250 MemoryBuffer::getFileOrSTDIN(BundlerConfig.InputFileNames.front(),
1251 /*IsText=*/true);
1252 if (std::error_code EC = CodeOrErr.getError())
1253 return createFileError(BundlerConfig.InputFileNames.front(), EC);
1254
1255 // Create a work list that consist of the map triple/output file.
1256 StringMap<StringRef> Worklist;
1257 auto Output = BundlerConfig.OutputFileNames.begin();
1258 for (auto &Triple : BundlerConfig.TargetNames) {
1259 if (!checkOffloadBundleID(Triple))
1260 return createStringError(errc::invalid_argument,
1261 "invalid bundle id from bundle config");
1262 Worklist[Triple] = *Output;
1263 ++Output;
1264 }
1265
1266 // The input may contain multiple concatenated fat binary blobs (e.g. when
1267 // the linker merges .hip_fatbin sections from multiple TUs into one). Walk
1268 // through each blob exactly as ListBundleIDsInFile does, draining worklist
1269 // entries as matching targets are found.
1270 bool FoundHostBundle = false;
1271 size_t Offset = 0;
1272 size_t NextBundleStart = 0;
1273 std::unique_ptr<MemoryBuffer> Buffer;
1274
1275 while ((NextBundleStart != StringRef::npos) &&
1276 (Offset < (**CodeOrErr).getBufferSize())) {
1277
1278 Buffer = MemoryBuffer::getMemBuffer(
1279 (**CodeOrErr).getBuffer().drop_front(Offset), "",
1280 /*RequiresNullTerminator=*/false);
1281
1282 size_t CurBundleEnd = StringRef::npos;
1283 if (identify_magic((*Buffer).getBuffer()) ==
1284 file_magic::offload_bundle_compressed) {
1285 // Locate this bundle's end and the next bundle from the header size.
1286 if (std::optional<size_t> Size =
1287 getCompressedBundleSize((*Buffer).getBuffer())) {
1288 CurBundleEnd = *Size;
1289 NextBundleStart = (*Buffer).getBuffer().find("CCOB", *Size);
1290 } else {
1291 // Legacy bundle without a recorded size: fall back to magic scanning.
1292 NextBundleStart = (*Buffer).getBuffer().find("CCOB", 4);
1293 CurBundleEnd = NextBundleStart;
1294 }
1295 } else if (identify_magic((*Buffer).getBuffer()) ==
1296 file_magic::offload_bundle) {
1297 NextBundleStart = (*Buffer).getBuffer().find(
1299 CurBundleEnd = NextBundleStart;
1300 } else
1301 NextBundleStart = StringRef::npos;
1302
1303 ErrorOr<std::unique_ptr<MemoryBuffer>> BlobOrErr =
1304 MemoryBuffer::getMemBuffer(
1305 (*Buffer).getBuffer().take_front(CurBundleEnd),
1306 BundlerConfig.InputFileNames.front(),
1307 /*RequiresNullTerminator=*/false);
1308 if (std::error_code EC = BlobOrErr.getError())
1309 return createFileError(BundlerConfig.InputFileNames.front(), EC);
1310
1311 // Decompress the blob if necessary.
1312 Expected<std::unique_ptr<MemoryBuffer>> DecompressedBufferOrErr =
1313 CompressedOffloadBundle::decompress(
1314 **BlobOrErr, BundlerConfig.Verbose ? &llvm::errs() : nullptr);
1315 if (!DecompressedBufferOrErr)
1316 return createStringError(
1317 inconvertibleErrorCode(),
1318 "Failed to decompress input: " +
1319 llvm::toString(DecompressedBufferOrErr.takeError()));
1320
1321 MemoryBuffer &Input = **DecompressedBufferOrErr;
1322
1323 // Select the right file handler for this blob.
1324 Expected<std::unique_ptr<FileHandler>> FileHandlerOrErr =
1326 if (!FileHandlerOrErr)
1327 return FileHandlerOrErr.takeError();
1328
1329 std::unique_ptr<FileHandler> &FH = *FileHandlerOrErr;
1330 assert(FH);
1331
1332 // Read the header of this blob.
1333 if (Error Err = FH->ReadHeader(Input.getBuffer()))
1334 return Err;
1335
1336 // Drain worklist entries satisfied by this blob.
1337 while (!Worklist.empty()) {
1338 Expected<std::optional<StringRef>> CurTripleOrErr =
1339 FH->ReadBundleStart(Input.getBuffer());
1340 if (!CurTripleOrErr)
1341 return CurTripleOrErr.takeError();
1342
1343 // No more bundles in this blob.
1344 if (!*CurTripleOrErr)
1345 break;
1346
1347 StringRef CurTriple = **CurTripleOrErr;
1348 assert(!CurTriple.empty());
1349 if (!checkOffloadBundleID(CurTriple))
1350 return createStringError(errc::invalid_argument,
1351 "invalid bundle id read from the bundle");
1352
1353 auto Output = Worklist.begin();
1354 for (auto E = Worklist.end(); Output != E; Output++) {
1356 OffloadTargetInfo(CurTriple, BundlerConfig),
1357 OffloadTargetInfo((*Output).first(), BundlerConfig)))
1358 break;
1359 }
1360
1361 if (Output == Worklist.end())
1362 continue;
1363
1364 // Check if the output file can be opened and copy the bundle to it.
1365 std::error_code EC;
1366 raw_fd_ostream OutputFile((*Output).second, EC, sys::fs::OF_None);
1367 if (EC)
1368 return createFileError((*Output).second, EC);
1369 if (Error Err = FH->ReadBundle(OutputFile, Input))
1370 return Err;
1371 if (Error Err = FH->ReadBundleEnd(Input))
1372 return Err;
1373 Worklist.erase(Output);
1374
1375 // Record if we found the host bundle.
1376 auto OffloadInfo = OffloadTargetInfo(CurTriple, BundlerConfig);
1377 if (OffloadInfo.hasHostKind())
1378 FoundHostBundle = true;
1379 }
1380
1381 if (NextBundleStart != StringRef::npos)
1382 Offset += NextBundleStart;
1383 }
1384
1385 if (!BundlerConfig.AllowMissingBundles && !Worklist.empty()) {
1386 std::string ErrMsg = "Can't find bundles for";
1387 std::set<StringRef> Sorted;
1388 for (auto &E : Worklist)
1389 Sorted.insert(E.first());
1390 unsigned I = 0;
1391 unsigned Last = Sorted.size() - 1;
1392 for (auto &E : Sorted) {
1393 if (I != 0 && Last > 1)
1394 ErrMsg += ",";
1395 ErrMsg += " ";
1396 if (I == Last && I != 0)
1397 ErrMsg += "and ";
1398 ErrMsg += E.str();
1399 ++I;
1400 }
1401 return createStringError(inconvertibleErrorCode(), ErrMsg);
1402 }
1403
1404 // If no bundles were found, assume the input file is the host bundle and
1405 // create empty files for the remaining targets.
1406 if (Worklist.size() == BundlerConfig.TargetNames.size()) {
1407 for (auto &E : Worklist) {
1408 std::error_code EC;
1409 raw_fd_ostream OutputFile(E.second, EC, sys::fs::OF_None);
1410 if (EC)
1411 return createFileError(E.second, EC);
1412
1413 // If this entry has a host kind, copy the input file to the output file.
1414 // We don't need to check E.getKey() here through checkOffloadBundleID
1415 // because the entire WorkList has been checked above.
1416 auto OffloadInfo = OffloadTargetInfo(E.getKey(), BundlerConfig);
1417 if (OffloadInfo.hasHostKind())
1418 OutputFile.write((**CodeOrErr).getBufferStart(),
1419 (**CodeOrErr).getBufferSize());
1420 }
1421 return Error::success();
1422 }
1423
1424 // If we found elements, we emit an error if none of those were for the host
1425 // in case host bundle name was provided in command line.
1426 if (!(FoundHostBundle || BundlerConfig.HostInputIndex == ~0u ||
1427 BundlerConfig.AllowMissingBundles))
1428 return createStringError(inconvertibleErrorCode(),
1429 "Can't find bundle for the host target");
1430
1431 // If we still have any elements in the worklist, create empty files for them.
1432 for (auto &E : Worklist) {
1433 std::error_code EC;
1434 raw_fd_ostream OutputFile(E.second, EC, sys::fs::OF_None);
1435 if (EC)
1436 return createFileError(E.second, EC);
1437 }
1438
1439 return Error::success();
1440}
1441
1442static Archive::Kind getDefaultArchiveKindForHost() {
1443 return Triple(sys::getDefaultTargetTriple()).isOSDarwin() ? Archive::K_DARWIN
1444 : Archive::K_GNU;
1445}
1446
1447/// @brief Computes a list of targets among all given targets which are
1448/// compatible with this code object
1449/// @param [in] CodeObjectInfo Code Object
1450/// @param [out] CompatibleTargets List of all compatible targets among all
1451/// given targets
1452/// @return false, if no compatible target is found.
1453static bool
1455 SmallVectorImpl<StringRef> &CompatibleTargets,
1456 const OffloadBundlerConfig &BundlerConfig) {
1457 if (!CompatibleTargets.empty()) {
1458 DEBUG_WITH_TYPE("CodeObjectCompatibility",
1459 dbgs() << "CompatibleTargets list should be empty\n");
1460 return false;
1461 }
1462 for (auto &Target : BundlerConfig.TargetNames) {
1463 auto TargetInfo = OffloadTargetInfo(Target, BundlerConfig);
1464 if (isCodeObjectCompatible(CodeObjectInfo, TargetInfo))
1465 CompatibleTargets.push_back(Target);
1466 }
1467 return !CompatibleTargets.empty();
1468}
1469
1470// Check that each code object file in the input archive conforms to following
1471// rule: for a specific processor, a feature either shows up in all target IDs,
1472// or does not show up in any target IDs. Otherwise the target ID combination is
1473// invalid.
1474static Error
1475CheckHeterogeneousArchive(StringRef ArchiveName,
1476 const OffloadBundlerConfig &BundlerConfig) {
1477 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
1478 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1479 MemoryBuffer::getFileOrSTDIN(ArchiveName, true, false);
1480 if (std::error_code EC = BufOrErr.getError())
1481 return createFileError(ArchiveName, EC);
1482
1483 ArchiveBuffers.push_back(std::move(*BufOrErr));
1485 Archive::create(ArchiveBuffers.back()->getMemBufferRef());
1486 if (!LibOrErr)
1487 return LibOrErr.takeError();
1488
1489 auto Archive = std::move(*LibOrErr);
1490
1491 Error ArchiveErr = Error::success();
1492 auto ChildEnd = Archive->child_end();
1493
1494 /// Iterate over all bundled code object files in the input archive.
1495 for (auto ArchiveIter = Archive->child_begin(ArchiveErr);
1496 ArchiveIter != ChildEnd; ++ArchiveIter) {
1497 if (ArchiveErr)
1498 return ArchiveErr;
1499 auto ArchiveChildNameOrErr = (*ArchiveIter).getName();
1500 if (!ArchiveChildNameOrErr)
1501 return ArchiveChildNameOrErr.takeError();
1502
1503 auto CodeObjectBufferRefOrErr = (*ArchiveIter).getMemoryBufferRef();
1504 if (!CodeObjectBufferRefOrErr)
1505 return CodeObjectBufferRefOrErr.takeError();
1506
1507 auto CodeObjectBuffer =
1508 MemoryBuffer::getMemBuffer(*CodeObjectBufferRefOrErr, false);
1509
1510 Expected<std::unique_ptr<FileHandler>> FileHandlerOrErr =
1511 CreateFileHandler(*CodeObjectBuffer, BundlerConfig);
1512 if (!FileHandlerOrErr)
1513 return FileHandlerOrErr.takeError();
1514
1515 std::unique_ptr<FileHandler> &FileHandler = *FileHandlerOrErr;
1516 assert(FileHandler);
1517
1518 std::set<StringRef> BundleIds;
1519 auto CodeObjectFileError =
1520 FileHandler->getBundleIDs(*CodeObjectBuffer, BundleIds);
1521 if (CodeObjectFileError)
1522 return CodeObjectFileError;
1523
1524 auto &&ConflictingArchs = clang::getConflictTargetIDCombination(BundleIds);
1525 if (ConflictingArchs) {
1526 std::string ErrMsg =
1527 Twine("conflicting TargetIDs [" + ConflictingArchs.value().first +
1528 ", " + ConflictingArchs.value().second + "] found in " +
1529 ArchiveChildNameOrErr.get() + " of " + ArchiveName)
1530 .str();
1531 return createStringError(inconvertibleErrorCode(), ErrMsg);
1532 }
1533 }
1534
1535 return ArchiveErr;
1536}
1537
1538/// UnbundleArchive takes an archive file (".a") as input containing bundled
1539/// code object files, and a list of offload targets (not host), and extracts
1540/// the code objects into a new archive file for each offload target. Each
1541/// resulting archive file contains all code object files corresponding to that
1542/// particular offload target. The created archive file does not
1543/// contain an index of the symbols and code object files are named as
1544/// <<Parent Bundle Name>-<CodeObject's TargetID>>, with ':' replaced with '_'.
1546 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
1547
1548 /// Map of target names with list of object files that will form the device
1549 /// specific archive for that target
1550 StringMap<std::vector<NewArchiveMember>> OutputArchivesMap;
1551
1552 // Map of target names and output archive filenames
1553 StringMap<StringRef> TargetOutputFileNameMap;
1554
1555 auto Output = BundlerConfig.OutputFileNames.begin();
1556 for (auto &Target : BundlerConfig.TargetNames) {
1557 TargetOutputFileNameMap[Target] = *Output;
1558 ++Output;
1559 }
1560
1561 StringRef IFName = BundlerConfig.InputFileNames.front();
1562
1563 if (BundlerConfig.CheckInputArchive) {
1564 // For a specific processor, a feature either shows up in all target IDs, or
1565 // does not show up in any target IDs. Otherwise the target ID combination
1566 // is invalid.
1567 auto ArchiveError = CheckHeterogeneousArchive(IFName, BundlerConfig);
1568 if (ArchiveError) {
1569 return ArchiveError;
1570 }
1571 }
1572
1573 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1574 MemoryBuffer::getFileOrSTDIN(IFName, true, false);
1575 if (std::error_code EC = BufOrErr.getError())
1576 return createFileError(BundlerConfig.InputFileNames.front(), EC);
1577
1578 ArchiveBuffers.push_back(std::move(*BufOrErr));
1580 Archive::create(ArchiveBuffers.back()->getMemBufferRef());
1581 if (!LibOrErr)
1582 return LibOrErr.takeError();
1583
1584 auto Archive = std::move(*LibOrErr);
1585
1586 Error ArchiveErr = Error::success();
1587 auto ChildEnd = Archive->child_end();
1588
1589 /// Iterate over all bundled code object files in the input archive.
1590 for (auto ArchiveIter = Archive->child_begin(ArchiveErr);
1591 ArchiveIter != ChildEnd; ++ArchiveIter) {
1592 if (ArchiveErr)
1593 return ArchiveErr;
1594 auto ArchiveChildNameOrErr = (*ArchiveIter).getName();
1595 if (!ArchiveChildNameOrErr)
1596 return ArchiveChildNameOrErr.takeError();
1597
1598 StringRef BundledObjectFile = sys::path::filename(*ArchiveChildNameOrErr);
1599
1600 auto CodeObjectBufferRefOrErr = (*ArchiveIter).getMemoryBufferRef();
1601 if (!CodeObjectBufferRefOrErr)
1602 return CodeObjectBufferRefOrErr.takeError();
1603
1604 auto TempCodeObjectBuffer =
1605 MemoryBuffer::getMemBuffer(*CodeObjectBufferRefOrErr, false);
1606
1607 // Decompress the buffer if necessary.
1608 Expected<std::unique_ptr<MemoryBuffer>> DecompressedBufferOrErr =
1609 CompressedOffloadBundle::decompress(
1610 *TempCodeObjectBuffer,
1611 BundlerConfig.Verbose ? &llvm::errs() : nullptr);
1612 if (!DecompressedBufferOrErr)
1613 return createStringError(
1614 inconvertibleErrorCode(),
1615 "Failed to decompress code object: " +
1616 llvm::toString(DecompressedBufferOrErr.takeError()));
1617
1618 MemoryBuffer &CodeObjectBuffer = **DecompressedBufferOrErr;
1619
1620 Expected<std::unique_ptr<FileHandler>> FileHandlerOrErr =
1621 CreateFileHandler(CodeObjectBuffer, BundlerConfig);
1622 if (!FileHandlerOrErr)
1623 return FileHandlerOrErr.takeError();
1624
1625 std::unique_ptr<FileHandler> &FileHandler = *FileHandlerOrErr;
1626 assert(FileHandler &&
1627 "FileHandle creation failed for file in the archive!");
1628
1629 if (Error ReadErr = FileHandler->ReadHeader(CodeObjectBuffer.getBuffer()))
1630 return ReadErr;
1631
1632 Expected<std::optional<StringRef>> CurBundleIDOrErr =
1633 FileHandler->ReadBundleStart(CodeObjectBuffer.getBuffer());
1634 if (!CurBundleIDOrErr)
1635 return CurBundleIDOrErr.takeError();
1636
1637 std::optional<StringRef> OptionalCurBundleID = *CurBundleIDOrErr;
1638 // No device code in this child, skip.
1639 if (!OptionalCurBundleID)
1640 continue;
1641 StringRef CodeObject = *OptionalCurBundleID;
1642
1643 // Process all bundle entries (CodeObjects) found in this child of input
1644 // archive.
1645 while (!CodeObject.empty()) {
1646 SmallVector<StringRef> CompatibleTargets;
1647 if (!checkOffloadBundleID(CodeObject)) {
1648 return createStringError(errc::invalid_argument,
1649 "Invalid bundle id read from code object");
1650 }
1651 auto CodeObjectInfo = OffloadTargetInfo(CodeObject, BundlerConfig);
1652 if (getCompatibleOffloadTargets(CodeObjectInfo, CompatibleTargets,
1653 BundlerConfig)) {
1654 std::string BundleData;
1655 raw_string_ostream DataStream(BundleData);
1656 if (Error Err = FileHandler->ReadBundle(DataStream, CodeObjectBuffer))
1657 return Err;
1658
1659 for (auto &CompatibleTarget : CompatibleTargets) {
1660 SmallString<128> BundledObjectFileName;
1661 BundledObjectFileName.assign(BundledObjectFile);
1662 auto OutputBundleName =
1663 Twine(llvm::sys::path::stem(BundledObjectFileName) + "-" +
1664 CodeObject +
1665 getDeviceLibraryFileName(BundledObjectFileName,
1666 CodeObjectInfo.TargetID))
1667 .str();
1668 // Replace ':' in optional target feature list with '_' to ensure
1669 // cross-platform validity.
1670 llvm::replace(OutputBundleName, ':', '_');
1671
1672 std::unique_ptr<MemoryBuffer> MemBuf = MemoryBuffer::getMemBufferCopy(
1673 DataStream.str(), OutputBundleName);
1674 ArchiveBuffers.push_back(std::move(MemBuf));
1675 llvm::MemoryBufferRef MemBufRef =
1676 MemoryBufferRef(*(ArchiveBuffers.back()));
1677
1678 // For inserting <CompatibleTarget, list<CodeObject>> entry in
1679 // OutputArchivesMap.
1680 OutputArchivesMap[CompatibleTarget].push_back(
1681 NewArchiveMember(MemBufRef));
1682 }
1683 }
1684
1685 if (Error Err = FileHandler->ReadBundleEnd(CodeObjectBuffer))
1686 return Err;
1687
1688 Expected<std::optional<StringRef>> NextTripleOrErr =
1689 FileHandler->ReadBundleStart(CodeObjectBuffer.getBuffer());
1690 if (!NextTripleOrErr)
1691 return NextTripleOrErr.takeError();
1692
1693 CodeObject = ((*NextTripleOrErr).has_value()) ? **NextTripleOrErr : "";
1694 } // End of processing of all bundle entries of this child of input archive.
1695 } // End of while over children of input archive.
1696
1697 assert(!ArchiveErr && "Error occurred while reading archive!");
1698
1699 /// Write out an archive for each target
1700 for (auto &Target : BundlerConfig.TargetNames) {
1701 StringRef FileName = TargetOutputFileNameMap[Target];
1702 auto CurArchiveMembers = OutputArchivesMap.find(Target);
1703 if (CurArchiveMembers != OutputArchivesMap.end()) {
1704 if (Error WriteErr = writeArchive(FileName, CurArchiveMembers->getValue(),
1705 SymtabWritingMode::NormalSymtab,
1707 false, nullptr))
1708 return WriteErr;
1709 } else if (!BundlerConfig.AllowMissingBundles) {
1710 std::string ErrMsg =
1711 Twine("no compatible code object found for the target '" + Target +
1712 "' in heterogeneous archive library: " + IFName)
1713 .str();
1714 return createStringError(inconvertibleErrorCode(), ErrMsg);
1715 } else { // Create an empty archive file if no compatible code object is
1716 // found and "allow-missing-bundles" is enabled. It ensures that
1717 // the linker using output of this step doesn't complain about
1718 // the missing input file.
1719 std::vector<llvm::NewArchiveMember> EmptyArchive;
1720 EmptyArchive.clear();
1721 if (Error WriteErr = writeArchive(
1722 FileName, EmptyArchive, SymtabWritingMode::NormalSymtab,
1723 getDefaultArchiveKindForHost(), true, false, nullptr))
1724 return WriteErr;
1725 }
1726 }
1727
1728 return Error::success();
1729}
1730
1731bool clang::checkOffloadBundleID(const llvm::StringRef Str) {
1732 // <kind>-<triple>[-<target id>[:target features]]
1733 // <triple> := <arch>-<vendor>-<os>-<env>
1734 SmallVector<StringRef, 6> Components;
1735 Str.split(Components, '-', /*MaxSplit=*/5);
1736 return Components.size() == 5 || Components.size() == 6;
1737}
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Target Target
Definition MachO.h:51
static std::string getDeviceLibraryFileName(StringRef BundleFileName, StringRef Device)
static StringRef getDeviceFileExtension(StringRef Device, StringRef BundleFileName)
static Expected< std::unique_ptr< FileHandler > > CreateFileHandler(MemoryBuffer &FirstInput, const OffloadBundlerConfig &BundlerConfig)
Return an appropriate handler given the input files and options.
#define OFFLOAD_BUNDLER_MAGIC_STR
Magic string that marks the existence of offloading data.
bool isCodeObjectCompatible(const OffloadTargetInfo &CodeObjectInfo, const OffloadTargetInfo &TargetInfo)
Checks if a code object CodeObjectInfo is compatible with a given target TargetInfo.
static Error CheckHeterogeneousArchive(StringRef ArchiveName, const OffloadBundlerConfig &BundlerConfig)
static std::unique_ptr< FileHandler > CreateObjectFileHandler(MemoryBuffer &FirstInput, const OffloadBundlerConfig &BundlerConfig)
Return an appropriate object file handler.
static Archive::Kind getDefaultArchiveKindForHost()
static std::optional< size_t > getCompressedBundleSize(StringRef Blob)
static bool getCompatibleOffloadTargets(OffloadTargetInfo &CodeObjectInfo, SmallVectorImpl< StringRef > &CompatibleTargets, const OffloadBundlerConfig &BundlerConfig)
Computes a list of targets among all given targets which are compatible with this code object.
This file defines an offload bundling API that bundles different files that relate with the same sour...
llvm::SmallVector< std::string, 4 > TargetNames
llvm::compression::Format CompressionFormat
llvm::SmallVector< std::string, 4 > OutputFileNames
llvm::SmallVector< std::string, 4 > InputFileNames
llvm::Error BundleFiles()
Bundle the files. Return true if an error was found.
llvm::Error UnbundleArchive()
UnbundleArchive takes an archive file (".a") as input containing bundled code object files,...
static llvm::Error ListBundleIDsInFile(llvm::StringRef InputFileName, const OffloadBundlerConfig &BundlerConfig)
const OffloadBundlerConfig & BundlerConfig
Exposes information about the current target.
Definition TargetInfo.h:228
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition Interp.h:3936
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
std::optional< llvm::StringRef > parseTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch, llvm::StringMap< bool > *FeatureMap)
Parse a target ID to get processor and feature map.
Definition TargetID.cpp:122
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
std::optional< std::pair< llvm::StringRef, llvm::StringRef > > getConflictTargetIDCombination(const std::set< llvm::StringRef > &TargetIDs)
Get the conflicted pair of target IDs for a compilation or a bundled code object, assuming TargetIDs ...
Definition TargetID.cpp:171
OffloadArch StringToOffloadArch(llvm::StringRef S)
bool checkOffloadBundleID(const llvm::StringRef Str)
Check whether the bundle id is in the following format: <kind>-<triple>[-<target id>[:target features...
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Obtain the offload kind, real machine triple, and an optional TargetID out of the target information ...
bool operator==(const OffloadTargetInfo &Target) const
bool isOffloadKindCompatible(const llvm::StringRef TargetOffloadKind) const
OffloadTargetInfo(const llvm::StringRef Target, const OffloadBundlerConfig &BC)
llvm::StringRef OffloadKind
std::string str() const
const OffloadBundlerConfig & BundlerConfig