CompileUtils.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===-- CompileUtils.h - Utilities for compiling IR in the JIT --*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Contains utilities for compiling IR to object files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
  14. #define LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
  15. #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
  16. #include "llvm/IR/LegacyPassManager.h"
  17. #include "llvm/MC/MCContext.h"
  18. #include "llvm/Object/ObjectFile.h"
  19. #include "llvm/Target/TargetMachine.h"
  20. namespace llvm {
  21. namespace orc {
  22. /// @brief Simple compile functor: Takes a single IR module and returns an
  23. /// ObjectFile.
  24. class SimpleCompiler {
  25. public:
  26. /// @brief Construct a simple compile functor with the given target.
  27. SimpleCompiler(TargetMachine &TM) : TM(TM) {}
  28. /// @brief Compile a Module to an ObjectFile.
  29. object::OwningBinary<object::ObjectFile> operator()(Module &M) const {
  30. SmallVector<char, 0> ObjBufferSV;
  31. raw_svector_ostream ObjStream(ObjBufferSV);
  32. legacy::PassManager PM;
  33. MCContext *Ctx;
  34. if (TM.addPassesToEmitMC(PM, Ctx, ObjStream))
  35. llvm_unreachable("Target does not support MC emission.");
  36. PM.run(M);
  37. ObjStream.flush();
  38. std::unique_ptr<MemoryBuffer> ObjBuffer(
  39. new ObjectMemoryBuffer(std::move(ObjBufferSV)));
  40. ErrorOr<std::unique_ptr<object::ObjectFile>> Obj =
  41. object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef());
  42. // TODO: Actually report errors helpfully.
  43. typedef object::OwningBinary<object::ObjectFile> OwningObj;
  44. if (Obj)
  45. return OwningObj(std::move(*Obj), std::move(ObjBuffer));
  46. return OwningObj(nullptr, nullptr);
  47. }
  48. private:
  49. TargetMachine &TM;
  50. };
  51. } // End namespace orc.
  52. } // End namespace llvm.
  53. #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H