OffloadEmitter.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #include "llvm/Object/OffloadBinary.h"
  9. #include "llvm/ObjectYAML/OffloadYAML.h"
  10. #include "llvm/ObjectYAML/yaml2obj.h"
  11. #include "llvm/Support/Error.h"
  12. #include "llvm/Support/raw_ostream.h"
  13. using namespace llvm;
  14. using namespace OffloadYAML;
  15. namespace llvm {
  16. namespace yaml {
  17. bool yaml2offload(Binary &Doc, raw_ostream &Out, ErrorHandler EH) {
  18. for (const auto &Member : Doc.Members) {
  19. object::OffloadBinary::OffloadingImage Image{};
  20. if (Member.ImageKind)
  21. Image.TheImageKind = *Member.ImageKind;
  22. if (Member.OffloadKind)
  23. Image.TheOffloadKind = *Member.OffloadKind;
  24. if (Member.Flags)
  25. Image.Flags = *Member.Flags;
  26. StringMap<StringRef> &StringData = Image.StringData;
  27. if (Member.StringEntries) {
  28. for (const auto &Entry : *Member.StringEntries) {
  29. StringData[Entry.Key] = Entry.Value;
  30. }
  31. }
  32. SmallVector<char, 1024> Data;
  33. raw_svector_ostream OS(Data);
  34. if (Member.Content)
  35. Member.Content->writeAsBinary(OS);
  36. Image.Image = MemoryBuffer::getMemBufferCopy(OS.str());
  37. std::unique_ptr<MemoryBuffer> Binary = object::OffloadBinary::write(Image);
  38. // Copy the data to a new buffer so we can modify the bytes directly.
  39. SmallVector<char> NewBuffer;
  40. std::copy(Binary->getBufferStart(), Binary->getBufferEnd(),
  41. std::back_inserter(NewBuffer));
  42. auto *TheHeader =
  43. reinterpret_cast<object::OffloadBinary::Header *>(&NewBuffer[0]);
  44. if (Doc.Version)
  45. TheHeader->Version = *Doc.Version;
  46. if (Doc.Size)
  47. TheHeader->Size = *Doc.Size;
  48. if (Doc.EntryOffset)
  49. TheHeader->EntryOffset = *Doc.EntryOffset;
  50. if (Doc.EntrySize)
  51. TheHeader->EntrySize = *Doc.EntrySize;
  52. Out.write(NewBuffer.begin(), NewBuffer.size());
  53. }
  54. return true;
  55. }
  56. } // namespace yaml
  57. } // namespace llvm