Enable lazy compilation in MCJIT
[oota-llvm.git] / lib / ExecutionEngine / MCJIT / MCJIT.cpp
1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
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 "MCJIT.h"
11 #include "MCJITMemoryManager.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Function.h"
14 #include "llvm/ExecutionEngine/GenericValue.h"
15 #include "llvm/ExecutionEngine/MCJIT.h"
16 #include "llvm/ExecutionEngine/JITMemoryManager.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/DynamicLibrary.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/MutexGuard.h"
22 #include "llvm/Target/TargetData.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 static struct RegisterJIT {
29   RegisterJIT() { MCJIT::Register(); }
30 } JITRegistrator;
31
32 }
33
34 extern "C" void LLVMLinkInMCJIT() {
35 }
36
37 ExecutionEngine *MCJIT::createJIT(Module *M,
38                                   std::string *ErrorStr,
39                                   JITMemoryManager *JMM,
40                                   bool GVsWithCode,
41                                   TargetMachine *TM) {
42   // Try to register the program as a source of symbols to resolve against.
43   //
44   // FIXME: Don't do this here.
45   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
46
47   // If the target supports JIT code generation, create the JIT.
48   if (TargetJITInfo *TJ = TM->getJITInfo())
49     return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM), GVsWithCode);
50
51   if (ErrorStr)
52     *ErrorStr = "target does not support JIT code generation";
53   return 0;
54 }
55
56 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
57              RTDyldMemoryManager *MM, bool AllocateGVsWithCode)
58   : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM), 
59     isCompiled(false), M(m), OS(Buffer)  {
60
61   setTargetData(TM->getTargetData());
62 }
63
64 MCJIT::~MCJIT() {
65   delete MemMgr;
66   delete TM;
67 }
68
69 void MCJIT::emitObject(Module *m) {
70   /// Currently, MCJIT only supports a single module and the module passed to
71   /// this function call is expected to be the contained module.  The module
72   /// is passed as a parameter here to prepare for multiple module support in 
73   /// the future.
74   assert(M == m);
75
76   // Get a thread lock to make sure we aren't trying to compile multiple times
77   MutexGuard locked(lock);
78
79   // FIXME: Track compilation state on a per-module basis when multiple modules
80   //        are supported.
81   // Re-compilation is not supported
82   if (isCompiled)
83     return;
84
85   PassManager PM;
86
87   PM.add(new TargetData(*TM->getTargetData()));
88
89   // Turn the machine code intermediate representation into bytes in memory
90   // that may be executed.
91   if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
92     report_fatal_error("Target does not support MC emission!");
93   }
94
95   // Initialize passes.
96   // FIXME: When we support multiple modules, we'll want to move the code
97   // gen and finalization out of the constructor here and do it more
98   // on-demand as part of getPointerToFunction().
99   PM.run(*m);
100   // Flush the output buffer so the SmallVector gets its data.
101   OS.flush();
102
103   // Load the object into the dynamic linker.
104   MemoryBuffer* MB = MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
105                                                           Buffer.size()),
106                                                 "", false);
107   if (Dyld.loadObject(MB))
108     report_fatal_error(Dyld.getErrorString());
109
110   // Resolve any relocations.
111   Dyld.resolveRelocations();
112
113   // FIXME: Add support for per-module compilation state
114   isCompiled = true;
115 }
116
117 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
118   report_fatal_error("not yet implemented");
119 }
120
121 void *MCJIT::getPointerToFunction(Function *F) {
122   // FIXME: Add support for per-module compilation state
123   if (!isCompiled)
124     emitObject(M);
125
126   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
127     bool AbortOnFailure = !F->hasExternalWeakLinkage();
128     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
129     addGlobalMapping(F, Addr);
130     return Addr;
131   }
132
133   // FIXME: Should the Dyld be retaining module information? Probably not.
134   // FIXME: Should we be using the mangler for this? Probably.
135   StringRef BaseName = F->getName();
136   if (BaseName[0] == '\1')
137     return (void*)Dyld.getSymbolAddress(BaseName.substr(1));
138   return (void*)Dyld.getSymbolAddress((TM->getMCAsmInfo()->getGlobalPrefix()
139                                        + BaseName).str());
140 }
141
142 void *MCJIT::recompileAndRelinkFunction(Function *F) {
143   report_fatal_error("not yet implemented");
144 }
145
146 void MCJIT::freeMachineCodeForFunction(Function *F) {
147   report_fatal_error("not yet implemented");
148 }
149
150 GenericValue MCJIT::runFunction(Function *F,
151                                 const std::vector<GenericValue> &ArgValues) {
152   assert(F && "Function *F was null at entry to run()");
153
154   void *FPtr = getPointerToFunction(F);
155   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
156   FunctionType *FTy = F->getFunctionType();
157   Type *RetTy = FTy->getReturnType();
158
159   assert((FTy->getNumParams() == ArgValues.size() ||
160           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
161          "Wrong number of arguments passed into function!");
162   assert(FTy->getNumParams() == ArgValues.size() &&
163          "This doesn't support passing arguments through varargs (yet)!");
164
165   // Handle some common cases first.  These cases correspond to common `main'
166   // prototypes.
167   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
168     switch (ArgValues.size()) {
169     case 3:
170       if (FTy->getParamType(0)->isIntegerTy(32) &&
171           FTy->getParamType(1)->isPointerTy() &&
172           FTy->getParamType(2)->isPointerTy()) {
173         int (*PF)(int, char **, const char **) =
174           (int(*)(int, char **, const char **))(intptr_t)FPtr;
175
176         // Call the function.
177         GenericValue rv;
178         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
179                                  (char **)GVTOP(ArgValues[1]),
180                                  (const char **)GVTOP(ArgValues[2])));
181         return rv;
182       }
183       break;
184     case 2:
185       if (FTy->getParamType(0)->isIntegerTy(32) &&
186           FTy->getParamType(1)->isPointerTy()) {
187         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
188
189         // Call the function.
190         GenericValue rv;
191         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
192                                  (char **)GVTOP(ArgValues[1])));
193         return rv;
194       }
195       break;
196     case 1:
197       if (FTy->getNumParams() == 1 &&
198           FTy->getParamType(0)->isIntegerTy(32)) {
199         GenericValue rv;
200         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
201         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
202         return rv;
203       }
204       break;
205     }
206   }
207
208   // Handle cases where no arguments are passed first.
209   if (ArgValues.empty()) {
210     GenericValue rv;
211     switch (RetTy->getTypeID()) {
212     default: llvm_unreachable("Unknown return type for function call!");
213     case Type::IntegerTyID: {
214       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
215       if (BitWidth == 1)
216         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
217       else if (BitWidth <= 8)
218         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
219       else if (BitWidth <= 16)
220         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
221       else if (BitWidth <= 32)
222         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
223       else if (BitWidth <= 64)
224         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
225       else
226         llvm_unreachable("Integer types > 64 bits not supported");
227       return rv;
228     }
229     case Type::VoidTyID:
230       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
231       return rv;
232     case Type::FloatTyID:
233       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
234       return rv;
235     case Type::DoubleTyID:
236       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
237       return rv;
238     case Type::X86_FP80TyID:
239     case Type::FP128TyID:
240     case Type::PPC_FP128TyID:
241       llvm_unreachable("long double not supported yet");
242     case Type::PointerTyID:
243       return PTOGV(((void*(*)())(intptr_t)FPtr)());
244     }
245   }
246
247   llvm_unreachable("Full-featured argument passing not supported yet!");
248 }
249
250 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
251                                        bool AbortOnFailure) {
252   // FIXME: Add support for per-module compilation state
253   if (!isCompiled)
254     emitObject(M);
255
256   if (!isSymbolSearchingDisabled() && MemMgr) {
257     void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
258     if (ptr)
259       return ptr;
260   }
261
262   /// If a LazyFunctionCreator is installed, use it to get/create the function.
263   if (LazyFunctionCreator)
264     if (void *RP = LazyFunctionCreator(Name))
265       return RP;
266
267   if (AbortOnFailure) {
268     report_fatal_error("Program used external function '"+Name+
269                        "' which could not be resolved!");
270   }
271   return 0;
272 }