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