0490343b861d4fdba18b184fb55982db4ad8de01
[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/ModuleProvider.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetJITInfo.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/MutexGuard.h"
29 #include "llvm/System/DynamicLibrary.h"
30 #include "llvm/Config/config.h"
31
32 using namespace llvm;
33
34 #ifdef __APPLE__ 
35 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
36 // of atexit). It passes the address of linker generated symbol __dso_handle
37 // to the function.
38 // This configuration change happened at version 5330.
39 # include <AvailabilityMacros.h>
40 # if defined(MAC_OS_X_VERSION_10_4) && \
41      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
42       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
43        __APPLE_CC__ >= 5330))
44 #  ifndef HAVE___DSO_HANDLE
45 #   define HAVE___DSO_HANDLE 1
46 #  endif
47 # endif
48 #endif
49
50 #if HAVE___DSO_HANDLE
51 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
52 #endif
53
54 namespace {
55
56 static struct RegisterJIT {
57   RegisterJIT() { JIT::Register(); }
58 } JITRegistrator;
59
60 }
61
62 namespace llvm {
63   void LinkInJIT() {
64   }
65 }
66
67
68 #if defined(__GNUC__) && !defined(__ARM__EABI__)
69  
70 // libgcc defines the __register_frame function to dynamically register new
71 // dwarf frames for exception handling. This functionality is not portable
72 // across compilers and is only provided by GCC. We use the __register_frame
73 // function here so that code generated by the JIT cooperates with the unwinding
74 // runtime of libgcc. When JITting with exception handling enable, LLVM
75 // generates dwarf frames and registers it to libgcc with __register_frame.
76 //
77 // The __register_frame function works with Linux.
78 //
79 // Unfortunately, this functionality seems to be in libgcc after the unwinding
80 // library of libgcc for darwin was written. The code for darwin overwrites the
81 // value updated by __register_frame with a value fetched with "keymgr".
82 // "keymgr" is an obsolete functionality, which should be rewritten some day.
83 // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
84 // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
85 // values of an opaque key, used by libgcc to find dwarf tables.
86
87 extern "C" void __register_frame(void*);
88
89 #if defined(__APPLE__)
90
91 namespace {
92
93 // LibgccObject - This is the structure defined in libgcc. There is no #include
94 // provided for this structure, so we also define it here. libgcc calls it
95 // "struct object". The structure is undocumented in libgcc.
96 struct LibgccObject {
97   void *unused1;
98   void *unused2;
99   void *unused3;
100   
101   /// frame - Pointer to the exception table.
102   void *frame;
103   
104   /// encoding -  The encoding of the object?
105   union {
106     struct {
107       unsigned long sorted : 1;
108       unsigned long from_array : 1;
109       unsigned long mixed_encoding : 1;
110       unsigned long encoding : 8;
111       unsigned long count : 21; 
112     } b;
113     size_t i;
114   } encoding;
115   
116   /// fde_end - libgcc defines this field only if some macro is defined. We
117   /// include this field even if it may not there, to make libgcc happy.
118   char *fde_end;
119   
120   /// next - At least we know it's a chained list!
121   struct LibgccObject *next;
122 };
123
124 // "kemgr" stuff. Apparently, all frame tables are stored there.
125 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
126 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
127 #define KEYMGR_GCC3_DW2_OBJ_LIST        302     /* Dwarf2 object list  */
128
129 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
130 /// probably contains all dwarf tables that are loaded.
131 struct LibgccObjectInfo {
132
133   /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
134   ///
135   struct LibgccObject* seenObjects;
136
137   /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
138   ///
139   struct LibgccObject* unseenObjects;
140   
141   unsigned unused[2];
142 };
143
144 /// darwin_register_frame - Since __register_frame does not work with darwin's
145 /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
146 /// "Dwarf2 object list" key.
147 void DarwinRegisterFrame(void* FrameBegin) {
148   // Get the key.
149   LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
150     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
151   assert(LOI && "This should be preallocated by the runtime");
152   
153   // Allocate a new LibgccObject to represent this frame. Deallocation of this
154   // object may be impossible: since darwin code in libgcc was written after
155   // the ability to dynamically register frames, things may crash if we
156   // deallocate it.
157   struct LibgccObject* ob = (struct LibgccObject*)
158     malloc(sizeof(struct LibgccObject));
159   
160   // Do like libgcc for the values of the field.
161   ob->unused1 = (void *)-1;
162   ob->unused2 = 0;
163   ob->unused3 = 0;
164   ob->frame = FrameBegin;
165   ob->encoding.i = 0; 
166   ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
167   
168   // Put the info on both places, as libgcc uses the first or the the second
169   // field. Note that we rely on having two pointers here. If fde_end was a
170   // char, things would get complicated.
171   ob->fde_end = (char*)LOI->unseenObjects;
172   ob->next = LOI->unseenObjects;
173   
174   // Update the key's unseenObjects list.
175   LOI->unseenObjects = ob;
176   
177   // Finally update the "key". Apparently, libgcc requires it. 
178   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
179                                          LOI);
180
181 }
182
183 }
184 #endif // __APPLE__
185 #endif // __GNUC__
186
187 /// createJIT - This is the factory method for creating a JIT for the current
188 /// machine, it does not fall back to the interpreter.  This takes ownership
189 /// of the module provider.
190 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
191                                             std::string *ErrorStr,
192                                             JITMemoryManager *JMM,
193                                             bool Fast) {
194   ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
195   if (!EE) return 0;
196   
197   // Make sure we can resolve symbols in the program as well. The zero arg
198   // to the function tells DynamicLibrary to load the program, not a library.
199   sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
200   return EE;
201 }
202
203 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
204          JITMemoryManager *JMM, bool Fast)
205   : ExecutionEngine(MP), TM(tm), TJI(tji) {
206   setTargetData(TM.getTargetData());
207
208   jitstate = new JITState(MP);
209
210   // Initialize MCE
211   MCE = createEmitter(*this, JMM);
212
213   // Add target data
214   MutexGuard locked(lock);
215   FunctionPassManager &PM = jitstate->getPM(locked);
216   PM.add(new TargetData(*TM.getTargetData()));
217
218   // Turn the machine code intermediate representation into bytes in memory that
219   // may be executed.
220   if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
221     cerr << "Target does not support machine code emission!\n";
222     abort();
223   }
224   
225   // Register routine for informing unwinding runtime about new EH frames
226 #if defined(__GNUC__) && !defined(__ARM_EABI__)
227 #if defined(__APPLE__)
228   struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
229     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
230   
231   // The key is created on demand, and libgcc creates it the first time an
232   // exception occurs. Since we need the key to register frames, we create
233   // it now.
234   if (!LOI) {
235     LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo)); 
236     _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
237                                            LOI);
238   }
239   InstallExceptionTableRegister(DarwinRegisterFrame);
240 #else
241   InstallExceptionTableRegister(__register_frame);
242 #endif // __APPLE__
243 #endif // __GNUC__
244   
245   // Initialize passes.
246   PM.doInitialization();
247 }
248
249 JIT::~JIT() {
250   delete jitstate;
251   delete MCE;
252   delete &TM;
253 }
254
255 /// addModuleProvider - Add a new ModuleProvider to the JIT.  If we previously
256 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
257 /// ModuleProvider.
258 void JIT::addModuleProvider(ModuleProvider *MP) {
259   MutexGuard locked(lock);
260
261   if (Modules.empty()) {
262     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
263
264     jitstate = new JITState(MP);
265
266     FunctionPassManager &PM = jitstate->getPM(locked);
267     PM.add(new TargetData(*TM.getTargetData()));
268
269     // Turn the machine code intermediate representation into bytes in memory
270     // that may be executed.
271     if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
272       cerr << "Target does not support machine code emission!\n";
273       abort();
274     }
275     
276     // Initialize passes.
277     PM.doInitialization();
278   }
279   
280   ExecutionEngine::addModuleProvider(MP);
281 }
282
283 /// removeModuleProvider - If we are removing the last ModuleProvider, 
284 /// invalidate the jitstate since the PassManager it contains references a
285 /// released ModuleProvider.
286 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
287   Module *result = ExecutionEngine::removeModuleProvider(MP, E);
288   
289   MutexGuard locked(lock);
290   
291   if (jitstate->getMP() == MP) {
292     delete jitstate;
293     jitstate = 0;
294   }
295   
296   if (!jitstate && !Modules.empty()) {
297     jitstate = new JITState(Modules[0]);
298
299     FunctionPassManager &PM = jitstate->getPM(locked);
300     PM.add(new TargetData(*TM.getTargetData()));
301     
302     // Turn the machine code intermediate representation into bytes in memory
303     // that may be executed.
304     if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
305       cerr << "Target does not support machine code emission!\n";
306       abort();
307     }
308     
309     // Initialize passes.
310     PM.doInitialization();
311   }    
312   return result;
313 }
314
315 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
316 /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
317 /// the underlying module.
318 void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
319   ExecutionEngine::deleteModuleProvider(MP, E);
320   
321   MutexGuard locked(lock);
322   
323   if (jitstate->getMP() == MP) {
324     delete jitstate;
325     jitstate = 0;
326   }
327
328   if (!jitstate && !Modules.empty()) {
329     jitstate = new JITState(Modules[0]);
330     
331     FunctionPassManager &PM = jitstate->getPM(locked);
332     PM.add(new TargetData(*TM.getTargetData()));
333     
334     // Turn the machine code intermediate representation into bytes in memory
335     // that may be executed.
336     if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
337       cerr << "Target does not support machine code emission!\n";
338       abort();
339     }
340     
341     // Initialize passes.
342     PM.doInitialization();
343   }    
344 }
345
346 /// run - Start execution with the specified function and arguments.
347 ///
348 GenericValue JIT::runFunction(Function *F,
349                               const std::vector<GenericValue> &ArgValues) {
350   assert(F && "Function *F was null at entry to run()");
351
352   void *FPtr = getPointerToFunction(F);
353   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
354   const FunctionType *FTy = F->getFunctionType();
355   const Type *RetTy = FTy->getReturnType();
356
357   assert((FTy->getNumParams() == ArgValues.size() ||
358           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
359          "Wrong number of arguments passed into function!");
360   assert(FTy->getNumParams() == ArgValues.size() &&
361          "This doesn't support passing arguments through varargs (yet)!");
362
363   // Handle some common cases first.  These cases correspond to common `main'
364   // prototypes.
365   if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
366     switch (ArgValues.size()) {
367     case 3:
368       if (FTy->getParamType(0) == Type::Int32Ty &&
369           isa<PointerType>(FTy->getParamType(1)) &&
370           isa<PointerType>(FTy->getParamType(2))) {
371         int (*PF)(int, char **, const char **) =
372           (int(*)(int, char **, const char **))(intptr_t)FPtr;
373
374         // Call the function.
375         GenericValue rv;
376         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
377                                  (char **)GVTOP(ArgValues[1]),
378                                  (const char **)GVTOP(ArgValues[2])));
379         return rv;
380       }
381       break;
382     case 2:
383       if (FTy->getParamType(0) == Type::Int32Ty &&
384           isa<PointerType>(FTy->getParamType(1))) {
385         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
386
387         // Call the function.
388         GenericValue rv;
389         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
390                                  (char **)GVTOP(ArgValues[1])));
391         return rv;
392       }
393       break;
394     case 1:
395       if (FTy->getNumParams() == 1 &&
396           FTy->getParamType(0) == Type::Int32Ty) {
397         GenericValue rv;
398         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
399         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
400         return rv;
401       }
402       break;
403     }
404   }
405
406   // Handle cases where no arguments are passed first.
407   if (ArgValues.empty()) {
408     GenericValue rv;
409     switch (RetTy->getTypeID()) {
410     default: assert(0 && "Unknown return type for function call!");
411     case Type::IntegerTyID: {
412       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
413       if (BitWidth == 1)
414         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
415       else if (BitWidth <= 8)
416         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
417       else if (BitWidth <= 16)
418         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
419       else if (BitWidth <= 32)
420         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
421       else if (BitWidth <= 64)
422         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
423       else 
424         assert(0 && "Integer types > 64 bits not supported");
425       return rv;
426     }
427     case Type::VoidTyID:
428       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
429       return rv;
430     case Type::FloatTyID:
431       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
432       return rv;
433     case Type::DoubleTyID:
434       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
435       return rv;
436     case Type::X86_FP80TyID:
437     case Type::FP128TyID:
438     case Type::PPC_FP128TyID:
439       assert(0 && "long double not supported yet");
440       return rv;
441     case Type::PointerTyID:
442       return PTOGV(((void*(*)())(intptr_t)FPtr)());
443     }
444   }
445
446   // Okay, this is not one of our quick and easy cases.  Because we don't have a
447   // full FFI, we have to codegen a nullary stub function that just calls the
448   // function we are interested in, passing in constants for all of the
449   // arguments.  Make this function and return.
450
451   // First, create the function.
452   FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
453   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
454                                     F->getParent());
455
456   // Insert a basic block.
457   BasicBlock *StubBB = BasicBlock::Create("", Stub);
458
459   // Convert all of the GenericValue arguments over to constants.  Note that we
460   // currently don't support varargs.
461   SmallVector<Value*, 8> Args;
462   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
463     Constant *C = 0;
464     const Type *ArgTy = FTy->getParamType(i);
465     const GenericValue &AV = ArgValues[i];
466     switch (ArgTy->getTypeID()) {
467     default: assert(0 && "Unknown argument type for function call!");
468     case Type::IntegerTyID:
469         C = ConstantInt::get(AV.IntVal);
470         break;
471     case Type::FloatTyID:
472         C = ConstantFP::get(APFloat(AV.FloatVal));
473         break;
474     case Type::DoubleTyID:
475         C = ConstantFP::get(APFloat(AV.DoubleVal));
476         break;
477     case Type::PPC_FP128TyID:
478     case Type::X86_FP80TyID:
479     case Type::FP128TyID:
480         C = ConstantFP::get(APFloat(AV.IntVal));
481         break;
482     case Type::PointerTyID:
483       void *ArgPtr = GVTOP(AV);
484       if (sizeof(void*) == 4)
485         C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
486       else
487         C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
488       C = ConstantExpr::getIntToPtr(C, ArgTy);  // Cast the integer to pointer
489       break;
490     }
491     Args.push_back(C);
492   }
493
494   CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
495                                        "", StubBB);
496   TheCall->setCallingConv(F->getCallingConv());
497   TheCall->setTailCall();
498   if (TheCall->getType() != Type::VoidTy)
499     ReturnInst::Create(TheCall, StubBB);    // Return result of the call.
500   else
501     ReturnInst::Create(StubBB);             // Just return void.
502
503   // Finally, return the value returned by our nullary stub function.
504   return runFunction(Stub, std::vector<GenericValue>());
505 }
506
507 /// runJITOnFunction - Run the FunctionPassManager full of
508 /// just-in-time compilation passes on F, hopefully filling in
509 /// GlobalAddress[F] with the address of F's machine code.
510 ///
511 void JIT::runJITOnFunction(Function *F) {
512   MutexGuard locked(lock);
513   runJITOnFunctionUnlocked(F, locked);
514 }
515
516 void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
517   static bool isAlreadyCodeGenerating = false;
518   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
519
520   // JIT the function
521   isAlreadyCodeGenerating = true;
522   jitstate->getPM(locked).run(*F);
523   isAlreadyCodeGenerating = false;
524
525   // If the function referred to another function that had not yet been
526   // read from bitcode, but we are jitting non-lazily, emit it now.
527   while (!jitstate->getPendingFunctions(locked).empty()) {
528     Function *PF = jitstate->getPendingFunctions(locked).back();
529     jitstate->getPendingFunctions(locked).pop_back();
530
531     // JIT the function
532     isAlreadyCodeGenerating = true;
533     jitstate->getPM(locked).run(*PF);
534     isAlreadyCodeGenerating = false;
535     
536     // Now that the function has been jitted, ask the JITEmitter to rewrite
537     // the stub with real address of the function.
538     updateFunctionStub(PF);
539   }
540   
541   // If the JIT is configured to emit info so that dlsym can be used to
542   // rewrite stubs to external globals, do so now.
543   if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
544     updateDlsymStubTable();
545 }
546
547 /// getPointerToFunction - This method is used to get the address of the
548 /// specified function, compiling it if neccesary.
549 ///
550 void *JIT::getPointerToFunction(Function *F) {
551
552   if (void *Addr = getPointerToGlobalIfAvailable(F))
553     return Addr;   // Check if function already code gen'd
554
555   MutexGuard locked(lock);
556
557   // Make sure we read in the function if it exists in this Module.
558   if (F->hasNotBeenReadFromBitcode()) {
559     // Determine the module provider this function is provided by.
560     Module *M = F->getParent();
561     ModuleProvider *MP = 0;
562     for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
563       if (Modules[i]->getModule() == M) {
564         MP = Modules[i];
565         break;
566       }
567     }
568     assert(MP && "Function isn't in a module we know about!");
569     
570     std::string ErrorMsg;
571     if (MP->materializeFunction(F, &ErrorMsg)) {
572       cerr << "Error reading function '" << F->getName()
573            << "' from bitcode file: " << ErrorMsg << "\n";
574       abort();
575     }
576
577     // Now retry to get the address.
578     if (void *Addr = getPointerToGlobalIfAvailable(F))
579       return Addr;
580   }
581
582   if (F->isDeclaration()) {
583     bool AbortOnFailure =
584       !areDlsymStubsEnabled() && !F->hasExternalWeakLinkage();
585     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
586     addGlobalMapping(F, Addr);
587     return Addr;
588   }
589
590   runJITOnFunctionUnlocked(F, locked);
591
592   void *Addr = getPointerToGlobalIfAvailable(F);
593   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
594   return Addr;
595 }
596
597 /// getOrEmitGlobalVariable - Return the address of the specified global
598 /// variable, possibly emitting it to memory if needed.  This is used by the
599 /// Emitter.
600 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
601   MutexGuard locked(lock);
602
603   void *Ptr = getPointerToGlobalIfAvailable(GV);
604   if (Ptr) return Ptr;
605
606   // If the global is external, just remember the address.
607   if (GV->isDeclaration()) {
608 #if HAVE___DSO_HANDLE
609     if (GV->getName() == "__dso_handle")
610       return (void*)&__dso_handle;
611 #endif
612     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
613     if (Ptr == 0 && !areDlsymStubsEnabled()) {
614       cerr << "Could not resolve external global address: "
615            << GV->getName() << "\n";
616       abort();
617     }
618     addGlobalMapping(GV, Ptr);
619   } else {
620     // GlobalVariable's which are not "constant" will cause trouble in a server
621     // situation. It's returned in the same block of memory as code which may
622     // not be writable.
623     if (isGVCompilationDisabled() && !GV->isConstant()) {
624       cerr << "Compilation of non-internal GlobalValue is disabled!\n";
625       abort();
626     }
627     // If the global hasn't been emitted to memory yet, allocate space and
628     // emit it into memory.  It goes in the same array as the generated
629     // code, jump tables, etc.
630     const Type *GlobalType = GV->getType()->getElementType();
631     size_t S = getTargetData()->getTypePaddedSize(GlobalType);
632     size_t A = getTargetData()->getPreferredAlignment(GV);
633     if (GV->isThreadLocal()) {
634       MutexGuard locked(lock);
635       Ptr = TJI.allocateThreadLocalMemory(S);
636     } else if (TJI.allocateSeparateGVMemory()) {
637       if (A <= 8) {
638         Ptr = malloc(S);
639       } else {
640         // Allocate S+A bytes of memory, then use an aligned pointer within that
641         // space.
642         Ptr = malloc(S+A);
643         unsigned MisAligned = ((intptr_t)Ptr & (A-1));
644         Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
645       }
646     } else {
647       Ptr = MCE->allocateSpace(S, A);
648     }
649     addGlobalMapping(GV, Ptr);
650     EmitGlobalVariable(GV);
651   }
652   return Ptr;
653 }
654
655 /// recompileAndRelinkFunction - This method is used to force a function
656 /// which has already been compiled, to be compiled again, possibly
657 /// after it has been modified. Then the entry to the old copy is overwritten
658 /// with a branch to the new copy. If there was no old copy, this acts
659 /// just like JIT::getPointerToFunction().
660 ///
661 void *JIT::recompileAndRelinkFunction(Function *F) {
662   void *OldAddr = getPointerToGlobalIfAvailable(F);
663
664   // If it's not already compiled there is no reason to patch it up.
665   if (OldAddr == 0) { return getPointerToFunction(F); }
666
667   // Delete the old function mapping.
668   addGlobalMapping(F, 0);
669
670   // Recodegen the function
671   runJITOnFunction(F);
672
673   // Update state, forward the old function to the new function.
674   void *Addr = getPointerToGlobalIfAvailable(F);
675   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
676   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
677   return Addr;
678 }
679
680 /// getMemoryForGV - This method abstracts memory allocation of global
681 /// variable so that the JIT can allocate thread local variables depending
682 /// on the target.
683 ///
684 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
685   const Type *ElTy = GV->getType()->getElementType();
686   size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
687   if (GV->isThreadLocal()) {
688     MutexGuard locked(lock);
689     return TJI.allocateThreadLocalMemory(GVSize);
690   } else {
691     return new char[GVSize];
692   }
693 }
694
695 void JIT::addPendingFunction(Function *F) {
696   MutexGuard locked(lock);
697   jitstate->getPendingFunctions(locked).push_back(F);
698 }