• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
14 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
15 #define LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
16 
17 #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
18 #include "llvm/IR/LegacyPassManager.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Target/TargetMachine.h"
22 
23 namespace llvm {
24 namespace orc {
25 
26 /// @brief Simple compile functor: Takes a single IR module and returns an
27 ///        ObjectFile.
28 class SimpleCompiler {
29 public:
30   /// @brief Construct a simple compile functor with the given target.
SimpleCompiler(TargetMachine & TM)31   SimpleCompiler(TargetMachine &TM) : TM(TM) {}
32 
33   /// @brief Compile a Module to an ObjectFile.
operator()34   object::OwningBinary<object::ObjectFile> operator()(Module &M) const {
35     SmallVector<char, 0> ObjBufferSV;
36     raw_svector_ostream ObjStream(ObjBufferSV);
37 
38     legacy::PassManager PM;
39     MCContext *Ctx;
40     if (TM.addPassesToEmitMC(PM, Ctx, ObjStream))
41       llvm_unreachable("Target does not support MC emission.");
42     PM.run(M);
43     std::unique_ptr<MemoryBuffer> ObjBuffer(
44         new ObjectMemoryBuffer(std::move(ObjBufferSV)));
45     Expected<std::unique_ptr<object::ObjectFile>> Obj =
46         object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef());
47     typedef object::OwningBinary<object::ObjectFile> OwningObj;
48     if (Obj)
49       return OwningObj(std::move(*Obj), std::move(ObjBuffer));
50     // TODO: Actually report errors helpfully.
51     consumeError(Obj.takeError());
52     return OwningObj(nullptr, nullptr);
53   }
54 
55 private:
56   TargetMachine &TM;
57 };
58 
59 } // End namespace orc.
60 } // End namespace llvm.
61 
62 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
63