ExecutionEngine: fix JIT/MCJIT selectTarget() duplication (v2)
[oota-llvm.git] / lib / ExecutionEngine / JIT / JIT.cpp
1 //===-- JIT.cpp - LLVM 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 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bitcode in an efficient manner.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/CodeGen/JITCodeEmitter.h"
23 #include "llvm/CodeGen/MachineCodeInfo.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetJITInfo.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MutexGuard.h"
33 #include "llvm/Support/DynamicLibrary.h"
34 #include "llvm/Config/config.h"
35
36 using namespace llvm;
37
38 #ifdef __APPLE__
39 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
40 // of atexit). It passes the address of linker generated symbol __dso_handle
41 // to the function.
42 // This configuration change happened at version 5330.
43 # include <AvailabilityMacros.h>
44 # if defined(MAC_OS_X_VERSION_10_4) && \
45      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
46       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
47        __APPLE_CC__ >= 5330))
48 #  ifndef HAVE___DSO_HANDLE
49 #   define HAVE___DSO_HANDLE 1
50 #  endif
51 # endif
52 #endif
53
54 #if HAVE___DSO_HANDLE
55 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
56 #endif
57
58 namespace {
59
60 static struct RegisterJIT {
61   RegisterJIT() { JIT::Register(); }
62 } JITRegistrator;
63
64 }
65
66 extern "C" void LLVMLinkInJIT() {
67 }
68
69 // Determine whether we can register EH tables.
70 #if (defined(__GNUC__) && !defined(__ARM_EABI__) && \
71      !defined(__USING_SJLJ_EXCEPTIONS__))
72 #define HAVE_EHTABLE_SUPPORT 1
73 #else
74 #define HAVE_EHTABLE_SUPPORT 0
75 #endif
76
77 #if HAVE_EHTABLE_SUPPORT
78
79 // libgcc defines the __register_frame function to dynamically register new
80 // dwarf frames for exception handling. This functionality is not portable
81 // across compilers and is only provided by GCC. We use the __register_frame
82 // function here so that code generated by the JIT cooperates with the unwinding
83 // runtime of libgcc. When JITting with exception handling enable, LLVM
84 // generates dwarf frames and registers it to libgcc with __register_frame.
85 //
86 // The __register_frame function works with Linux.
87 //
88 // Unfortunately, this functionality seems to be in libgcc after the unwinding
89 // library of libgcc for darwin was written. The code for darwin overwrites the
90 // value updated by __register_frame with a value fetched with "keymgr".
91 // "keymgr" is an obsolete functionality, which should be rewritten some day.
92 // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
93 // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
94 // values of an opaque key, used by libgcc to find dwarf tables.
95
96 extern "C" void __register_frame(void*);
97 extern "C" void __deregister_frame(void*);
98
99 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
100 # define USE_KEYMGR 1
101 #else
102 # define USE_KEYMGR 0
103 #endif
104
105 #if USE_KEYMGR
106
107 namespace {
108
109 // LibgccObject - This is the structure defined in libgcc. There is no #include
110 // provided for this structure, so we also define it here. libgcc calls it
111 // "struct object". The structure is undocumented in libgcc.
112 struct LibgccObject {
113   void *unused1;
114   void *unused2;
115   void *unused3;
116
117   /// frame - Pointer to the exception table.
118   void *frame;
119
120   /// encoding -  The encoding of the object?
121   union {
122     struct {
123       unsigned long sorted : 1;
124       unsigned long from_array : 1;
125       unsigned long mixed_encoding : 1;
126       unsigned long encoding : 8;
127       unsigned long count : 21;
128     } b;
129     size_t i;
130   } encoding;
131
132   /// fde_end - libgcc defines this field only if some macro is defined. We
133   /// include this field even if it may not there, to make libgcc happy.
134   char *fde_end;
135
136   /// next - At least we know it's a chained list!
137   struct LibgccObject *next;
138 };
139
140 // "kemgr" stuff. Apparently, all frame tables are stored there.
141 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
142 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
143 #define KEYMGR_GCC3_DW2_OBJ_LIST        302     /* Dwarf2 object list  */
144
145 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
146 /// probably contains all dwarf tables that are loaded.
147 struct LibgccObjectInfo {
148
149   /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
150   ///
151   struct LibgccObject* seenObjects;
152
153   /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
154   ///
155   struct LibgccObject* unseenObjects;
156
157   unsigned unused[2];
158 };
159
160 /// darwin_register_frame - Since __register_frame does not work with darwin's
161 /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
162 /// "Dwarf2 object list" key.
163 void DarwinRegisterFrame(void* FrameBegin) {
164   // Get the key.
165   LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
166     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
167   assert(LOI && "This should be preallocated by the runtime");
168
169   // Allocate a new LibgccObject to represent this frame. Deallocation of this
170   // object may be impossible: since darwin code in libgcc was written after
171   // the ability to dynamically register frames, things may crash if we
172   // deallocate it.
173   struct LibgccObject* ob = (struct LibgccObject*)
174     malloc(sizeof(struct LibgccObject));
175
176   // Do like libgcc for the values of the field.
177   ob->unused1 = (void *)-1;
178   ob->unused2 = 0;
179   ob->unused3 = 0;
180   ob->frame = FrameBegin;
181   ob->encoding.i = 0;
182   ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
183
184   // Put the info on both places, as libgcc uses the first or the second
185   // field. Note that we rely on having two pointers here. If fde_end was a
186   // char, things would get complicated.
187   ob->fde_end = (char*)LOI->unseenObjects;
188   ob->next = LOI->unseenObjects;
189
190   // Update the key's unseenObjects list.
191   LOI->unseenObjects = ob;
192
193   // Finally update the "key". Apparently, libgcc requires it.
194   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
195                                          LOI);
196
197 }
198
199 }
200 #endif // __APPLE__
201 #endif // HAVE_EHTABLE_SUPPORT
202
203 /// createJIT - This is the factory method for creating a JIT for the current
204 /// machine, it does not fall back to the interpreter.  This takes ownership
205 /// of the module.
206 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
207                                             std::string *ErrorStr,
208                                             JITMemoryManager *JMM,
209                                             CodeGenOpt::Level OptLevel,
210                                             bool GVsWithCode,
211                                             CodeModel::Model CMM) {
212   // Use the defaults for extra parameters.  Users can use EngineBuilder to
213   // set them.
214   StringRef MArch = "";
215   StringRef MCPU = "";
216   SmallVector<std::string, 1> MAttrs;
217   return JIT::createJIT(M, ErrorStr, JMM, OptLevel, GVsWithCode, CMM,
218                         MArch, MCPU, MAttrs);
219 }
220
221 ExecutionEngine *JIT::createJIT(Module *M,
222                                 std::string *ErrorStr,
223                                 JITMemoryManager *JMM,
224                                 CodeGenOpt::Level OptLevel,
225                                 bool GVsWithCode,
226                                 CodeModel::Model CMM,
227                                 StringRef MArch,
228                                 StringRef MCPU,
229                                 const SmallVectorImpl<std::string>& MAttrs) {
230   // Try to register the program as a source of symbols to resolve against.
231   //
232   // FIXME: Don't do this here.
233   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
234
235   // Pick a target either via -march or by guessing the native arch.
236   //
237   // FIXME: This should be lifted out of here, it isn't something which should
238   // be part of the JIT policy, rather the burden for this selection should be
239   // pushed to clients.
240   TargetMachine *TM =
241           EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
242   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
243   TM->setCodeModel(CMM);
244
245   // If the target supports JIT code generation, create the JIT.
246   if (TargetJITInfo *TJ = TM->getJITInfo()) {
247     return new JIT(M, *TM, *TJ, JMM, OptLevel, GVsWithCode);
248   } else {
249     if (ErrorStr)
250       *ErrorStr = "target does not support JIT code generation";
251     return 0;
252   }
253 }
254
255 namespace {
256 /// This class supports the global getPointerToNamedFunction(), which allows
257 /// bugpoint or gdb users to search for a function by name without any context.
258 class JitPool {
259   SmallPtrSet<JIT*, 1> JITs;  // Optimize for process containing just 1 JIT.
260   mutable sys::Mutex Lock;
261 public:
262   void Add(JIT *jit) {
263     MutexGuard guard(Lock);
264     JITs.insert(jit);
265   }
266   void Remove(JIT *jit) {
267     MutexGuard guard(Lock);
268     JITs.erase(jit);
269   }
270   void *getPointerToNamedFunction(const char *Name) const {
271     MutexGuard guard(Lock);
272     assert(JITs.size() != 0 && "No Jit registered");
273     //search function in every instance of JIT
274     for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
275            end = JITs.end();
276          Jit != end; ++Jit) {
277       if (Function *F = (*Jit)->FindFunctionNamed(Name))
278         return (*Jit)->getPointerToFunction(F);
279     }
280     // The function is not available : fallback on the first created (will
281     // search in symbol of the current program/library)
282     return (*JITs.begin())->getPointerToNamedFunction(Name);
283   }
284 };
285 ManagedStatic<JitPool> AllJits;
286 }
287 extern "C" {
288   // getPointerToNamedFunction - This function is used as a global wrapper to
289   // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
290   // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
291   // need to resolve function(s) that are being mis-codegenerated, so we need to
292   // resolve their addresses at runtime, and this is the way to do it.
293   void *getPointerToNamedFunction(const char *Name) {
294     return AllJits->getPointerToNamedFunction(Name);
295   }
296 }
297
298 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
299          JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCode)
300   : ExecutionEngine(M), TM(tm), TJI(tji), AllocateGVsWithCode(GVsWithCode),
301     isAlreadyCodeGenerating(false) {
302   setTargetData(TM.getTargetData());
303
304   jitstate = new JITState(M);
305
306   // Initialize JCE
307   JCE = createEmitter(*this, JMM, TM);
308
309   // Register in global list of all JITs.
310   AllJits->Add(this);
311
312   // Add target data
313   MutexGuard locked(lock);
314   FunctionPassManager &PM = jitstate->getPM(locked);
315   PM.add(new TargetData(*TM.getTargetData()));
316
317   // Turn the machine code intermediate representation into bytes in memory that
318   // may be executed.
319   if (TM.addPassesToEmitMachineCode(PM, *JCE, OptLevel)) {
320     report_fatal_error("Target does not support machine code emission!");
321   }
322
323   // Register routine for informing unwinding runtime about new EH frames
324 #if HAVE_EHTABLE_SUPPORT
325 #if USE_KEYMGR
326   struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
327     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
328
329   // The key is created on demand, and libgcc creates it the first time an
330   // exception occurs. Since we need the key to register frames, we create
331   // it now.
332   if (!LOI)
333     LOI = (LibgccObjectInfo*)calloc(sizeof(struct LibgccObjectInfo), 1);
334   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, LOI);
335   InstallExceptionTableRegister(DarwinRegisterFrame);
336   // Not sure about how to deregister on Darwin.
337 #else
338   InstallExceptionTableRegister(__register_frame);
339   InstallExceptionTableDeregister(__deregister_frame);
340 #endif // __APPLE__
341 #endif // HAVE_EHTABLE_SUPPORT
342
343   // Initialize passes.
344   PM.doInitialization();
345 }
346
347 JIT::~JIT() {
348   // Unregister all exception tables registered by this JIT.
349   DeregisterAllTables();
350   // Cleanup.
351   AllJits->Remove(this);
352   delete jitstate;
353   delete JCE;
354   delete &TM;
355 }
356
357 /// addModule - Add a new Module to the JIT.  If we previously removed the last
358 /// Module, we need re-initialize jitstate with a valid Module.
359 void JIT::addModule(Module *M) {
360   MutexGuard locked(lock);
361
362   if (Modules.empty()) {
363     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
364
365     jitstate = new JITState(M);
366
367     FunctionPassManager &PM = jitstate->getPM(locked);
368     PM.add(new TargetData(*TM.getTargetData()));
369
370     // Turn the machine code intermediate representation into bytes in memory
371     // that may be executed.
372     if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
373       report_fatal_error("Target does not support machine code emission!");
374     }
375
376     // Initialize passes.
377     PM.doInitialization();
378   }
379
380   ExecutionEngine::addModule(M);
381 }
382
383 /// removeModule - If we are removing the last Module, invalidate the jitstate
384 /// since the PassManager it contains references a released Module.
385 bool JIT::removeModule(Module *M) {
386   bool result = ExecutionEngine::removeModule(M);
387
388   MutexGuard locked(lock);
389
390   if (jitstate->getModule() == M) {
391     delete jitstate;
392     jitstate = 0;
393   }
394
395   if (!jitstate && !Modules.empty()) {
396     jitstate = new JITState(Modules[0]);
397
398     FunctionPassManager &PM = jitstate->getPM(locked);
399     PM.add(new TargetData(*TM.getTargetData()));
400
401     // Turn the machine code intermediate representation into bytes in memory
402     // that may be executed.
403     if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
404       report_fatal_error("Target does not support machine code emission!");
405     }
406
407     // Initialize passes.
408     PM.doInitialization();
409   }
410   return result;
411 }
412
413 /// run - Start execution with the specified function and arguments.
414 ///
415 GenericValue JIT::runFunction(Function *F,
416                               const std::vector<GenericValue> &ArgValues) {
417   assert(F && "Function *F was null at entry to run()");
418
419   void *FPtr = getPointerToFunction(F);
420   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
421   const FunctionType *FTy = F->getFunctionType();
422   const Type *RetTy = FTy->getReturnType();
423
424   assert((FTy->getNumParams() == ArgValues.size() ||
425           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
426          "Wrong number of arguments passed into function!");
427   assert(FTy->getNumParams() == ArgValues.size() &&
428          "This doesn't support passing arguments through varargs (yet)!");
429
430   // Handle some common cases first.  These cases correspond to common `main'
431   // prototypes.
432   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
433     switch (ArgValues.size()) {
434     case 3:
435       if (FTy->getParamType(0)->isIntegerTy(32) &&
436           FTy->getParamType(1)->isPointerTy() &&
437           FTy->getParamType(2)->isPointerTy()) {
438         int (*PF)(int, char **, const char **) =
439           (int(*)(int, char **, const char **))(intptr_t)FPtr;
440
441         // Call the function.
442         GenericValue rv;
443         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
444                                  (char **)GVTOP(ArgValues[1]),
445                                  (const char **)GVTOP(ArgValues[2])));
446         return rv;
447       }
448       break;
449     case 2:
450       if (FTy->getParamType(0)->isIntegerTy(32) &&
451           FTy->getParamType(1)->isPointerTy()) {
452         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
453
454         // Call the function.
455         GenericValue rv;
456         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
457                                  (char **)GVTOP(ArgValues[1])));
458         return rv;
459       }
460       break;
461     case 1:
462       if (FTy->getNumParams() == 1 &&
463           FTy->getParamType(0)->isIntegerTy(32)) {
464         GenericValue rv;
465         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
466         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
467         return rv;
468       }
469       break;
470     }
471   }
472
473   // Handle cases where no arguments are passed first.
474   if (ArgValues.empty()) {
475     GenericValue rv;
476     switch (RetTy->getTypeID()) {
477     default: llvm_unreachable("Unknown return type for function call!");
478     case Type::IntegerTyID: {
479       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
480       if (BitWidth == 1)
481         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
482       else if (BitWidth <= 8)
483         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
484       else if (BitWidth <= 16)
485         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
486       else if (BitWidth <= 32)
487         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
488       else if (BitWidth <= 64)
489         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
490       else
491         llvm_unreachable("Integer types > 64 bits not supported");
492       return rv;
493     }
494     case Type::VoidTyID:
495       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
496       return rv;
497     case Type::FloatTyID:
498       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
499       return rv;
500     case Type::DoubleTyID:
501       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
502       return rv;
503     case Type::X86_FP80TyID:
504     case Type::FP128TyID:
505     case Type::PPC_FP128TyID:
506       llvm_unreachable("long double not supported yet");
507       return rv;
508     case Type::PointerTyID:
509       return PTOGV(((void*(*)())(intptr_t)FPtr)());
510     }
511   }
512
513   // Okay, this is not one of our quick and easy cases.  Because we don't have a
514   // full FFI, we have to codegen a nullary stub function that just calls the
515   // function we are interested in, passing in constants for all of the
516   // arguments.  Make this function and return.
517
518   // First, create the function.
519   FunctionType *STy=FunctionType::get(RetTy, false);
520   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
521                                     F->getParent());
522
523   // Insert a basic block.
524   BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
525
526   // Convert all of the GenericValue arguments over to constants.  Note that we
527   // currently don't support varargs.
528   SmallVector<Value*, 8> Args;
529   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
530     Constant *C = 0;
531     const Type *ArgTy = FTy->getParamType(i);
532     const GenericValue &AV = ArgValues[i];
533     switch (ArgTy->getTypeID()) {
534     default: llvm_unreachable("Unknown argument type for function call!");
535     case Type::IntegerTyID:
536         C = ConstantInt::get(F->getContext(), AV.IntVal);
537         break;
538     case Type::FloatTyID:
539         C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
540         break;
541     case Type::DoubleTyID:
542         C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
543         break;
544     case Type::PPC_FP128TyID:
545     case Type::X86_FP80TyID:
546     case Type::FP128TyID:
547         C = ConstantFP::get(F->getContext(), APFloat(AV.IntVal));
548         break;
549     case Type::PointerTyID:
550       void *ArgPtr = GVTOP(AV);
551       if (sizeof(void*) == 4)
552         C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
553                              (int)(intptr_t)ArgPtr);
554       else
555         C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
556                              (intptr_t)ArgPtr);
557       // Cast the integer to pointer
558       C = ConstantExpr::getIntToPtr(C, ArgTy);
559       break;
560     }
561     Args.push_back(C);
562   }
563
564   CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
565                                        "", StubBB);
566   TheCall->setCallingConv(F->getCallingConv());
567   TheCall->setTailCall();
568   if (!TheCall->getType()->isVoidTy())
569     // Return result of the call.
570     ReturnInst::Create(F->getContext(), TheCall, StubBB);
571   else
572     ReturnInst::Create(F->getContext(), StubBB);           // Just return void.
573
574   // Finally, call our nullary stub function.
575   GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
576   // Erase it, since no other function can have a reference to it.
577   Stub->eraseFromParent();
578   // And return the result.
579   return Result;
580 }
581
582 void JIT::RegisterJITEventListener(JITEventListener *L) {
583   if (L == NULL)
584     return;
585   MutexGuard locked(lock);
586   EventListeners.push_back(L);
587 }
588 void JIT::UnregisterJITEventListener(JITEventListener *L) {
589   if (L == NULL)
590     return;
591   MutexGuard locked(lock);
592   std::vector<JITEventListener*>::reverse_iterator I=
593       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
594   if (I != EventListeners.rend()) {
595     std::swap(*I, EventListeners.back());
596     EventListeners.pop_back();
597   }
598 }
599 void JIT::NotifyFunctionEmitted(
600     const Function &F,
601     void *Code, size_t Size,
602     const JITEvent_EmittedFunctionDetails &Details) {
603   MutexGuard locked(lock);
604   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
605     EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
606   }
607 }
608
609 void JIT::NotifyFreeingMachineCode(void *OldPtr) {
610   MutexGuard locked(lock);
611   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
612     EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
613   }
614 }
615
616 /// runJITOnFunction - Run the FunctionPassManager full of
617 /// just-in-time compilation passes on F, hopefully filling in
618 /// GlobalAddress[F] with the address of F's machine code.
619 ///
620 void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
621   MutexGuard locked(lock);
622
623   class MCIListener : public JITEventListener {
624     MachineCodeInfo *const MCI;
625    public:
626     MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
627     virtual void NotifyFunctionEmitted(const Function &,
628                                        void *Code, size_t Size,
629                                        const EmittedFunctionDetails &) {
630       MCI->setAddress(Code);
631       MCI->setSize(Size);
632     }
633   };
634   MCIListener MCIL(MCI);
635   if (MCI)
636     RegisterJITEventListener(&MCIL);
637
638   runJITOnFunctionUnlocked(F, locked);
639
640   if (MCI)
641     UnregisterJITEventListener(&MCIL);
642 }
643
644 void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
645   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
646
647   jitTheFunction(F, locked);
648
649   // If the function referred to another function that had not yet been
650   // read from bitcode, and we are jitting non-lazily, emit it now.
651   while (!jitstate->getPendingFunctions(locked).empty()) {
652     Function *PF = jitstate->getPendingFunctions(locked).back();
653     jitstate->getPendingFunctions(locked).pop_back();
654
655     assert(!PF->hasAvailableExternallyLinkage() &&
656            "Externally-defined function should not be in pending list.");
657
658     jitTheFunction(PF, locked);
659
660     // Now that the function has been jitted, ask the JITEmitter to rewrite
661     // the stub with real address of the function.
662     updateFunctionStub(PF);
663   }
664 }
665
666 void JIT::jitTheFunction(Function *F, const MutexGuard &locked) {
667   isAlreadyCodeGenerating = true;
668   jitstate->getPM(locked).run(*F);
669   isAlreadyCodeGenerating = false;
670
671   // clear basic block addresses after this function is done
672   getBasicBlockAddressMap(locked).clear();
673 }
674
675 /// getPointerToFunction - This method is used to get the address of the
676 /// specified function, compiling it if necessary.
677 ///
678 void *JIT::getPointerToFunction(Function *F) {
679
680   if (void *Addr = getPointerToGlobalIfAvailable(F))
681     return Addr;   // Check if function already code gen'd
682
683   MutexGuard locked(lock);
684
685   // Now that this thread owns the lock, make sure we read in the function if it
686   // exists in this Module.
687   std::string ErrorMsg;
688   if (F->Materialize(&ErrorMsg)) {
689     report_fatal_error("Error reading function '" + F->getName()+
690                       "' from bitcode file: " + ErrorMsg);
691   }
692
693   // ... and check if another thread has already code gen'd the function.
694   if (void *Addr = getPointerToGlobalIfAvailable(F))
695     return Addr;
696
697   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
698     bool AbortOnFailure = !F->hasExternalWeakLinkage();
699     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
700     addGlobalMapping(F, Addr);
701     return Addr;
702   }
703
704   runJITOnFunctionUnlocked(F, locked);
705
706   void *Addr = getPointerToGlobalIfAvailable(F);
707   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
708   return Addr;
709 }
710
711 void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
712   MutexGuard locked(lock);
713
714   BasicBlockAddressMapTy::iterator I =
715     getBasicBlockAddressMap(locked).find(BB);
716   if (I == getBasicBlockAddressMap(locked).end()) {
717     getBasicBlockAddressMap(locked)[BB] = Addr;
718   } else {
719     // ignore repeats: some BBs can be split into few MBBs?
720   }
721 }
722
723 void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
724   MutexGuard locked(lock);
725   getBasicBlockAddressMap(locked).erase(BB);
726 }
727
728 void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
729   // make sure it's function is compiled by JIT
730   (void)getPointerToFunction(BB->getParent());
731
732   // resolve basic block address
733   MutexGuard locked(lock);
734
735   BasicBlockAddressMapTy::iterator I =
736     getBasicBlockAddressMap(locked).find(BB);
737   if (I != getBasicBlockAddressMap(locked).end()) {
738     return I->second;
739   } else {
740     assert(0 && "JIT does not have BB address for address-of-label, was"
741            " it eliminated by optimizer?");
742     return 0;
743   }
744 }
745
746 /// getOrEmitGlobalVariable - Return the address of the specified global
747 /// variable, possibly emitting it to memory if needed.  This is used by the
748 /// Emitter.
749 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
750   MutexGuard locked(lock);
751
752   void *Ptr = getPointerToGlobalIfAvailable(GV);
753   if (Ptr) return Ptr;
754
755   // If the global is external, just remember the address.
756   if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
757 #if HAVE___DSO_HANDLE
758     if (GV->getName() == "__dso_handle")
759       return (void*)&__dso_handle;
760 #endif
761     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
762     if (Ptr == 0) {
763       report_fatal_error("Could not resolve external global address: "
764                         +GV->getName());
765     }
766     addGlobalMapping(GV, Ptr);
767   } else {
768     // If the global hasn't been emitted to memory yet, allocate space and
769     // emit it into memory.
770     Ptr = getMemoryForGV(GV);
771     addGlobalMapping(GV, Ptr);
772     EmitGlobalVariable(GV);  // Initialize the variable.
773   }
774   return Ptr;
775 }
776
777 /// recompileAndRelinkFunction - This method is used to force a function
778 /// which has already been compiled, to be compiled again, possibly
779 /// after it has been modified. Then the entry to the old copy is overwritten
780 /// with a branch to the new copy. If there was no old copy, this acts
781 /// just like JIT::getPointerToFunction().
782 ///
783 void *JIT::recompileAndRelinkFunction(Function *F) {
784   void *OldAddr = getPointerToGlobalIfAvailable(F);
785
786   // If it's not already compiled there is no reason to patch it up.
787   if (OldAddr == 0) { return getPointerToFunction(F); }
788
789   // Delete the old function mapping.
790   addGlobalMapping(F, 0);
791
792   // Recodegen the function
793   runJITOnFunction(F);
794
795   // Update state, forward the old function to the new function.
796   void *Addr = getPointerToGlobalIfAvailable(F);
797   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
798   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
799   return Addr;
800 }
801
802 /// getMemoryForGV - This method abstracts memory allocation of global
803 /// variable so that the JIT can allocate thread local variables depending
804 /// on the target.
805 ///
806 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
807   char *Ptr;
808
809   // GlobalVariable's which are not "constant" will cause trouble in a server
810   // situation. It's returned in the same block of memory as code which may
811   // not be writable.
812   if (isGVCompilationDisabled() && !GV->isConstant()) {
813     report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
814   }
815
816   // Some applications require globals and code to live together, so they may
817   // be allocated into the same buffer, but in general globals are allocated
818   // through the memory manager which puts them near the code but not in the
819   // same buffer.
820   const Type *GlobalType = GV->getType()->getElementType();
821   size_t S = getTargetData()->getTypeAllocSize(GlobalType);
822   size_t A = getTargetData()->getPreferredAlignment(GV);
823   if (GV->isThreadLocal()) {
824     MutexGuard locked(lock);
825     Ptr = TJI.allocateThreadLocalMemory(S);
826   } else if (TJI.allocateSeparateGVMemory()) {
827     if (A <= 8) {
828       Ptr = (char*)malloc(S);
829     } else {
830       // Allocate S+A bytes of memory, then use an aligned pointer within that
831       // space.
832       Ptr = (char*)malloc(S+A);
833       unsigned MisAligned = ((intptr_t)Ptr & (A-1));
834       Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
835     }
836   } else if (AllocateGVsWithCode) {
837     Ptr = (char*)JCE->allocateSpace(S, A);
838   } else {
839     Ptr = (char*)JCE->allocateGlobal(S, A);
840   }
841   return Ptr;
842 }
843
844 void JIT::addPendingFunction(Function *F) {
845   MutexGuard locked(lock);
846   jitstate->getPendingFunctions(locked).push_back(F);
847 }
848
849
850 JITEventListener::~JITEventListener() {}