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     ErrorOr<std::unique_ptr<object::ObjectFile>> Obj =
46         object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef());
47     // TODO: Actually report errors helpfully.
48     typedef object::OwningBinary<object::ObjectFile> OwningObj;
49     if (Obj)
50       return OwningObj(std::move(*Obj), std::move(ObjBuffer));
51     return OwningObj(nullptr, nullptr);
52   }
53 
54 private:
55   TargetMachine &TM;
56 };
57 
58 } // End namespace orc.
59 } // End namespace llvm.
60 
61 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEUTILS_H
62