Use the new script to sort the includes of every file under lib.
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
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 file defines the common interface used by the various execution engine
11 // subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DataLayout.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/DynamicLibrary.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/MutexGuard.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/ValueHandle.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include <cmath>
34 #include <cstring>
35 using namespace llvm;
36
37 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38 STATISTIC(NumGlobals  , "Number of global vars initialized");
39
40 ExecutionEngine *(*ExecutionEngine::JITCtor)(
41   Module *M,
42   std::string *ErrorStr,
43   JITMemoryManager *JMM,
44   bool GVsWithCode,
45   TargetMachine *TM) = 0;
46 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
47   Module *M,
48   std::string *ErrorStr,
49   JITMemoryManager *JMM,
50   bool GVsWithCode,
51   TargetMachine *TM) = 0;
52 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
53                                                 std::string *ErrorStr) = 0;
54
55 ExecutionEngine::ExecutionEngine(Module *M)
56   : EEState(*this),
57     LazyFunctionCreator(0),
58     ExceptionTableRegister(0),
59     ExceptionTableDeregister(0) {
60   CompilingLazily         = false;
61   GVCompilationDisabled   = false;
62   SymbolSearchingDisabled = false;
63   Modules.push_back(M);
64   assert(M && "Module is null?");
65 }
66
67 ExecutionEngine::~ExecutionEngine() {
68   clearAllGlobalMappings();
69   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
70     delete Modules[i];
71 }
72
73 void ExecutionEngine::DeregisterAllTables() {
74   if (ExceptionTableDeregister) {
75     DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
76     DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
77     for (; it != ite; ++it)
78       ExceptionTableDeregister(it->second);
79     AllExceptionTables.clear();
80   }
81 }
82
83 namespace {
84 /// \brief Helper class which uses a value handler to automatically deletes the
85 /// memory block when the GlobalVariable is destroyed.
86 class GVMemoryBlock : public CallbackVH {
87   GVMemoryBlock(const GlobalVariable *GV)
88     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
89
90 public:
91   /// \brief Returns the address the GlobalVariable should be written into.  The
92   /// GVMemoryBlock object prefixes that.
93   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
94     Type *ElTy = GV->getType()->getElementType();
95     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
96     void *RawMemory = ::operator new(
97       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
98                                    TD.getPreferredAlignment(GV))
99       + GVSize);
100     new(RawMemory) GVMemoryBlock(GV);
101     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
102   }
103
104   virtual void deleted() {
105     // We allocated with operator new and with some extra memory hanging off the
106     // end, so don't just delete this.  I'm not sure if this is actually
107     // required.
108     this->~GVMemoryBlock();
109     ::operator delete(this);
110   }
111 };
112 }  // anonymous namespace
113
114 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
115   return GVMemoryBlock::Create(GV, *getDataLayout());
116 }
117
118 bool ExecutionEngine::removeModule(Module *M) {
119   for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
120         E = Modules.end(); I != E; ++I) {
121     Module *Found = *I;
122     if (Found == M) {
123       Modules.erase(I);
124       clearGlobalMappingsFromModule(M);
125       return true;
126     }
127   }
128   return false;
129 }
130
131 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
132   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
133     if (Function *F = Modules[i]->getFunction(FnName))
134       return F;
135   }
136   return 0;
137 }
138
139
140 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
141                                           const GlobalValue *ToUnmap) {
142   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
143   void *OldVal;
144
145   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
146   // GlobalAddressMap.
147   if (I == GlobalAddressMap.end())
148     OldVal = 0;
149   else {
150     OldVal = I->second;
151     GlobalAddressMap.erase(I);
152   }
153
154   GlobalAddressReverseMap.erase(OldVal);
155   return OldVal;
156 }
157
158 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
159   MutexGuard locked(lock);
160
161   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
162         << "\' to [" << Addr << "]\n";);
163   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
164   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
165   CurVal = Addr;
166
167   // If we are using the reverse mapping, add it too.
168   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
169     AssertingVH<const GlobalValue> &V =
170       EEState.getGlobalAddressReverseMap(locked)[Addr];
171     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
172     V = GV;
173   }
174 }
175
176 void ExecutionEngine::clearAllGlobalMappings() {
177   MutexGuard locked(lock);
178
179   EEState.getGlobalAddressMap(locked).clear();
180   EEState.getGlobalAddressReverseMap(locked).clear();
181 }
182
183 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
184   MutexGuard locked(lock);
185
186   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
187     EEState.RemoveMapping(locked, FI);
188   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
189        GI != GE; ++GI)
190     EEState.RemoveMapping(locked, GI);
191 }
192
193 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
194   MutexGuard locked(lock);
195
196   ExecutionEngineState::GlobalAddressMapTy &Map =
197     EEState.getGlobalAddressMap(locked);
198
199   // Deleting from the mapping?
200   if (Addr == 0)
201     return EEState.RemoveMapping(locked, GV);
202
203   void *&CurVal = Map[GV];
204   void *OldVal = CurVal;
205
206   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
207     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
208   CurVal = Addr;
209
210   // If we are using the reverse mapping, add it too.
211   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
212     AssertingVH<const GlobalValue> &V =
213       EEState.getGlobalAddressReverseMap(locked)[Addr];
214     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
215     V = GV;
216   }
217   return OldVal;
218 }
219
220 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
221   MutexGuard locked(lock);
222
223   ExecutionEngineState::GlobalAddressMapTy::iterator I =
224     EEState.getGlobalAddressMap(locked).find(GV);
225   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
226 }
227
228 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
229   MutexGuard locked(lock);
230
231   // If we haven't computed the reverse mapping yet, do so first.
232   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
233     for (ExecutionEngineState::GlobalAddressMapTy::iterator
234          I = EEState.getGlobalAddressMap(locked).begin(),
235          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
236       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
237                                                           I->second, I->first));
238   }
239
240   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
241     EEState.getGlobalAddressReverseMap(locked).find(Addr);
242   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
243 }
244
245 namespace {
246 class ArgvArray {
247   char *Array;
248   std::vector<char*> Values;
249 public:
250   ArgvArray() : Array(NULL) {}
251   ~ArgvArray() { clear(); }
252   void clear() {
253     delete[] Array;
254     Array = NULL;
255     for (size_t I = 0, E = Values.size(); I != E; ++I) {
256       delete[] Values[I];
257     }
258     Values.clear();
259   }
260   /// Turn a vector of strings into a nice argv style array of pointers to null
261   /// terminated strings.
262   void *reset(LLVMContext &C, ExecutionEngine *EE,
263               const std::vector<std::string> &InputArgv);
264 };
265 }  // anonymous namespace
266 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
267                        const std::vector<std::string> &InputArgv) {
268   clear();  // Free the old contents.
269   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
270   Array = new char[(InputArgv.size()+1)*PtrSize];
271
272   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
273   Type *SBytePtr = Type::getInt8PtrTy(C);
274
275   for (unsigned i = 0; i != InputArgv.size(); ++i) {
276     unsigned Size = InputArgv[i].size()+1;
277     char *Dest = new char[Size];
278     Values.push_back(Dest);
279     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
280
281     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
282     Dest[Size-1] = 0;
283
284     // Endian safe: Array[i] = (PointerTy)Dest;
285     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
286                            SBytePtr);
287   }
288
289   // Null terminate it
290   EE->StoreValueToMemory(PTOGV(0),
291                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
292                          SBytePtr);
293   return Array;
294 }
295
296 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
297                                                        bool isDtors) {
298   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
299   GlobalVariable *GV = module->getNamedGlobal(Name);
300
301   // If this global has internal linkage, or if it has a use, then it must be
302   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
303   // this is the case, don't execute any of the global ctors, __main will do
304   // it.
305   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
306
307   // Should be an array of '{ i32, void ()* }' structs.  The first value is
308   // the init priority, which we ignore.
309   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
310   if (InitList == 0)
311     return;
312   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
313     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
314     if (CS == 0) continue;
315
316     Constant *FP = CS->getOperand(1);
317     if (FP->isNullValue())
318       continue;  // Found a sentinal value, ignore.
319
320     // Strip off constant expression casts.
321     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
322       if (CE->isCast())
323         FP = CE->getOperand(0);
324
325     // Execute the ctor/dtor function!
326     if (Function *F = dyn_cast<Function>(FP))
327       runFunction(F, std::vector<GenericValue>());
328
329     // FIXME: It is marginally lame that we just do nothing here if we see an
330     // entry we don't recognize. It might not be unreasonable for the verifier
331     // to not even allow this and just assert here.
332   }
333 }
334
335 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
336   // Execute global ctors/dtors for each module in the program.
337   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
338     runStaticConstructorsDestructors(Modules[i], isDtors);
339 }
340
341 #ifndef NDEBUG
342 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
343 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
344   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
345   for (unsigned i = 0; i < PtrSize; ++i)
346     if (*(i + (uint8_t*)Loc))
347       return false;
348   return true;
349 }
350 #endif
351
352 int ExecutionEngine::runFunctionAsMain(Function *Fn,
353                                        const std::vector<std::string> &argv,
354                                        const char * const * envp) {
355   std::vector<GenericValue> GVArgs;
356   GenericValue GVArgc;
357   GVArgc.IntVal = APInt(32, argv.size());
358
359   // Check main() type
360   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
361   FunctionType *FTy = Fn->getFunctionType();
362   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
363
364   // Check the argument types.
365   if (NumArgs > 3)
366     report_fatal_error("Invalid number of arguments of main() supplied");
367   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
368     report_fatal_error("Invalid type for third argument of main() supplied");
369   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
370     report_fatal_error("Invalid type for second argument of main() supplied");
371   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
372     report_fatal_error("Invalid type for first argument of main() supplied");
373   if (!FTy->getReturnType()->isIntegerTy() &&
374       !FTy->getReturnType()->isVoidTy())
375     report_fatal_error("Invalid return type of main() supplied");
376
377   ArgvArray CArgv;
378   ArgvArray CEnv;
379   if (NumArgs) {
380     GVArgs.push_back(GVArgc); // Arg #0 = argc.
381     if (NumArgs > 1) {
382       // Arg #1 = argv.
383       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
384       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
385              "argv[0] was null after CreateArgv");
386       if (NumArgs > 2) {
387         std::vector<std::string> EnvVars;
388         for (unsigned i = 0; envp[i]; ++i)
389           EnvVars.push_back(envp[i]);
390         // Arg #2 = envp.
391         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
392       }
393     }
394   }
395
396   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
397 }
398
399 ExecutionEngine *ExecutionEngine::create(Module *M,
400                                          bool ForceInterpreter,
401                                          std::string *ErrorStr,
402                                          CodeGenOpt::Level OptLevel,
403                                          bool GVsWithCode) {
404   EngineBuilder EB =  EngineBuilder(M)
405       .setEngineKind(ForceInterpreter
406                      ? EngineKind::Interpreter
407                      : EngineKind::JIT)
408       .setErrorStr(ErrorStr)
409       .setOptLevel(OptLevel)
410       .setAllocateGVsWithCode(GVsWithCode);
411
412   return EB.create();
413 }
414
415 /// createJIT - This is the factory method for creating a JIT for the current
416 /// machine, it does not fall back to the interpreter.  This takes ownership
417 /// of the module.
418 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
419                                             std::string *ErrorStr,
420                                             JITMemoryManager *JMM,
421                                             CodeGenOpt::Level OL,
422                                             bool GVsWithCode,
423                                             Reloc::Model RM,
424                                             CodeModel::Model CMM) {
425   if (ExecutionEngine::JITCtor == 0) {
426     if (ErrorStr)
427       *ErrorStr = "JIT has not been linked in.";
428     return 0;
429   }
430
431   // Use the defaults for extra parameters.  Users can use EngineBuilder to
432   // set them.
433   EngineBuilder EB(M);
434   EB.setEngineKind(EngineKind::JIT);
435   EB.setErrorStr(ErrorStr);
436   EB.setRelocationModel(RM);
437   EB.setCodeModel(CMM);
438   EB.setAllocateGVsWithCode(GVsWithCode);
439   EB.setOptLevel(OL);
440   EB.setJITMemoryManager(JMM);
441
442   // TODO: permit custom TargetOptions here
443   TargetMachine *TM = EB.selectTarget();
444   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
445
446   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
447 }
448
449 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
450   OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
451
452   // Make sure we can resolve symbols in the program as well. The zero arg
453   // to the function tells DynamicLibrary to load the program, not a library.
454   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
455     return 0;
456
457   // If the user specified a memory manager but didn't specify which engine to
458   // create, we assume they only want the JIT, and we fail if they only want
459   // the interpreter.
460   if (JMM) {
461     if (WhichEngine & EngineKind::JIT)
462       WhichEngine = EngineKind::JIT;
463     else {
464       if (ErrorStr)
465         *ErrorStr = "Cannot create an interpreter with a memory manager.";
466       return 0;
467     }
468   }
469
470   // Unless the interpreter was explicitly selected or the JIT is not linked,
471   // try making a JIT.
472   if ((WhichEngine & EngineKind::JIT) && TheTM) {
473     Triple TT(M->getTargetTriple());
474     if (!TM->getTarget().hasJIT()) {
475       errs() << "WARNING: This target JIT is not designed for the host"
476              << " you are running.  If bad things happen, please choose"
477              << " a different -march switch.\n";
478     }
479
480     if (UseMCJIT && ExecutionEngine::MCJITCtor) {
481       ExecutionEngine *EE =
482         ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
483                                    AllocateGVsWithCode, TheTM.take());
484       if (EE) return EE;
485     } else if (ExecutionEngine::JITCtor) {
486       ExecutionEngine *EE =
487         ExecutionEngine::JITCtor(M, ErrorStr, JMM,
488                                  AllocateGVsWithCode, TheTM.take());
489       if (EE) return EE;
490     }
491   }
492
493   // If we can't make a JIT and we didn't request one specifically, try making
494   // an interpreter instead.
495   if (WhichEngine & EngineKind::Interpreter) {
496     if (ExecutionEngine::InterpCtor)
497       return ExecutionEngine::InterpCtor(M, ErrorStr);
498     if (ErrorStr)
499       *ErrorStr = "Interpreter has not been linked in.";
500     return 0;
501   }
502
503   if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
504       ExecutionEngine::MCJITCtor == 0) {
505     if (ErrorStr)
506       *ErrorStr = "JIT has not been linked in.";
507   }
508
509   return 0;
510 }
511
512 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
513   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
514     return getPointerToFunction(F);
515
516   MutexGuard locked(lock);
517   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
518     return P;
519
520   // Global variable might have been added since interpreter started.
521   if (GlobalVariable *GVar =
522           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
523     EmitGlobalVariable(GVar);
524   else
525     llvm_unreachable("Global hasn't had an address allocated yet!");
526
527   return EEState.getGlobalAddressMap(locked)[GV];
528 }
529
530 /// \brief Converts a Constant* into a GenericValue, including handling of
531 /// ConstantExpr values.
532 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
533   // If its undefined, return the garbage.
534   if (isa<UndefValue>(C)) {
535     GenericValue Result;
536     switch (C->getType()->getTypeID()) {
537     case Type::IntegerTyID:
538     case Type::X86_FP80TyID:
539     case Type::FP128TyID:
540     case Type::PPC_FP128TyID:
541       // Although the value is undefined, we still have to construct an APInt
542       // with the correct bit width.
543       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
544       break;
545     default:
546       break;
547     }
548     return Result;
549   }
550
551   // Otherwise, if the value is a ConstantExpr...
552   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
553     Constant *Op0 = CE->getOperand(0);
554     switch (CE->getOpcode()) {
555     case Instruction::GetElementPtr: {
556       // Compute the index
557       GenericValue Result = getConstantValue(Op0);
558       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
559       uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
560
561       char* tmp = (char*) Result.PointerVal;
562       Result = PTOGV(tmp + Offset);
563       return Result;
564     }
565     case Instruction::Trunc: {
566       GenericValue GV = getConstantValue(Op0);
567       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
568       GV.IntVal = GV.IntVal.trunc(BitWidth);
569       return GV;
570     }
571     case Instruction::ZExt: {
572       GenericValue GV = getConstantValue(Op0);
573       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
574       GV.IntVal = GV.IntVal.zext(BitWidth);
575       return GV;
576     }
577     case Instruction::SExt: {
578       GenericValue GV = getConstantValue(Op0);
579       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
580       GV.IntVal = GV.IntVal.sext(BitWidth);
581       return GV;
582     }
583     case Instruction::FPTrunc: {
584       // FIXME long double
585       GenericValue GV = getConstantValue(Op0);
586       GV.FloatVal = float(GV.DoubleVal);
587       return GV;
588     }
589     case Instruction::FPExt:{
590       // FIXME long double
591       GenericValue GV = getConstantValue(Op0);
592       GV.DoubleVal = double(GV.FloatVal);
593       return GV;
594     }
595     case Instruction::UIToFP: {
596       GenericValue GV = getConstantValue(Op0);
597       if (CE->getType()->isFloatTy())
598         GV.FloatVal = float(GV.IntVal.roundToDouble());
599       else if (CE->getType()->isDoubleTy())
600         GV.DoubleVal = GV.IntVal.roundToDouble();
601       else if (CE->getType()->isX86_FP80Ty()) {
602         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
603         (void)apf.convertFromAPInt(GV.IntVal,
604                                    false,
605                                    APFloat::rmNearestTiesToEven);
606         GV.IntVal = apf.bitcastToAPInt();
607       }
608       return GV;
609     }
610     case Instruction::SIToFP: {
611       GenericValue GV = getConstantValue(Op0);
612       if (CE->getType()->isFloatTy())
613         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
614       else if (CE->getType()->isDoubleTy())
615         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
616       else if (CE->getType()->isX86_FP80Ty()) {
617         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
618         (void)apf.convertFromAPInt(GV.IntVal,
619                                    true,
620                                    APFloat::rmNearestTiesToEven);
621         GV.IntVal = apf.bitcastToAPInt();
622       }
623       return GV;
624     }
625     case Instruction::FPToUI: // double->APInt conversion handles sign
626     case Instruction::FPToSI: {
627       GenericValue GV = getConstantValue(Op0);
628       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
629       if (Op0->getType()->isFloatTy())
630         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
631       else if (Op0->getType()->isDoubleTy())
632         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
633       else if (Op0->getType()->isX86_FP80Ty()) {
634         APFloat apf = APFloat(GV.IntVal);
635         uint64_t v;
636         bool ignored;
637         (void)apf.convertToInteger(&v, BitWidth,
638                                    CE->getOpcode()==Instruction::FPToSI,
639                                    APFloat::rmTowardZero, &ignored);
640         GV.IntVal = v; // endian?
641       }
642       return GV;
643     }
644     case Instruction::PtrToInt: {
645       GenericValue GV = getConstantValue(Op0);
646       uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
647       assert(PtrWidth <= 64 && "Bad pointer width");
648       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
649       uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
650       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
651       return GV;
652     }
653     case Instruction::IntToPtr: {
654       GenericValue GV = getConstantValue(Op0);
655       uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
656       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
657       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
658       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
659       return GV;
660     }
661     case Instruction::BitCast: {
662       GenericValue GV = getConstantValue(Op0);
663       Type* DestTy = CE->getType();
664       switch (Op0->getType()->getTypeID()) {
665         default: llvm_unreachable("Invalid bitcast operand");
666         case Type::IntegerTyID:
667           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
668           if (DestTy->isFloatTy())
669             GV.FloatVal = GV.IntVal.bitsToFloat();
670           else if (DestTy->isDoubleTy())
671             GV.DoubleVal = GV.IntVal.bitsToDouble();
672           break;
673         case Type::FloatTyID:
674           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
675           GV.IntVal = APInt::floatToBits(GV.FloatVal);
676           break;
677         case Type::DoubleTyID:
678           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
679           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
680           break;
681         case Type::PointerTyID:
682           assert(DestTy->isPointerTy() && "Invalid bitcast");
683           break; // getConstantValue(Op0)  above already converted it
684       }
685       return GV;
686     }
687     case Instruction::Add:
688     case Instruction::FAdd:
689     case Instruction::Sub:
690     case Instruction::FSub:
691     case Instruction::Mul:
692     case Instruction::FMul:
693     case Instruction::UDiv:
694     case Instruction::SDiv:
695     case Instruction::URem:
696     case Instruction::SRem:
697     case Instruction::And:
698     case Instruction::Or:
699     case Instruction::Xor: {
700       GenericValue LHS = getConstantValue(Op0);
701       GenericValue RHS = getConstantValue(CE->getOperand(1));
702       GenericValue GV;
703       switch (CE->getOperand(0)->getType()->getTypeID()) {
704       default: llvm_unreachable("Bad add type!");
705       case Type::IntegerTyID:
706         switch (CE->getOpcode()) {
707           default: llvm_unreachable("Invalid integer opcode");
708           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
709           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
710           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
711           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
712           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
713           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
714           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
715           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
716           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
717           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
718         }
719         break;
720       case Type::FloatTyID:
721         switch (CE->getOpcode()) {
722           default: llvm_unreachable("Invalid float opcode");
723           case Instruction::FAdd:
724             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
725           case Instruction::FSub:
726             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
727           case Instruction::FMul:
728             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
729           case Instruction::FDiv:
730             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
731           case Instruction::FRem:
732             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
733         }
734         break;
735       case Type::DoubleTyID:
736         switch (CE->getOpcode()) {
737           default: llvm_unreachable("Invalid double opcode");
738           case Instruction::FAdd:
739             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
740           case Instruction::FSub:
741             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
742           case Instruction::FMul:
743             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
744           case Instruction::FDiv:
745             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
746           case Instruction::FRem:
747             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
748         }
749         break;
750       case Type::X86_FP80TyID:
751       case Type::PPC_FP128TyID:
752       case Type::FP128TyID: {
753         APFloat apfLHS = APFloat(LHS.IntVal);
754         switch (CE->getOpcode()) {
755           default: llvm_unreachable("Invalid long double opcode");
756           case Instruction::FAdd:
757             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
758             GV.IntVal = apfLHS.bitcastToAPInt();
759             break;
760           case Instruction::FSub:
761             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
762             GV.IntVal = apfLHS.bitcastToAPInt();
763             break;
764           case Instruction::FMul:
765             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
766             GV.IntVal = apfLHS.bitcastToAPInt();
767             break;
768           case Instruction::FDiv:
769             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
770             GV.IntVal = apfLHS.bitcastToAPInt();
771             break;
772           case Instruction::FRem:
773             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
774             GV.IntVal = apfLHS.bitcastToAPInt();
775             break;
776           }
777         }
778         break;
779       }
780       return GV;
781     }
782     default:
783       break;
784     }
785
786     SmallString<256> Msg;
787     raw_svector_ostream OS(Msg);
788     OS << "ConstantExpr not handled: " << *CE;
789     report_fatal_error(OS.str());
790   }
791
792   // Otherwise, we have a simple constant.
793   GenericValue Result;
794   switch (C->getType()->getTypeID()) {
795   case Type::FloatTyID:
796     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
797     break;
798   case Type::DoubleTyID:
799     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
800     break;
801   case Type::X86_FP80TyID:
802   case Type::FP128TyID:
803   case Type::PPC_FP128TyID:
804     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
805     break;
806   case Type::IntegerTyID:
807     Result.IntVal = cast<ConstantInt>(C)->getValue();
808     break;
809   case Type::PointerTyID:
810     if (isa<ConstantPointerNull>(C))
811       Result.PointerVal = 0;
812     else if (const Function *F = dyn_cast<Function>(C))
813       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
814     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
815       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
816     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
817       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
818                                                         BA->getBasicBlock())));
819     else
820       llvm_unreachable("Unknown constant pointer type!");
821     break;
822   default:
823     SmallString<256> Msg;
824     raw_svector_ostream OS(Msg);
825     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
826     report_fatal_error(OS.str());
827   }
828
829   return Result;
830 }
831
832 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
833 /// with the integer held in IntVal.
834 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
835                              unsigned StoreBytes) {
836   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
837   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
838
839   if (sys::isLittleEndianHost()) {
840     // Little-endian host - the source is ordered from LSB to MSB.  Order the
841     // destination from LSB to MSB: Do a straight copy.
842     memcpy(Dst, Src, StoreBytes);
843   } else {
844     // Big-endian host - the source is an array of 64 bit words ordered from
845     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
846     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
847     while (StoreBytes > sizeof(uint64_t)) {
848       StoreBytes -= sizeof(uint64_t);
849       // May not be aligned so use memcpy.
850       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
851       Src += sizeof(uint64_t);
852     }
853
854     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
855   }
856 }
857
858 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
859                                          GenericValue *Ptr, Type *Ty) {
860   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
861
862   switch (Ty->getTypeID()) {
863   case Type::IntegerTyID:
864     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
865     break;
866   case Type::FloatTyID:
867     *((float*)Ptr) = Val.FloatVal;
868     break;
869   case Type::DoubleTyID:
870     *((double*)Ptr) = Val.DoubleVal;
871     break;
872   case Type::X86_FP80TyID:
873     memcpy(Ptr, Val.IntVal.getRawData(), 10);
874     break;
875   case Type::PointerTyID:
876     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
877     if (StoreBytes != sizeof(PointerTy))
878       memset(&(Ptr->PointerVal), 0, StoreBytes);
879
880     *((PointerTy*)Ptr) = Val.PointerVal;
881     break;
882   default:
883     dbgs() << "Cannot store value of type " << *Ty << "!\n";
884   }
885
886   if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
887     // Host and target are different endian - reverse the stored bytes.
888     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
889 }
890
891 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
892 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
893 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
894   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
895   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
896
897   if (sys::isLittleEndianHost())
898     // Little-endian host - the destination must be ordered from LSB to MSB.
899     // The source is ordered from LSB to MSB: Do a straight copy.
900     memcpy(Dst, Src, LoadBytes);
901   else {
902     // Big-endian - the destination is an array of 64 bit words ordered from
903     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
904     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
905     // a word.
906     while (LoadBytes > sizeof(uint64_t)) {
907       LoadBytes -= sizeof(uint64_t);
908       // May not be aligned so use memcpy.
909       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
910       Dst += sizeof(uint64_t);
911     }
912
913     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
914   }
915 }
916
917 /// FIXME: document
918 ///
919 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
920                                           GenericValue *Ptr,
921                                           Type *Ty) {
922   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
923
924   switch (Ty->getTypeID()) {
925   case Type::IntegerTyID:
926     // An APInt with all words initially zero.
927     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
928     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
929     break;
930   case Type::FloatTyID:
931     Result.FloatVal = *((float*)Ptr);
932     break;
933   case Type::DoubleTyID:
934     Result.DoubleVal = *((double*)Ptr);
935     break;
936   case Type::PointerTyID:
937     Result.PointerVal = *((PointerTy*)Ptr);
938     break;
939   case Type::X86_FP80TyID: {
940     // This is endian dependent, but it will only work on x86 anyway.
941     // FIXME: Will not trap if loading a signaling NaN.
942     uint64_t y[2];
943     memcpy(y, Ptr, 10);
944     Result.IntVal = APInt(80, y);
945     break;
946   }
947   default:
948     SmallString<256> Msg;
949     raw_svector_ostream OS(Msg);
950     OS << "Cannot load value of type " << *Ty << "!";
951     report_fatal_error(OS.str());
952   }
953 }
954
955 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
956   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
957   DEBUG(Init->dump());
958   if (isa<UndefValue>(Init))
959     return;
960   
961   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
962     unsigned ElementSize =
963       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
964     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
965       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
966     return;
967   }
968   
969   if (isa<ConstantAggregateZero>(Init)) {
970     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
971     return;
972   }
973   
974   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
975     unsigned ElementSize =
976       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
977     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
978       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
979     return;
980   }
981   
982   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
983     const StructLayout *SL =
984       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
985     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
986       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
987     return;
988   }
989
990   if (const ConstantDataSequential *CDS =
991                dyn_cast<ConstantDataSequential>(Init)) {
992     // CDS is already laid out in host memory order.
993     StringRef Data = CDS->getRawDataValues();
994     memcpy(Addr, Data.data(), Data.size());
995     return;
996   }
997
998   if (Init->getType()->isFirstClassType()) {
999     GenericValue Val = getConstantValue(Init);
1000     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1001     return;
1002   }
1003
1004   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1005   llvm_unreachable("Unknown constant type to initialize memory with!");
1006 }
1007
1008 /// EmitGlobals - Emit all of the global variables to memory, storing their
1009 /// addresses into GlobalAddress.  This must make sure to copy the contents of
1010 /// their initializers into the memory.
1011 void ExecutionEngine::emitGlobals() {
1012   // Loop over all of the global variables in the program, allocating the memory
1013   // to hold them.  If there is more than one module, do a prepass over globals
1014   // to figure out how the different modules should link together.
1015   std::map<std::pair<std::string, Type*>,
1016            const GlobalValue*> LinkedGlobalsMap;
1017
1018   if (Modules.size() != 1) {
1019     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1020       Module &M = *Modules[m];
1021       for (Module::const_global_iterator I = M.global_begin(),
1022            E = M.global_end(); I != E; ++I) {
1023         const GlobalValue *GV = I;
1024         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1025             GV->hasAppendingLinkage() || !GV->hasName())
1026           continue;// Ignore external globals and globals with internal linkage.
1027
1028         const GlobalValue *&GVEntry =
1029           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1030
1031         // If this is the first time we've seen this global, it is the canonical
1032         // version.
1033         if (!GVEntry) {
1034           GVEntry = GV;
1035           continue;
1036         }
1037
1038         // If the existing global is strong, never replace it.
1039         if (GVEntry->hasExternalLinkage() ||
1040             GVEntry->hasDLLImportLinkage() ||
1041             GVEntry->hasDLLExportLinkage())
1042           continue;
1043
1044         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1045         // symbol.  FIXME is this right for common?
1046         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1047           GVEntry = GV;
1048       }
1049     }
1050   }
1051
1052   std::vector<const GlobalValue*> NonCanonicalGlobals;
1053   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1054     Module &M = *Modules[m];
1055     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1056          I != E; ++I) {
1057       // In the multi-module case, see what this global maps to.
1058       if (!LinkedGlobalsMap.empty()) {
1059         if (const GlobalValue *GVEntry =
1060               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1061           // If something else is the canonical global, ignore this one.
1062           if (GVEntry != &*I) {
1063             NonCanonicalGlobals.push_back(I);
1064             continue;
1065           }
1066         }
1067       }
1068
1069       if (!I->isDeclaration()) {
1070         addGlobalMapping(I, getMemoryForGV(I));
1071       } else {
1072         // External variable reference. Try to use the dynamic loader to
1073         // get a pointer to it.
1074         if (void *SymAddr =
1075             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1076           addGlobalMapping(I, SymAddr);
1077         else {
1078           report_fatal_error("Could not resolve external global address: "
1079                             +I->getName());
1080         }
1081       }
1082     }
1083
1084     // If there are multiple modules, map the non-canonical globals to their
1085     // canonical location.
1086     if (!NonCanonicalGlobals.empty()) {
1087       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1088         const GlobalValue *GV = NonCanonicalGlobals[i];
1089         const GlobalValue *CGV =
1090           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1091         void *Ptr = getPointerToGlobalIfAvailable(CGV);
1092         assert(Ptr && "Canonical global wasn't codegen'd!");
1093         addGlobalMapping(GV, Ptr);
1094       }
1095     }
1096
1097     // Now that all of the globals are set up in memory, loop through them all
1098     // and initialize their contents.
1099     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1100          I != E; ++I) {
1101       if (!I->isDeclaration()) {
1102         if (!LinkedGlobalsMap.empty()) {
1103           if (const GlobalValue *GVEntry =
1104                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1105             if (GVEntry != &*I)  // Not the canonical variable.
1106               continue;
1107         }
1108         EmitGlobalVariable(I);
1109       }
1110     }
1111   }
1112 }
1113
1114 // EmitGlobalVariable - This method emits the specified global variable to the
1115 // address specified in GlobalAddresses, or allocates new memory if it's not
1116 // already in the map.
1117 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1118   void *GA = getPointerToGlobalIfAvailable(GV);
1119
1120   if (GA == 0) {
1121     // If it's not already specified, allocate memory for the global.
1122     GA = getMemoryForGV(GV);
1123     addGlobalMapping(GV, GA);
1124   }
1125
1126   // Don't initialize if it's thread local, let the client do it.
1127   if (!GV->isThreadLocal())
1128     InitializeMemory(GV->getInitializer(), GA);
1129
1130   Type *ElTy = GV->getType()->getElementType();
1131   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1132   NumInitBytes += (unsigned)GVSize;
1133   ++NumGlobals;
1134 }
1135
1136 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1137   : EE(EE), GlobalAddressMap(this) {
1138 }
1139
1140 sys::Mutex *
1141 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1142   return &EES->EE.lock;
1143 }
1144
1145 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1146                                                       const GlobalValue *Old) {
1147   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1148   EES->GlobalAddressReverseMap.erase(OldVal);
1149 }
1150
1151 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1152                                                     const GlobalValue *,
1153                                                     const GlobalValue *) {
1154   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1155                    " RAUW on a value it has a global mapping for.");
1156 }