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