ab0c1a680bd59ef9b15d62fb388d2703b5dad9c3
[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/ADT/SmallPtrSet.h"
17 #include "llvm/CodeGen/JITCodeEmitter.h"
18 #include "llvm/CodeGen/MachineCodeInfo.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/ExecutionEngine/GenericValue.h"
21 #include "llvm/ExecutionEngine/JITEventListener.h"
22 #include "llvm/ExecutionEngine/JITMemoryManager.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/DynamicLibrary.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Target/TargetJITInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38
39 using namespace llvm;
40
41 #ifdef __APPLE__
42 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
43 // of atexit). It passes the address of linker generated symbol __dso_handle
44 // to the function.
45 // This configuration change happened at version 5330.
46 # include <AvailabilityMacros.h>
47 # if defined(MAC_OS_X_VERSION_10_4) && \
48      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
49       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
50        __APPLE_CC__ >= 5330))
51 #  ifndef HAVE___DSO_HANDLE
52 #   define HAVE___DSO_HANDLE 1
53 #  endif
54 # endif
55 #endif
56
57 #if HAVE___DSO_HANDLE
58 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
59 #endif
60
61 namespace {
62
63 static struct RegisterJIT {
64   RegisterJIT() { JIT::Register(); }
65 } JITRegistrator;
66
67 }
68
69 extern "C" void LLVMLinkInJIT() {
70 }
71
72 /// createJIT - This is the factory method for creating a JIT for the current
73 /// machine, it does not fall back to the interpreter.  This takes ownership
74 /// of the module.
75 ExecutionEngine *JIT::createJIT(Module *M,
76                                 std::string *ErrorStr,
77                                 JITMemoryManager *JMM,
78                                 bool GVsWithCode,
79                                 TargetMachine *TM) {
80   // Try to register the program as a source of symbols to resolve against.
81   //
82   // FIXME: Don't do this here.
83   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
84
85   // If the target supports JIT code generation, create the JIT.
86   if (TargetJITInfo *TJ = TM->getSubtargetImpl()->getJITInfo()) {
87     return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
88   } else {
89     if (ErrorStr)
90       *ErrorStr = "target does not support JIT code generation";
91     return nullptr;
92   }
93 }
94
95 namespace {
96 /// This class supports the global getPointerToNamedFunction(), which allows
97 /// bugpoint or gdb users to search for a function by name without any context.
98 class JitPool {
99   SmallPtrSet<JIT*, 1> JITs;  // Optimize for process containing just 1 JIT.
100   mutable sys::Mutex Lock;
101 public:
102   void Add(JIT *jit) {
103     MutexGuard guard(Lock);
104     JITs.insert(jit);
105   }
106   void Remove(JIT *jit) {
107     MutexGuard guard(Lock);
108     JITs.erase(jit);
109   }
110   void *getPointerToNamedFunction(const char *Name) const {
111     MutexGuard guard(Lock);
112     assert(JITs.size() != 0 && "No Jit registered");
113     //search function in every instance of JIT
114     for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
115            end = JITs.end();
116          Jit != end; ++Jit) {
117       if (Function *F = (*Jit)->FindFunctionNamed(Name))
118         return (*Jit)->getPointerToFunction(F);
119     }
120     // The function is not available : fallback on the first created (will
121     // search in symbol of the current program/library)
122     return (*JITs.begin())->getPointerToNamedFunction(Name);
123   }
124 };
125 ManagedStatic<JitPool> AllJits;
126 }
127 extern "C" {
128   // getPointerToNamedFunction - This function is used as a global wrapper to
129   // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
130   // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
131   // need to resolve function(s) that are being mis-codegenerated, so we need to
132   // resolve their addresses at runtime, and this is the way to do it.
133   void *getPointerToNamedFunction(const char *Name) {
134     return AllJits->getPointerToNamedFunction(Name);
135   }
136 }
137
138 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
139          JITMemoryManager *jmm, bool GVsWithCode)
140   : ExecutionEngine(M), TM(tm), TJI(tji),
141     JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
142     AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
143   setDataLayout(TM.getSubtargetImpl()->getDataLayout());
144
145   jitstate = new JITState(M);
146
147   // Initialize JCE
148   JCE = createEmitter(*this, JMM, TM);
149
150   // Register in global list of all JITs.
151   AllJits->Add(this);
152
153   // Add target data
154   MutexGuard locked(lock);
155   FunctionPassManager &PM = jitstate->getPM();
156   M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
157   PM.add(new DataLayoutPass(M));
158
159   // Turn the machine code intermediate representation into bytes in memory that
160   // may be executed.
161   if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
162     report_fatal_error("Target does not support machine code emission!");
163   }
164
165   // Initialize passes.
166   PM.doInitialization();
167 }
168
169 JIT::~JIT() {
170   // Cleanup.
171   AllJits->Remove(this);
172   delete jitstate;
173   delete JCE;
174   // JMM is a ownership of JCE, so we no need delete JMM here.
175   delete &TM;
176 }
177
178 /// addModule - Add a new Module to the JIT.  If we previously removed the last
179 /// Module, we need re-initialize jitstate with a valid Module.
180 void JIT::addModule(Module *M) {
181   MutexGuard locked(lock);
182
183   if (Modules.empty()) {
184     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
185
186     jitstate = new JITState(M);
187
188     FunctionPassManager &PM = jitstate->getPM();
189     M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
190     PM.add(new DataLayoutPass(M));
191
192     // Turn the machine code intermediate representation into bytes in memory
193     // that may be executed.
194     if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
195       report_fatal_error("Target does not support machine code emission!");
196     }
197
198     // Initialize passes.
199     PM.doInitialization();
200   }
201
202   ExecutionEngine::addModule(M);
203 }
204
205 /// removeModule - If we are removing the last Module, invalidate the jitstate
206 /// since the PassManager it contains references a released Module.
207 bool JIT::removeModule(Module *M) {
208   bool result = ExecutionEngine::removeModule(M);
209
210   MutexGuard locked(lock);
211
212   if (jitstate && jitstate->getModule() == M) {
213     delete jitstate;
214     jitstate = nullptr;
215   }
216
217   if (!jitstate && !Modules.empty()) {
218     jitstate = new JITState(Modules[0]);
219
220     FunctionPassManager &PM = jitstate->getPM();
221     M->setDataLayout(TM.getSubtargetImpl()->getDataLayout());
222     PM.add(new DataLayoutPass(M));
223
224     // Turn the machine code intermediate representation into bytes in memory
225     // that may be executed.
226     if (TM.addPassesToEmitMachineCode(PM, *JCE, !getVerifyModules())) {
227       report_fatal_error("Target does not support machine code emission!");
228     }
229
230     // Initialize passes.
231     PM.doInitialization();
232   }
233   return result;
234 }
235
236 /// run - Start execution with the specified function and arguments.
237 ///
238 GenericValue JIT::runFunction(Function *F,
239                               const std::vector<GenericValue> &ArgValues) {
240   assert(F && "Function *F was null at entry to run()");
241
242   void *FPtr = getPointerToFunction(F);
243   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
244   FunctionType *FTy = F->getFunctionType();
245   Type *RetTy = FTy->getReturnType();
246
247   assert((FTy->getNumParams() == ArgValues.size() ||
248           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
249          "Wrong number of arguments passed into function!");
250   assert(FTy->getNumParams() == ArgValues.size() &&
251          "This doesn't support passing arguments through varargs (yet)!");
252
253   // Handle some common cases first.  These cases correspond to common `main'
254   // prototypes.
255   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
256     switch (ArgValues.size()) {
257     case 3:
258       if (FTy->getParamType(0)->isIntegerTy(32) &&
259           FTy->getParamType(1)->isPointerTy() &&
260           FTy->getParamType(2)->isPointerTy()) {
261         int (*PF)(int, char **, const char **) =
262           (int(*)(int, char **, const char **))(intptr_t)FPtr;
263
264         // Call the function.
265         GenericValue rv;
266         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
267                                  (char **)GVTOP(ArgValues[1]),
268                                  (const char **)GVTOP(ArgValues[2])));
269         return rv;
270       }
271       break;
272     case 2:
273       if (FTy->getParamType(0)->isIntegerTy(32) &&
274           FTy->getParamType(1)->isPointerTy()) {
275         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
276
277         // Call the function.
278         GenericValue rv;
279         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
280                                  (char **)GVTOP(ArgValues[1])));
281         return rv;
282       }
283       break;
284     case 1:
285       if (FTy->getParamType(0)->isIntegerTy(32)) {
286         GenericValue rv;
287         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
288         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
289         return rv;
290       }
291       if (FTy->getParamType(0)->isPointerTy()) {
292         GenericValue rv;
293         int (*PF)(char *) = (int(*)(char *))(intptr_t)FPtr;
294         rv.IntVal = APInt(32, PF((char*)GVTOP(ArgValues[0])));
295         return rv;
296       }
297       break;
298     }
299   }
300
301   // Handle cases where no arguments are passed first.
302   if (ArgValues.empty()) {
303     GenericValue rv;
304     switch (RetTy->getTypeID()) {
305     default: llvm_unreachable("Unknown return type for function call!");
306     case Type::IntegerTyID: {
307       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
308       if (BitWidth == 1)
309         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
310       else if (BitWidth <= 8)
311         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
312       else if (BitWidth <= 16)
313         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
314       else if (BitWidth <= 32)
315         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
316       else if (BitWidth <= 64)
317         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
318       else
319         llvm_unreachable("Integer types > 64 bits not supported");
320       return rv;
321     }
322     case Type::VoidTyID:
323       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
324       return rv;
325     case Type::FloatTyID:
326       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
327       return rv;
328     case Type::DoubleTyID:
329       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
330       return rv;
331     case Type::X86_FP80TyID:
332     case Type::FP128TyID:
333     case Type::PPC_FP128TyID:
334       llvm_unreachable("long double not supported yet");
335     case Type::PointerTyID:
336       return PTOGV(((void*(*)())(intptr_t)FPtr)());
337     }
338   }
339
340   // Okay, this is not one of our quick and easy cases.  Because we don't have a
341   // full FFI, we have to codegen a nullary stub function that just calls the
342   // function we are interested in, passing in constants for all of the
343   // arguments.  Make this function and return.
344
345   // First, create the function.
346   FunctionType *STy=FunctionType::get(RetTy, false);
347   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
348                                     F->getParent());
349
350   // Insert a basic block.
351   BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
352
353   // Convert all of the GenericValue arguments over to constants.  Note that we
354   // currently don't support varargs.
355   SmallVector<Value*, 8> Args;
356   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
357     Constant *C = nullptr;
358     Type *ArgTy = FTy->getParamType(i);
359     const GenericValue &AV = ArgValues[i];
360     switch (ArgTy->getTypeID()) {
361     default: llvm_unreachable("Unknown argument type for function call!");
362     case Type::IntegerTyID:
363         C = ConstantInt::get(F->getContext(), AV.IntVal);
364         break;
365     case Type::FloatTyID:
366         C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
367         break;
368     case Type::DoubleTyID:
369         C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
370         break;
371     case Type::PPC_FP128TyID:
372     case Type::X86_FP80TyID:
373     case Type::FP128TyID:
374         C = ConstantFP::get(F->getContext(), APFloat(ArgTy->getFltSemantics(),
375                                                      AV.IntVal));
376         break;
377     case Type::PointerTyID:
378       void *ArgPtr = GVTOP(AV);
379       if (sizeof(void*) == 4)
380         C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
381                              (int)(intptr_t)ArgPtr);
382       else
383         C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
384                              (intptr_t)ArgPtr);
385       // Cast the integer to pointer
386       C = ConstantExpr::getIntToPtr(C, ArgTy);
387       break;
388     }
389     Args.push_back(C);
390   }
391
392   CallInst *TheCall = CallInst::Create(F, Args, "", StubBB);
393   TheCall->setCallingConv(F->getCallingConv());
394   TheCall->setTailCall();
395   if (!TheCall->getType()->isVoidTy())
396     // Return result of the call.
397     ReturnInst::Create(F->getContext(), TheCall, StubBB);
398   else
399     ReturnInst::Create(F->getContext(), StubBB);           // Just return void.
400
401   // Finally, call our nullary stub function.
402   GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
403   // Erase it, since no other function can have a reference to it.
404   Stub->eraseFromParent();
405   // And return the result.
406   return Result;
407 }
408
409 void JIT::RegisterJITEventListener(JITEventListener *L) {
410   if (!L)
411     return;
412   MutexGuard locked(lock);
413   EventListeners.push_back(L);
414 }
415 void JIT::UnregisterJITEventListener(JITEventListener *L) {
416   if (!L)
417     return;
418   MutexGuard locked(lock);
419   std::vector<JITEventListener*>::reverse_iterator I=
420       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
421   if (I != EventListeners.rend()) {
422     std::swap(*I, EventListeners.back());
423     EventListeners.pop_back();
424   }
425 }
426 void JIT::NotifyFunctionEmitted(
427     const Function &F,
428     void *Code, size_t Size,
429     const JITEvent_EmittedFunctionDetails &Details) {
430   MutexGuard locked(lock);
431   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
432     EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
433   }
434 }
435
436 void JIT::NotifyFreeingMachineCode(void *OldPtr) {
437   MutexGuard locked(lock);
438   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
439     EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
440   }
441 }
442
443 /// runJITOnFunction - Run the FunctionPassManager full of
444 /// just-in-time compilation passes on F, hopefully filling in
445 /// GlobalAddress[F] with the address of F's machine code.
446 ///
447 void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
448   MutexGuard locked(lock);
449
450   class MCIListener : public JITEventListener {
451     MachineCodeInfo *const MCI;
452    public:
453     MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
454     void NotifyFunctionEmitted(const Function &, void *Code, size_t Size,
455                                const EmittedFunctionDetails &) override {
456       MCI->setAddress(Code);
457       MCI->setSize(Size);
458     }
459   };
460   MCIListener MCIL(MCI);
461   if (MCI)
462     RegisterJITEventListener(&MCIL);
463
464   runJITOnFunctionUnlocked(F);
465
466   if (MCI)
467     UnregisterJITEventListener(&MCIL);
468 }
469
470 void JIT::runJITOnFunctionUnlocked(Function *F) {
471   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
472
473   jitTheFunctionUnlocked(F);
474
475   // If the function referred to another function that had not yet been
476   // read from bitcode, and we are jitting non-lazily, emit it now.
477   while (!jitstate->getPendingFunctions().empty()) {
478     Function *PF = jitstate->getPendingFunctions().back();
479     jitstate->getPendingFunctions().pop_back();
480
481     assert(!PF->hasAvailableExternallyLinkage() &&
482            "Externally-defined function should not be in pending list.");
483
484     jitTheFunctionUnlocked(PF);
485
486     // Now that the function has been jitted, ask the JITEmitter to rewrite
487     // the stub with real address of the function.
488     updateFunctionStubUnlocked(PF);
489   }
490 }
491
492 void JIT::jitTheFunctionUnlocked(Function *F) {
493   isAlreadyCodeGenerating = true;
494   jitstate->getPM().run(*F);
495   isAlreadyCodeGenerating = false;
496
497   // clear basic block addresses after this function is done
498   getBasicBlockAddressMap().clear();
499 }
500
501 /// getPointerToFunction - This method is used to get the address of the
502 /// specified function, compiling it if necessary.
503 ///
504 void *JIT::getPointerToFunction(Function *F) {
505
506   if (void *Addr = getPointerToGlobalIfAvailable(F))
507     return Addr;   // Check if function already code gen'd
508
509   MutexGuard locked(lock);
510
511   // Now that this thread owns the lock, make sure we read in the function if it
512   // exists in this Module.
513   std::string ErrorMsg;
514   if (F->Materialize(&ErrorMsg)) {
515     report_fatal_error("Error reading function '" + F->getName()+
516                       "' from bitcode file: " + ErrorMsg);
517   }
518
519   // ... and check if another thread has already code gen'd the function.
520   if (void *Addr = getPointerToGlobalIfAvailable(F))
521     return Addr;
522
523   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
524     bool AbortOnFailure = !F->hasExternalWeakLinkage();
525     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
526     addGlobalMapping(F, Addr);
527     return Addr;
528   }
529
530   runJITOnFunctionUnlocked(F);
531
532   void *Addr = getPointerToGlobalIfAvailable(F);
533   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
534   return Addr;
535 }
536
537 void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
538   MutexGuard locked(lock);
539
540   BasicBlockAddressMapTy::iterator I =
541     getBasicBlockAddressMap().find(BB);
542   if (I == getBasicBlockAddressMap().end()) {
543     getBasicBlockAddressMap()[BB] = Addr;
544   } else {
545     // ignore repeats: some BBs can be split into few MBBs?
546   }
547 }
548
549 void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
550   MutexGuard locked(lock);
551   getBasicBlockAddressMap().erase(BB);
552 }
553
554 void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
555   // make sure it's function is compiled by JIT
556   (void)getPointerToFunction(BB->getParent());
557
558   // resolve basic block address
559   MutexGuard locked(lock);
560
561   BasicBlockAddressMapTy::iterator I =
562     getBasicBlockAddressMap().find(BB);
563   if (I != getBasicBlockAddressMap().end()) {
564     return I->second;
565   } else {
566     llvm_unreachable("JIT does not have BB address for address-of-label, was"
567                      " it eliminated by optimizer?");
568   }
569 }
570
571 void *JIT::getPointerToNamedFunction(const std::string &Name,
572                                      bool AbortOnFailure){
573   if (!isSymbolSearchingDisabled()) {
574     void *ptr = JMM->getPointerToNamedFunction(Name, false);
575     if (ptr)
576       return ptr;
577   }
578
579   /// If a LazyFunctionCreator is installed, use it to get/create the function.
580   if (LazyFunctionCreator)
581     if (void *RP = LazyFunctionCreator(Name))
582       return RP;
583
584   if (AbortOnFailure) {
585     report_fatal_error("Program used external function '"+Name+
586                       "' which could not be resolved!");
587   }
588   return nullptr;
589 }
590
591
592 /// getOrEmitGlobalVariable - Return the address of the specified global
593 /// variable, possibly emitting it to memory if needed.  This is used by the
594 /// Emitter.
595 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
596   MutexGuard locked(lock);
597
598   void *Ptr = getPointerToGlobalIfAvailable(GV);
599   if (Ptr) return Ptr;
600
601   // If the global is external, just remember the address.
602   if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
603 #if HAVE___DSO_HANDLE
604     if (GV->getName() == "__dso_handle")
605       return (void*)&__dso_handle;
606 #endif
607     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
608     if (!Ptr) {
609       report_fatal_error("Could not resolve external global address: "
610                         +GV->getName());
611     }
612     addGlobalMapping(GV, Ptr);
613   } else {
614     // If the global hasn't been emitted to memory yet, allocate space and
615     // emit it into memory.
616     Ptr = getMemoryForGV(GV);
617     addGlobalMapping(GV, Ptr);
618     EmitGlobalVariable(GV);  // Initialize the variable.
619   }
620   return Ptr;
621 }
622
623 /// recompileAndRelinkFunction - This method is used to force a function
624 /// which has already been compiled, to be compiled again, possibly
625 /// after it has been modified. Then the entry to the old copy is overwritten
626 /// with a branch to the new copy. If there was no old copy, this acts
627 /// just like JIT::getPointerToFunction().
628 ///
629 void *JIT::recompileAndRelinkFunction(Function *F) {
630   void *OldAddr = getPointerToGlobalIfAvailable(F);
631
632   // If it's not already compiled there is no reason to patch it up.
633   if (!OldAddr) return getPointerToFunction(F);
634
635   // Delete the old function mapping.
636   addGlobalMapping(F, nullptr);
637
638   // Recodegen the function
639   runJITOnFunction(F);
640
641   // Update state, forward the old function to the new function.
642   void *Addr = getPointerToGlobalIfAvailable(F);
643   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
644   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
645   return Addr;
646 }
647
648 /// getMemoryForGV - This method abstracts memory allocation of global
649 /// variable so that the JIT can allocate thread local variables depending
650 /// on the target.
651 ///
652 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
653   char *Ptr;
654
655   // GlobalVariable's which are not "constant" will cause trouble in a server
656   // situation. It's returned in the same block of memory as code which may
657   // not be writable.
658   if (isGVCompilationDisabled() && !GV->isConstant()) {
659     report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
660   }
661
662   // Some applications require globals and code to live together, so they may
663   // be allocated into the same buffer, but in general globals are allocated
664   // through the memory manager which puts them near the code but not in the
665   // same buffer.
666   Type *GlobalType = GV->getType()->getElementType();
667   size_t S = getDataLayout()->getTypeAllocSize(GlobalType);
668   size_t A = getDataLayout()->getPreferredAlignment(GV);
669   if (GV->isThreadLocal()) {
670     MutexGuard locked(lock);
671     Ptr = TJI.allocateThreadLocalMemory(S);
672   } else if (TJI.allocateSeparateGVMemory()) {
673     if (A <= 8) {
674       Ptr = (char*)malloc(S);
675     } else {
676       // Allocate S+A bytes of memory, then use an aligned pointer within that
677       // space.
678       Ptr = (char*)malloc(S+A);
679       unsigned MisAligned = ((intptr_t)Ptr & (A-1));
680       Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
681     }
682   } else if (AllocateGVsWithCode) {
683     Ptr = (char*)JCE->allocateSpace(S, A);
684   } else {
685     Ptr = (char*)JCE->allocateGlobal(S, A);
686   }
687   return Ptr;
688 }
689
690 void JIT::addPendingFunction(Function *F) {
691   MutexGuard locked(lock);
692   jitstate->getPendingFunctions().push_back(F);
693 }
694
695
696 JITEventListener::~JITEventListener() {}