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