Next round of APFloat changes.
[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    // FALLS THROUGH
246   case 2:
247    if (FTy->getParamType(1) != PPInt8Ty) {
248      cerr << "Invalid type for second argument of main() supplied\n";
249      abort();
250    }
251    // FALLS THROUGH
252   case 1:
253    if (FTy->getParamType(0) != Type::Int32Ty) {
254      cerr << "Invalid type for first argument of main() supplied\n";
255      abort();
256    }
257    // FALLS THROUGH
258   case 0:
259    if (FTy->getReturnType() != Type::Int32Ty &&
260        FTy->getReturnType() != Type::VoidTy) {
261      cerr << "Invalid return type of main() supplied\n";
262      abort();
263    }
264    break;
265   default:
266    cerr << "Invalid number of arguments of main() supplied\n";
267    abort();
268   }
269   
270   if (NumArgs) {
271     GVArgs.push_back(GVArgc); // Arg #0 = argc.
272     if (NumArgs > 1) {
273       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
274       assert(((char **)GVTOP(GVArgs[1]))[0] &&
275              "argv[0] was null after CreateArgv");
276       if (NumArgs > 2) {
277         std::vector<std::string> EnvVars;
278         for (unsigned i = 0; envp[i]; ++i)
279           EnvVars.push_back(envp[i]);
280         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
281       }
282     }
283   }
284   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
285 }
286
287 /// If possible, create a JIT, unless the caller specifically requests an
288 /// Interpreter or there's an error. If even an Interpreter cannot be created,
289 /// NULL is returned.
290 ///
291 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
292                                          bool ForceInterpreter,
293                                          std::string *ErrorStr) {
294   ExecutionEngine *EE = 0;
295
296   // Unless the interpreter was explicitly selected, try making a JIT.
297   if (!ForceInterpreter && JITCtor)
298     EE = JITCtor(MP, ErrorStr);
299
300   // If we can't make a JIT, make an interpreter instead.
301   if (EE == 0 && InterpCtor)
302     EE = InterpCtor(MP, ErrorStr);
303
304   if (EE) {
305     // Make sure we can resolve symbols in the program as well. The zero arg
306     // to the function tells DynamicLibrary to load the program, not a library.
307     try {
308       sys::DynamicLibrary::LoadLibraryPermanently(0);
309     } catch (...) {
310     }
311   }
312
313   return EE;
314 }
315
316 /// getPointerToGlobal - This returns the address of the specified global
317 /// value.  This may involve code generation if it's a function.
318 ///
319 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
320   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
321     return getPointerToFunction(F);
322
323   MutexGuard locked(lock);
324   void *p = state.getGlobalAddressMap(locked)[GV];
325   if (p)
326     return p;
327
328   // Global variable might have been added since interpreter started.
329   if (GlobalVariable *GVar =
330           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
331     EmitGlobalVariable(GVar);
332   else
333     assert(0 && "Global hasn't had an address allocated yet!");
334   return state.getGlobalAddressMap(locked)[GV];
335 }
336
337 /// This function converts a Constant* into a GenericValue. The interesting 
338 /// part is if C is a ConstantExpr.
339 /// @brief Get a GenericValue for a Constant*
340 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
341   // If its undefined, return the garbage.
342   if (isa<UndefValue>(C)) 
343     return GenericValue();
344
345   // If the value is a ConstantExpr
346   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
347     Constant *Op0 = CE->getOperand(0);
348     switch (CE->getOpcode()) {
349     case Instruction::GetElementPtr: {
350       // Compute the index 
351       GenericValue Result = getConstantValue(Op0);
352       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
353       uint64_t Offset =
354         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
355
356       char* tmp = (char*) Result.PointerVal;
357       Result = PTOGV(tmp + Offset);
358       return Result;
359     }
360     case Instruction::Trunc: {
361       GenericValue GV = getConstantValue(Op0);
362       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
363       GV.IntVal = GV.IntVal.trunc(BitWidth);
364       return GV;
365     }
366     case Instruction::ZExt: {
367       GenericValue GV = getConstantValue(Op0);
368       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
369       GV.IntVal = GV.IntVal.zext(BitWidth);
370       return GV;
371     }
372     case Instruction::SExt: {
373       GenericValue GV = getConstantValue(Op0);
374       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
375       GV.IntVal = GV.IntVal.sext(BitWidth);
376       return GV;
377     }
378     case Instruction::FPTrunc: {
379       GenericValue GV = getConstantValue(Op0);
380       GV.FloatVal = float(GV.DoubleVal);
381       return GV;
382     }
383     case Instruction::FPExt:{
384       GenericValue GV = getConstantValue(Op0);
385       GV.DoubleVal = double(GV.FloatVal);
386       return GV;
387     }
388     case Instruction::UIToFP: {
389       GenericValue GV = getConstantValue(Op0);
390       if (CE->getType() == Type::FloatTy)
391         GV.FloatVal = float(GV.IntVal.roundToDouble());
392       else
393         GV.DoubleVal = GV.IntVal.roundToDouble();
394       return GV;
395     }
396     case Instruction::SIToFP: {
397       GenericValue GV = getConstantValue(Op0);
398       if (CE->getType() == Type::FloatTy)
399         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
400       else
401         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
402       return GV;
403     }
404     case Instruction::FPToUI: // double->APInt conversion handles sign
405     case Instruction::FPToSI: {
406       GenericValue GV = getConstantValue(Op0);
407       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
408       if (Op0->getType() == Type::FloatTy)
409         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
410       else
411         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
412       return GV;
413     }
414     case Instruction::PtrToInt: {
415       GenericValue GV = getConstantValue(Op0);
416       uint32_t PtrWidth = TD->getPointerSizeInBits();
417       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
418       return GV;
419     }
420     case Instruction::IntToPtr: {
421       GenericValue GV = getConstantValue(Op0);
422       uint32_t PtrWidth = TD->getPointerSizeInBits();
423       if (PtrWidth != GV.IntVal.getBitWidth())
424         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
425       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
426       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
427       return GV;
428     }
429     case Instruction::BitCast: {
430       GenericValue GV = getConstantValue(Op0);
431       const Type* DestTy = CE->getType();
432       switch (Op0->getType()->getTypeID()) {
433         default: assert(0 && "Invalid bitcast operand");
434         case Type::IntegerTyID:
435           assert(DestTy->isFloatingPoint() && "invalid bitcast");
436           if (DestTy == Type::FloatTy)
437             GV.FloatVal = GV.IntVal.bitsToFloat();
438           else if (DestTy == Type::DoubleTy)
439             GV.DoubleVal = GV.IntVal.bitsToDouble();
440           break;
441         case Type::FloatTyID: 
442           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
443           GV.IntVal.floatToBits(GV.FloatVal);
444           break;
445         case Type::DoubleTyID:
446           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
447           GV.IntVal.doubleToBits(GV.DoubleVal);
448           break;
449         case Type::PointerTyID:
450           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
451           break; // getConstantValue(Op0)  above already converted it
452       }
453       return GV;
454     }
455     case Instruction::Add:
456     case Instruction::Sub:
457     case Instruction::Mul:
458     case Instruction::UDiv:
459     case Instruction::SDiv:
460     case Instruction::URem:
461     case Instruction::SRem:
462     case Instruction::And:
463     case Instruction::Or:
464     case Instruction::Xor: {
465       GenericValue LHS = getConstantValue(Op0);
466       GenericValue RHS = getConstantValue(CE->getOperand(1));
467       GenericValue GV;
468       switch (CE->getOperand(0)->getType()->getTypeID()) {
469       default: assert(0 && "Bad add type!"); abort();
470       case Type::IntegerTyID:
471         switch (CE->getOpcode()) {
472           default: assert(0 && "Invalid integer opcode");
473           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
474           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
475           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
476           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
477           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
478           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
479           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
480           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
481           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
482           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
483         }
484         break;
485       case Type::FloatTyID:
486         switch (CE->getOpcode()) {
487           default: assert(0 && "Invalid float opcode"); abort();
488           case Instruction::Add:  
489             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
490           case Instruction::Sub:  
491             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
492           case Instruction::Mul:  
493             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
494           case Instruction::FDiv: 
495             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
496           case Instruction::FRem: 
497             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
498         }
499         break;
500       case Type::DoubleTyID:
501         switch (CE->getOpcode()) {
502           default: assert(0 && "Invalid double opcode"); abort();
503           case Instruction::Add:  
504             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
505           case Instruction::Sub:  
506             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
507           case Instruction::Mul:  
508             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
509           case Instruction::FDiv: 
510             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
511           case Instruction::FRem: 
512             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
513         }
514         break;
515       }
516       return GV;
517     }
518     default:
519       break;
520     }
521     cerr << "ConstantExpr not handled: " << *CE << "\n";
522     abort();
523   }
524
525   GenericValue Result;
526   switch (C->getType()->getTypeID()) {
527   case Type::FloatTyID: 
528     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 
529     break;
530   case Type::DoubleTyID:
531     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
532     break;
533   case Type::IntegerTyID:
534     Result.IntVal = cast<ConstantInt>(C)->getValue();
535     break;
536   case Type::PointerTyID:
537     if (isa<ConstantPointerNull>(C))
538       Result.PointerVal = 0;
539     else if (const Function *F = dyn_cast<Function>(C))
540       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
541     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
542       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
543     else
544       assert(0 && "Unknown constant pointer type!");
545     break;
546   default:
547     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
548     abort();
549   }
550   return Result;
551 }
552
553 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
554 /// is the address of the memory at which to store Val, cast to GenericValue *.
555 /// It is not a pointer to a GenericValue containing the address at which to
556 /// store Val.
557 ///
558 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
559                                          const Type *Ty) {
560   switch (Ty->getTypeID()) {
561   case Type::IntegerTyID: {
562     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
563     GenericValue TmpVal = Val;
564     if (BitWidth <= 8)
565       *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
566     else if (BitWidth <= 16) {
567       *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
568     } else if (BitWidth <= 32) {
569       *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
570     } else if (BitWidth <= 64) {
571       *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
572     } else {
573       uint64_t *Dest = (uint64_t*)Ptr;
574       const uint64_t *Src = Val.IntVal.getRawData();
575       for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
576         Dest[i] = Src[i];
577     }
578     break;
579   }
580   case Type::FloatTyID:
581     *((float*)Ptr) = Val.FloatVal;
582     break;
583   case Type::DoubleTyID:
584     *((double*)Ptr) = Val.DoubleVal;
585     break;
586   case Type::PointerTyID: 
587     *((PointerTy*)Ptr) = Val.PointerVal;
588     break;
589   default:
590     cerr << "Cannot store value of type " << *Ty << "!\n";
591   }
592 }
593
594 /// FIXME: document
595 ///
596 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 
597                                                   GenericValue *Ptr,
598                                                   const Type *Ty) {
599   switch (Ty->getTypeID()) {
600   case Type::IntegerTyID: {
601     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
602     if (BitWidth <= 8)
603       Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
604     else if (BitWidth <= 16) {
605       Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
606     } else if (BitWidth <= 32) {
607       Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
608     } else if (BitWidth <= 64) {
609       Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
610     } else
611       Result.IntVal = APInt(BitWidth, (BitWidth+63)/64, (uint64_t*)Ptr);
612     break;
613   }
614   case Type::FloatTyID:
615     Result.FloatVal = *((float*)Ptr);
616     break;
617   case Type::DoubleTyID:
618     Result.DoubleVal = *((double*)Ptr); 
619     break;
620   case Type::PointerTyID: 
621     Result.PointerVal = *((PointerTy*)Ptr);
622     break;
623   default:
624     cerr << "Cannot load value of type " << *Ty << "!\n";
625     abort();
626   }
627 }
628
629 // InitializeMemory - Recursive function to apply a Constant value into the
630 // specified memory location...
631 //
632 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
633   if (isa<UndefValue>(Init)) {
634     return;
635   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
636     unsigned ElementSize =
637       getTargetData()->getTypeSize(CP->getType()->getElementType());
638     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
639       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
640     return;
641   } else if (Init->getType()->isFirstClassType()) {
642     GenericValue Val = getConstantValue(Init);
643     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
644     return;
645   } else if (isa<ConstantAggregateZero>(Init)) {
646     memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
647     return;
648   }
649
650   switch (Init->getType()->getTypeID()) {
651   case Type::ArrayTyID: {
652     const ConstantArray *CPA = cast<ConstantArray>(Init);
653     unsigned ElementSize =
654       getTargetData()->getTypeSize(CPA->getType()->getElementType());
655     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
656       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
657     return;
658   }
659
660   case Type::StructTyID: {
661     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
662     const StructLayout *SL =
663       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
664     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
665       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
666     return;
667   }
668
669   default:
670     cerr << "Bad Type: " << *Init->getType() << "\n";
671     assert(0 && "Unknown constant type to initialize memory with!");
672   }
673 }
674
675 /// EmitGlobals - Emit all of the global variables to memory, storing their
676 /// addresses into GlobalAddress.  This must make sure to copy the contents of
677 /// their initializers into the memory.
678 ///
679 void ExecutionEngine::emitGlobals() {
680   const TargetData *TD = getTargetData();
681
682   // Loop over all of the global variables in the program, allocating the memory
683   // to hold them.  If there is more than one module, do a prepass over globals
684   // to figure out how the different modules should link together.
685   //
686   std::map<std::pair<std::string, const Type*>,
687            const GlobalValue*> LinkedGlobalsMap;
688
689   if (Modules.size() != 1) {
690     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
691       Module &M = *Modules[m]->getModule();
692       for (Module::const_global_iterator I = M.global_begin(),
693            E = M.global_end(); I != E; ++I) {
694         const GlobalValue *GV = I;
695         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
696             GV->hasAppendingLinkage() || !GV->hasName())
697           continue;// Ignore external globals and globals with internal linkage.
698           
699         const GlobalValue *&GVEntry = 
700           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
701
702         // If this is the first time we've seen this global, it is the canonical
703         // version.
704         if (!GVEntry) {
705           GVEntry = GV;
706           continue;
707         }
708         
709         // If the existing global is strong, never replace it.
710         if (GVEntry->hasExternalLinkage() ||
711             GVEntry->hasDLLImportLinkage() ||
712             GVEntry->hasDLLExportLinkage())
713           continue;
714         
715         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
716         // symbol.
717         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
718           GVEntry = GV;
719       }
720     }
721   }
722   
723   std::vector<const GlobalValue*> NonCanonicalGlobals;
724   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
725     Module &M = *Modules[m]->getModule();
726     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
727          I != E; ++I) {
728       // In the multi-module case, see what this global maps to.
729       if (!LinkedGlobalsMap.empty()) {
730         if (const GlobalValue *GVEntry = 
731               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
732           // If something else is the canonical global, ignore this one.
733           if (GVEntry != &*I) {
734             NonCanonicalGlobals.push_back(I);
735             continue;
736           }
737         }
738       }
739       
740       if (!I->isDeclaration()) {
741         // Get the type of the global.
742         const Type *Ty = I->getType()->getElementType();
743
744         // Allocate some memory for it!
745         unsigned Size = TD->getTypeSize(Ty);
746         addGlobalMapping(I, new char[Size]);
747       } else {
748         // External variable reference. Try to use the dynamic loader to
749         // get a pointer to it.
750         if (void *SymAddr =
751             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
752           addGlobalMapping(I, SymAddr);
753         else {
754           cerr << "Could not resolve external global address: "
755                << I->getName() << "\n";
756           abort();
757         }
758       }
759     }
760     
761     // If there are multiple modules, map the non-canonical globals to their
762     // canonical location.
763     if (!NonCanonicalGlobals.empty()) {
764       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
765         const GlobalValue *GV = NonCanonicalGlobals[i];
766         const GlobalValue *CGV =
767           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
768         void *Ptr = getPointerToGlobalIfAvailable(CGV);
769         assert(Ptr && "Canonical global wasn't codegen'd!");
770         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
771       }
772     }
773     
774     // Now that all of the globals are set up in memory, loop through them all 
775     // and initialize their contents.
776     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
777          I != E; ++I) {
778       if (!I->isDeclaration()) {
779         if (!LinkedGlobalsMap.empty()) {
780           if (const GlobalValue *GVEntry = 
781                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
782             if (GVEntry != &*I)  // Not the canonical variable.
783               continue;
784         }
785         EmitGlobalVariable(I);
786       }
787     }
788   }
789 }
790
791 // EmitGlobalVariable - This method emits the specified global variable to the
792 // address specified in GlobalAddresses, or allocates new memory if it's not
793 // already in the map.
794 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
795   void *GA = getPointerToGlobalIfAvailable(GV);
796   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
797
798   const Type *ElTy = GV->getType()->getElementType();
799   size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
800   if (GA == 0) {
801     // If it's not already specified, allocate memory for the global.
802     GA = new char[GVSize];
803     addGlobalMapping(GV, GA);
804   }
805
806   InitializeMemory(GV->getInitializer(), GA);
807   NumInitBytes += (unsigned)GVSize;
808   ++NumGlobals;
809 }