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