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