Changed llvm_ostream et all to OStream. llvm_cerr, llvm_cout, llvm_null, are
[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 using namespace llvm;
28
29 namespace {
30   Statistic NumInitBytes("lli", "Number of bytes of global vars initialized");
31   Statistic NumGlobals  ("lli", "Number of global vars initialized");
32 }
33
34 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
35 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
36
37 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
38   LazyCompilationDisabled = false;
39   Modules.push_back(P);
40   assert(P && "ModuleProvider is null?");
41 }
42
43 ExecutionEngine::ExecutionEngine(Module *M) {
44   LazyCompilationDisabled = false;
45   assert(M && "Module is null?");
46   Modules.push_back(new ExistingModuleProvider(M));
47 }
48
49 ExecutionEngine::~ExecutionEngine() {
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()->getNamedFunction(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::SByteTy);
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->isExternal() || 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 = argv.size();
234   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
235   if (NumArgs) {
236     GVArgs.push_back(GVArgc); // Arg #0 = argc.
237     if (NumArgs > 1) {
238       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
239       assert(((char **)GVTOP(GVArgs[1]))[0] &&
240              "argv[0] was null after CreateArgv");
241       if (NumArgs > 2) {
242         std::vector<std::string> EnvVars;
243         for (unsigned i = 0; envp[i]; ++i)
244           EnvVars.push_back(envp[i]);
245         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
246       }
247     }
248   }
249   return runFunction(Fn, GVArgs).IntVal;
250 }
251
252 /// If possible, create a JIT, unless the caller specifically requests an
253 /// Interpreter or there's an error. If even an Interpreter cannot be created,
254 /// NULL is returned.
255 ///
256 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
257                                          bool ForceInterpreter) {
258   ExecutionEngine *EE = 0;
259
260   // Unless the interpreter was explicitly selected, try making a JIT.
261   if (!ForceInterpreter && JITCtor)
262     EE = JITCtor(MP);
263
264   // If we can't make a JIT, make an interpreter instead.
265   if (EE == 0 && InterpCtor)
266     EE = InterpCtor(MP);
267
268   if (EE) {
269     // Make sure we can resolve symbols in the program as well. The zero arg
270     // to the function tells DynamicLibrary to load the program, not a library.
271     try {
272       sys::DynamicLibrary::LoadLibraryPermanently(0);
273     } catch (...) {
274     }
275   }
276
277   return EE;
278 }
279
280 /// getPointerToGlobal - This returns the address of the specified global
281 /// value.  This may involve code generation if it's a function.
282 ///
283 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
284   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
285     return getPointerToFunction(F);
286
287   MutexGuard locked(lock);
288   void *p = state.getGlobalAddressMap(locked)[GV];
289   if (p)
290     return p;
291
292   // Global variable might have been added since interpreter started.
293   if (GlobalVariable *GVar =
294           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
295     EmitGlobalVariable(GVar);
296   else
297     assert("Global hasn't had an address allocated yet!");
298   return state.getGlobalAddressMap(locked)[GV];
299 }
300
301 /// This function converts a Constant* into a GenericValue. The interesting 
302 /// part is if C is a ConstantExpr.
303 /// @brief Get a GenericValue for a Constnat*
304 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
305   // Declare the result as garbage.
306   GenericValue Result;
307
308   // If its undefined, return the garbage.
309   if (isa<UndefValue>(C)) return Result;
310
311   // If the value is a ConstantExpr
312   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
313     switch (CE->getOpcode()) {
314     case Instruction::GetElementPtr: {
315       // Compute the index 
316       Result = getConstantValue(CE->getOperand(0));
317       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
318       uint64_t Offset =
319         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
320
321       if (getTargetData()->getPointerSize() == 4)
322         Result.IntVal += Offset;
323       else
324         Result.LongVal += Offset;
325       return Result;
326     }
327     case Instruction::Trunc:
328     case Instruction::ZExt:
329     case Instruction::SExt:
330     case Instruction::FPTrunc:
331     case Instruction::FPExt:
332     case Instruction::UIToFP:
333     case Instruction::SIToFP:
334     case Instruction::FPToUI:
335     case Instruction::FPToSI:
336       break;
337     case Instruction::PtrToInt: {
338       Constant *Op = CE->getOperand(0);
339       GenericValue GV = getConstantValue(Op);
340       return GV;
341     }
342     case Instruction::BitCast: {
343       // Bit casts are no-ops but we can only return the GV of the operand if
344       // they are the same basic type (pointer->pointer, packed->packed, etc.)
345       Constant *Op = CE->getOperand(0);
346       GenericValue GV = getConstantValue(Op);
347       if (Op->getType()->getTypeID() == C->getType()->getTypeID())
348         return GV;
349       break;
350     }
351     case Instruction::IntToPtr: {
352       // IntToPtr casts are just so special. Cast to intptr_t first.
353       Constant *Op = CE->getOperand(0);
354       GenericValue GV = getConstantValue(Op);
355       switch (Op->getType()->getTypeID()) {
356         case Type::BoolTyID:    return PTOGV((void*)(uintptr_t)GV.BoolVal);
357         case Type::SByteTyID:   return PTOGV((void*)( intptr_t)GV.SByteVal);
358         case Type::UByteTyID:   return PTOGV((void*)(uintptr_t)GV.UByteVal);
359         case Type::ShortTyID:   return PTOGV((void*)( intptr_t)GV.ShortVal);
360         case Type::UShortTyID:  return PTOGV((void*)(uintptr_t)GV.UShortVal);
361         case Type::IntTyID:     return PTOGV((void*)( intptr_t)GV.IntVal);
362         case Type::UIntTyID:    return PTOGV((void*)(uintptr_t)GV.UIntVal);
363         case Type::LongTyID:    return PTOGV((void*)( intptr_t)GV.LongVal);
364         case Type::ULongTyID:   return PTOGV((void*)(uintptr_t)GV.ULongVal);
365         default: assert(0 && "Unknown integral type!");
366       }
367       break;
368     }
369     case Instruction::Add:
370       switch (CE->getOperand(0)->getType()->getTypeID()) {
371       default: assert(0 && "Bad add type!"); abort();
372       case Type::LongTyID:
373       case Type::ULongTyID:
374         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
375                          getConstantValue(CE->getOperand(1)).LongVal;
376         break;
377       case Type::IntTyID:
378       case Type::UIntTyID:
379         Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
380                         getConstantValue(CE->getOperand(1)).IntVal;
381         break;
382       case Type::ShortTyID:
383       case Type::UShortTyID:
384         Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
385                           getConstantValue(CE->getOperand(1)).ShortVal;
386         break;
387       case Type::SByteTyID:
388       case Type::UByteTyID:
389         Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
390                           getConstantValue(CE->getOperand(1)).SByteVal;
391         break;
392       case Type::FloatTyID:
393         Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
394                           getConstantValue(CE->getOperand(1)).FloatVal;
395         break;
396       case Type::DoubleTyID:
397         Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
398                            getConstantValue(CE->getOperand(1)).DoubleVal;
399         break;
400       }
401       return Result;
402     default:
403       break;
404     }
405     cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
406     abort();
407   }
408
409   switch (C->getType()->getTypeID()) {
410 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
411   case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
412     GET_CONST_VAL(Bool   , bool          , ConstantBool, getValue);
413     GET_CONST_VAL(UByte  , unsigned char , ConstantInt, getZExtValue);
414     GET_CONST_VAL(SByte  , signed char   , ConstantInt, getSExtValue);
415     GET_CONST_VAL(UShort , unsigned short, ConstantInt, getZExtValue);
416     GET_CONST_VAL(Short  , signed short  , ConstantInt, getSExtValue);
417     GET_CONST_VAL(UInt   , unsigned int  , ConstantInt, getZExtValue);
418     GET_CONST_VAL(Int    , signed int    , ConstantInt, getSExtValue);
419     GET_CONST_VAL(ULong  , uint64_t      , ConstantInt, getZExtValue);
420     GET_CONST_VAL(Long   , int64_t       , ConstantInt, getSExtValue);
421     GET_CONST_VAL(Float  , float         , ConstantFP, getValue);
422     GET_CONST_VAL(Double , double        , ConstantFP, getValue);
423 #undef GET_CONST_VAL
424   case Type::PointerTyID:
425     if (isa<ConstantPointerNull>(C))
426       Result.PointerVal = 0;
427     else if (const Function *F = dyn_cast<Function>(C))
428       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
429     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
430       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
431     else
432       assert(0 && "Unknown constant pointer type!");
433     break;
434   default:
435     cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
436     abort();
437   }
438   return Result;
439 }
440
441 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
442 /// is the address of the memory at which to store Val, cast to GenericValue *.
443 /// It is not a pointer to a GenericValue containing the address at which to
444 /// store Val.
445 ///
446 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
447                                          const Type *Ty) {
448   if (getTargetData()->isLittleEndian()) {
449     switch (Ty->getTypeID()) {
450     case Type::BoolTyID:
451     case Type::UByteTyID:
452     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
453     case Type::UShortTyID:
454     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
455                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
456                             break;
457     Store4BytesLittleEndian:
458     case Type::FloatTyID:
459     case Type::UIntTyID:
460     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
461                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
462                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
463                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
464                             break;
465     case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
466                               goto Store4BytesLittleEndian;
467     case Type::DoubleTyID:
468     case Type::ULongTyID:
469     case Type::LongTyID:
470       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal      );
471       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >>  8);
472       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
473       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
474       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
475       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
476       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
477       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
478       break;
479     default:
480       cerr << "Cannot store value of type " << *Ty << "!\n";
481     }
482   } else {
483     switch (Ty->getTypeID()) {
484     case Type::BoolTyID:
485     case Type::UByteTyID:
486     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
487     case Type::UShortTyID:
488     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
489                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
490                             break;
491     Store4BytesBigEndian:
492     case Type::FloatTyID:
493     case Type::UIntTyID:
494     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
495                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
496                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
497                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
498                             break;
499     case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
500                               goto Store4BytesBigEndian;
501     case Type::DoubleTyID:
502     case Type::ULongTyID:
503     case Type::LongTyID:
504       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal      );
505       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >>  8);
506       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
507       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
508       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
509       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
510       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
511       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
512       break;
513     default:
514       cerr << "Cannot store value of type " << *Ty << "!\n";
515     }
516   }
517 }
518
519 /// FIXME: document
520 ///
521 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
522                                                   const Type *Ty) {
523   GenericValue Result;
524   if (getTargetData()->isLittleEndian()) {
525     switch (Ty->getTypeID()) {
526     case Type::BoolTyID:
527     case Type::UByteTyID:
528     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
529     case Type::UShortTyID:
530     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
531                                               ((unsigned)Ptr->Untyped[1] << 8);
532                             break;
533     Load4BytesLittleEndian:
534     case Type::FloatTyID:
535     case Type::UIntTyID:
536     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
537                                             ((unsigned)Ptr->Untyped[1] <<  8) |
538                                             ((unsigned)Ptr->Untyped[2] << 16) |
539                                             ((unsigned)Ptr->Untyped[3] << 24);
540                             break;
541     case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
542                               goto Load4BytesLittleEndian;
543     case Type::DoubleTyID:
544     case Type::ULongTyID:
545     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
546                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
547                                              ((uint64_t)Ptr->Untyped[2] << 16) |
548                                              ((uint64_t)Ptr->Untyped[3] << 24) |
549                                              ((uint64_t)Ptr->Untyped[4] << 32) |
550                                              ((uint64_t)Ptr->Untyped[5] << 40) |
551                                              ((uint64_t)Ptr->Untyped[6] << 48) |
552                                              ((uint64_t)Ptr->Untyped[7] << 56);
553                             break;
554     default:
555       cerr << "Cannot load value of type " << *Ty << "!\n";
556       abort();
557     }
558   } else {
559     switch (Ty->getTypeID()) {
560     case Type::BoolTyID:
561     case Type::UByteTyID:
562     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
563     case Type::UShortTyID:
564     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
565                                               ((unsigned)Ptr->Untyped[0] << 8);
566                             break;
567     Load4BytesBigEndian:
568     case Type::FloatTyID:
569     case Type::UIntTyID:
570     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
571                                             ((unsigned)Ptr->Untyped[2] <<  8) |
572                                             ((unsigned)Ptr->Untyped[1] << 16) |
573                                             ((unsigned)Ptr->Untyped[0] << 24);
574                             break;
575     case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
576                               goto Load4BytesBigEndian;
577     case Type::DoubleTyID:
578     case Type::ULongTyID:
579     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
580                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
581                                              ((uint64_t)Ptr->Untyped[5] << 16) |
582                                              ((uint64_t)Ptr->Untyped[4] << 24) |
583                                              ((uint64_t)Ptr->Untyped[3] << 32) |
584                                              ((uint64_t)Ptr->Untyped[2] << 40) |
585                                              ((uint64_t)Ptr->Untyped[1] << 48) |
586                                              ((uint64_t)Ptr->Untyped[0] << 56);
587                             break;
588     default:
589       cerr << "Cannot load value of type " << *Ty << "!\n";
590       abort();
591     }
592   }
593   return Result;
594 }
595
596 // InitializeMemory - Recursive function to apply a Constant value into the
597 // specified memory location...
598 //
599 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
600   if (isa<UndefValue>(Init)) {
601     return;
602   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
603     unsigned ElementSize =
604       getTargetData()->getTypeSize(CP->getType()->getElementType());
605     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
606       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
607     return;
608   } else if (Init->getType()->isFirstClassType()) {
609     GenericValue Val = getConstantValue(Init);
610     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
611     return;
612   } else if (isa<ConstantAggregateZero>(Init)) {
613     memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
614     return;
615   }
616
617   switch (Init->getType()->getTypeID()) {
618   case Type::ArrayTyID: {
619     const ConstantArray *CPA = cast<ConstantArray>(Init);
620     unsigned ElementSize =
621       getTargetData()->getTypeSize(CPA->getType()->getElementType());
622     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
623       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
624     return;
625   }
626
627   case Type::StructTyID: {
628     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
629     const StructLayout *SL =
630       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
631     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
632       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
633     return;
634   }
635
636   default:
637     cerr << "Bad Type: " << *Init->getType() << "\n";
638     assert(0 && "Unknown constant type to initialize memory with!");
639   }
640 }
641
642 /// EmitGlobals - Emit all of the global variables to memory, storing their
643 /// addresses into GlobalAddress.  This must make sure to copy the contents of
644 /// their initializers into the memory.
645 ///
646 void ExecutionEngine::emitGlobals() {
647   const TargetData *TD = getTargetData();
648
649   // Loop over all of the global variables in the program, allocating the memory
650   // to hold them.  If there is more than one module, do a prepass over globals
651   // to figure out how the different modules should link together.
652   //
653   std::map<std::pair<std::string, const Type*>,
654            const GlobalValue*> LinkedGlobalsMap;
655
656   if (Modules.size() != 1) {
657     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
658       Module &M = *Modules[m]->getModule();
659       for (Module::const_global_iterator I = M.global_begin(),
660            E = M.global_end(); I != E; ++I) {
661         const GlobalValue *GV = I;
662         if (GV->hasInternalLinkage() || GV->isExternal() ||
663             GV->hasAppendingLinkage() || !GV->hasName())
664           continue;// Ignore external globals and globals with internal linkage.
665           
666         const GlobalValue *&GVEntry = 
667           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
668
669         // If this is the first time we've seen this global, it is the canonical
670         // version.
671         if (!GVEntry) {
672           GVEntry = GV;
673           continue;
674         }
675         
676         // If the existing global is strong, never replace it.
677         if (GVEntry->hasExternalLinkage() ||
678             GVEntry->hasDLLImportLinkage() ||
679             GVEntry->hasDLLExportLinkage())
680           continue;
681         
682         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
683         // symbol.
684         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
685           GVEntry = GV;
686       }
687     }
688   }
689   
690   std::vector<const GlobalValue*> NonCanonicalGlobals;
691   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
692     Module &M = *Modules[m]->getModule();
693     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
694          I != E; ++I) {
695       // In the multi-module case, see what this global maps to.
696       if (!LinkedGlobalsMap.empty()) {
697         if (const GlobalValue *GVEntry = 
698               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
699           // If something else is the canonical global, ignore this one.
700           if (GVEntry != &*I) {
701             NonCanonicalGlobals.push_back(I);
702             continue;
703           }
704         }
705       }
706       
707       if (!I->isExternal()) {
708         // Get the type of the global.
709         const Type *Ty = I->getType()->getElementType();
710
711         // Allocate some memory for it!
712         unsigned Size = TD->getTypeSize(Ty);
713         addGlobalMapping(I, new char[Size]);
714       } else {
715         // External variable reference. Try to use the dynamic loader to
716         // get a pointer to it.
717         if (void *SymAddr =
718             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
719           addGlobalMapping(I, SymAddr);
720         else {
721           cerr << "Could not resolve external global address: "
722                << I->getName() << "\n";
723           abort();
724         }
725       }
726     }
727     
728     // If there are multiple modules, map the non-canonical globals to their
729     // canonical location.
730     if (!NonCanonicalGlobals.empty()) {
731       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
732         const GlobalValue *GV = NonCanonicalGlobals[i];
733         const GlobalValue *CGV =
734           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
735         void *Ptr = getPointerToGlobalIfAvailable(CGV);
736         assert(Ptr && "Canonical global wasn't codegen'd!");
737         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
738       }
739     }
740     
741     // Now that all of the globals are set up in memory, loop through them all and
742     // initialize their contents.
743     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
744          I != E; ++I) {
745       if (!I->isExternal()) {
746         if (!LinkedGlobalsMap.empty()) {
747           if (const GlobalValue *GVEntry = 
748                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
749             if (GVEntry != &*I)  // Not the canonical variable.
750               continue;
751         }
752         EmitGlobalVariable(I);
753       }
754     }
755   }
756 }
757
758 // EmitGlobalVariable - This method emits the specified global variable to the
759 // address specified in GlobalAddresses, or allocates new memory if it's not
760 // already in the map.
761 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
762   void *GA = getPointerToGlobalIfAvailable(GV);
763   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
764
765   const Type *ElTy = GV->getType()->getElementType();
766   size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
767   if (GA == 0) {
768     // If it's not already specified, allocate memory for the global.
769     GA = new char[GVSize];
770     addGlobalMapping(GV, GA);
771   }
772
773   InitializeMemory(GV->getInitializer(), GA);
774   NumInitBytes += (unsigned)GVSize;
775   ++NumGlobals;
776 }