d08008da6e056e63ade4baa83bc3b9efd8aa667e
[oota-llvm.git] / tools / lli / OrcLazyJIT.cpp
1 //===------ OrcLazyJIT.cpp - Basic Orc-based JIT for lazy execution -------===//
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 #include "OrcLazyJIT.h"
11 #include "llvm/ExecutionEngine/Orc/OrcTargetSupport.h"
12 #include "llvm/Support/DynamicLibrary.h"
13
14 using namespace llvm;
15
16 OrcLazyJIT::CallbackManagerBuilder
17 OrcLazyJIT::createCallbackManagerBuilder(Triple T) {
18   switch (T.getArch()) {
19     default: return nullptr;
20
21     case Triple::x86_64: {
22       typedef orc::JITCompileCallbackManager<CompileLayerT,
23                                              orc::OrcX86_64> CCMgrT;
24       return [](CompileLayerT &CompileLayer, RuntimeDyld::MemoryManager &MemMgr,
25                 LLVMContext &Context) {
26                return make_unique<CCMgrT>(CompileLayer, MemMgr, Context, 0, 64);
27              };
28     }
29   }
30 }
31
32 int llvm::runOrcLazyJIT(std::unique_ptr<Module> M, int ArgC, char* ArgV[]) {
33   // Add the program's symbols into the JIT's search space.
34   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr)) {
35     errs() << "Error loading program symbols.\n";
36     return 1;
37   }
38
39   // Grab a target machine and try to build a factory function for the
40   // target-specific Orc callback manager.
41   auto TM = std::unique_ptr<TargetMachine>(EngineBuilder().selectTarget());
42   auto &Context = getGlobalContext();
43   auto CallbackMgrBuilder =
44     OrcLazyJIT::createCallbackManagerBuilder(Triple(TM->getTargetTriple()));
45
46   // If we couldn't build the factory function then there must not be a callback
47   // manager for this target. Bail out.
48   if (!CallbackMgrBuilder) {
49     errs() << "No callback manager available for target '"
50            << TM->getTargetTriple() << "'.\n";
51     return 1;
52   }
53
54   // Everything looks good. Build the JIT.
55   OrcLazyJIT J(std::move(TM), Context, CallbackMgrBuilder);
56
57   // Add the module, look up main and run it.
58   auto MainHandle = J.addModule(std::move(M));
59   auto MainSym = J.findSymbolIn(MainHandle, "main");
60
61   if (!MainSym) {
62     errs() << "Could not find main function.\n";
63     return 1;
64   }
65
66   typedef int (*MainFnPtr)(int, char*[]);
67   auto Main = reinterpret_cast<MainFnPtr>(
68                 static_cast<uintptr_t>(MainSym.getAddress()));
69
70   return Main(ArgC, ArgV);
71 }