xref: /freebsd/contrib/llvm-project/llvm/lib/ObjectYAML/OffloadEmitter.cpp (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
1 //===- OffloadEmitter.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Object/OffloadBinary.h"
10 #include "llvm/ObjectYAML/OffloadYAML.h"
11 #include "llvm/ObjectYAML/yaml2obj.h"
12 #include "llvm/Support/Error.h"
13 #include "llvm/Support/raw_ostream.h"
14 
15 using namespace llvm;
16 using namespace OffloadYAML;
17 
18 namespace llvm {
19 namespace yaml {
20 
21 bool yaml2offload(Binary &Doc, raw_ostream &Out, ErrorHandler EH) {
22   for (const auto &Member : Doc.Members) {
23     object::OffloadBinary::OffloadingImage Image{};
24     if (Member.ImageKind)
25       Image.TheImageKind = *Member.ImageKind;
26     if (Member.OffloadKind)
27       Image.TheOffloadKind = *Member.OffloadKind;
28     if (Member.Flags)
29       Image.Flags = *Member.Flags;
30 
31     if (Member.StringEntries)
32       for (const auto &Entry : *Member.StringEntries)
33         Image.StringData[Entry.Key] = Entry.Value;
34 
35     SmallVector<char, 1024> Data;
36     raw_svector_ostream OS(Data);
37     if (Member.Content)
38       Member.Content->writeAsBinary(OS);
39     Image.Image = MemoryBuffer::getMemBufferCopy(OS.str());
40 
41     std::unique_ptr<MemoryBuffer> Binary = object::OffloadBinary::write(Image);
42 
43     // Copy the data to a new buffer so we can modify the bytes directly.
44     SmallVector<char> NewBuffer;
45     std::copy(Binary->getBufferStart(), Binary->getBufferEnd(),
46               std::back_inserter(NewBuffer));
47     auto *TheHeader =
48         reinterpret_cast<object::OffloadBinary::Header *>(&NewBuffer[0]);
49     if (Doc.Version)
50       TheHeader->Version = *Doc.Version;
51     if (Doc.Size)
52       TheHeader->Size = *Doc.Size;
53     if (Doc.EntryOffset)
54       TheHeader->EntryOffset = *Doc.EntryOffset;
55     if (Doc.EntrySize)
56       TheHeader->EntrySize = *Doc.EntrySize;
57 
58     Out.write(NewBuffer.begin(), NewBuffer.size());
59   }
60 
61   return true;
62 }
63 
64 } // namespace yaml
65 } // namespace llvm
66