note to self: *save* file, then check it in
[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/System/DynamicLibrary.h"
25 #include "llvm/Target/TargetData.h"
26 #include <iostream>
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   CurMod(*P->getModule()), MP(P) {
39   assert(P && "ModuleProvider is null?");
40 }
41
42 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
43   assert(M && "Module is null?");
44 }
45
46 ExecutionEngine::~ExecutionEngine() {
47   delete MP;
48 }
49
50 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
51 /// at the specified address.
52 ///
53 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
54   MutexGuard locked(lock);
55
56   // If we haven't computed the reverse mapping yet, do so first.
57   if (state.getGlobalAddressReverseMap(locked).empty()) {
58     for (std::map<const GlobalValue*, void *>::iterator I =
59            state.getGlobalAddressMap(locked).begin(), E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
60       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, I->first));
61   }
62
63   std::map<void *, const GlobalValue*>::iterator I =
64     state.getGlobalAddressReverseMap(locked).find(Addr);
65   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
66 }
67
68 // CreateArgv - Turn a vector of strings into a nice argv style array of
69 // pointers to null terminated strings.
70 //
71 static void *CreateArgv(ExecutionEngine *EE,
72                         const std::vector<std::string> &InputArgv) {
73   unsigned PtrSize = EE->getTargetData().getPointerSize();
74   char *Result = new char[(InputArgv.size()+1)*PtrSize];
75
76   DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
77   const Type *SBytePtr = PointerType::get(Type::SByteTy);
78
79   for (unsigned i = 0; i != InputArgv.size(); ++i) {
80     unsigned Size = InputArgv[i].size()+1;
81     char *Dest = new char[Size];
82     DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
83
84     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
85     Dest[Size-1] = 0;
86
87     // Endian safe: Result[i] = (PointerTy)Dest;
88     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
89                            SBytePtr);
90   }
91
92   // Null terminate it
93   EE->StoreValueToMemory(PTOGV(0),
94                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
95                          SBytePtr);
96   return Result;
97 }
98
99
100 /// runStaticConstructorsDestructors - This method is used to execute all of
101 /// the static constructors or destructors for a module, depending on the
102 /// value of isDtors.
103 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
104   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
105   GlobalVariable *GV = CurMod.getNamedGlobal(Name);
106   if (!GV || GV->isExternal() || !GV->hasInternalLinkage()) return;
107   
108   // Should be an array of '{ int, void ()* }' structs.  The first value is the
109   // init priority, which we ignore.
110   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
111   if (!InitList) return;
112   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
113     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
114       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
115       
116       Constant *FP = CS->getOperand(1);
117       if (FP->isNullValue())
118         return;  // Found a null terminator, exit.
119       
120       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
121         if (CE->getOpcode() == Instruction::Cast)
122           FP = CE->getOperand(0);
123       if (Function *F = dyn_cast<Function>(FP)) {
124         // Execute the ctor/dtor function!
125         runFunction(F, std::vector<GenericValue>());
126       }
127     }
128 }
129
130 /// runFunctionAsMain - This is a helper function which wraps runFunction to
131 /// handle the common task of starting up main with the specified argc, argv,
132 /// and envp parameters.
133 int ExecutionEngine::runFunctionAsMain(Function *Fn,
134                                        const std::vector<std::string> &argv,
135                                        const char * const * envp) {
136   std::vector<GenericValue> GVArgs;
137   GenericValue GVArgc;
138   GVArgc.IntVal = argv.size();
139   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
140   if (NumArgs) {
141     GVArgs.push_back(GVArgc); // Arg #0 = argc.
142     if (NumArgs > 1) {
143       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
144       assert(((char **)GVTOP(GVArgs[1]))[0] &&
145              "argv[0] was null after CreateArgv");
146       if (NumArgs > 2) {
147         std::vector<std::string> EnvVars;
148         for (unsigned i = 0; envp[i]; ++i)
149           EnvVars.push_back(envp[i]);
150         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
151       }
152     }
153   }
154   return runFunction(Fn, GVArgs).IntVal;
155 }
156
157 /// If possible, create a JIT, unless the caller specifically requests an
158 /// Interpreter or there's an error. If even an Interpreter cannot be created,
159 /// NULL is returned.
160 ///
161 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
162                                          bool ForceInterpreter) {
163   ExecutionEngine *EE = 0;
164
165   // Unless the interpreter was explicitly selected, try making a JIT.
166   if (!ForceInterpreter && JITCtor)
167     EE = JITCtor(MP);
168
169   // If we can't make a JIT, make an interpreter instead.
170   if (EE == 0 && InterpCtor)
171     EE = InterpCtor(MP);
172
173   if (EE) {
174     // Make sure we can resolve symbols in the program as well. The zero arg
175     // to the function tells DynamicLibrary to load the program, not a library.
176     sys::DynamicLibrary::LoadLibraryPermanently(0);
177   }
178
179   return EE;
180 }
181
182 /// getPointerToGlobal - This returns the address of the specified global
183 /// value.  This may involve code generation if it's a function.
184 ///
185 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
186   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
187     return getPointerToFunction(F);
188
189   MutexGuard locked(lock);
190   void *p = state.getGlobalAddressMap(locked)[GV];
191   if (p)
192     return p;
193
194   // Global variable might have been added since interpreter started.
195   if (GlobalVariable *GVar =
196           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
197     EmitGlobalVariable(GVar);
198   else
199     assert("Global hasn't had an address allocated yet!");
200   return state.getGlobalAddressMap(locked)[GV];
201 }
202
203 /// FIXME: document
204 ///
205 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
206   GenericValue Result;
207   if (isa<UndefValue>(C)) return Result;
208
209   if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
210     switch (CE->getOpcode()) {
211     case Instruction::GetElementPtr: {
212       Result = getConstantValue(CE->getOperand(0));
213       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
214       uint64_t Offset =
215         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
216
217       if (getTargetData().getPointerSize() == 4)
218         Result.IntVal += Offset;
219       else
220         Result.LongVal += Offset;
221       return Result;
222     }
223     case Instruction::Cast: {
224       // We only need to handle a few cases here.  Almost all casts will
225       // automatically fold, just the ones involving pointers won't.
226       //
227       Constant *Op = CE->getOperand(0);
228       GenericValue GV = getConstantValue(Op);
229
230       // Handle cast of pointer to pointer...
231       if (Op->getType()->getTypeID() == C->getType()->getTypeID())
232         return GV;
233
234       // Handle a cast of pointer to any integral type...
235       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
236         return GV;
237
238       // Handle cast of integer to a pointer...
239       if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
240         switch (Op->getType()->getTypeID()) {
241         case Type::BoolTyID:    return PTOGV((void*)(uintptr_t)GV.BoolVal);
242         case Type::SByteTyID:   return PTOGV((void*)( intptr_t)GV.SByteVal);
243         case Type::UByteTyID:   return PTOGV((void*)(uintptr_t)GV.UByteVal);
244         case Type::ShortTyID:   return PTOGV((void*)( intptr_t)GV.ShortVal);
245         case Type::UShortTyID:  return PTOGV((void*)(uintptr_t)GV.UShortVal);
246         case Type::IntTyID:     return PTOGV((void*)( intptr_t)GV.IntVal);
247         case Type::UIntTyID:    return PTOGV((void*)(uintptr_t)GV.UIntVal);
248         case Type::LongTyID:    return PTOGV((void*)( intptr_t)GV.LongVal);
249         case Type::ULongTyID:   return PTOGV((void*)(uintptr_t)GV.ULongVal);
250         default: assert(0 && "Unknown integral type!");
251         }
252       break;
253     }
254
255     case Instruction::Add:
256       switch (CE->getOperand(0)->getType()->getTypeID()) {
257       default: assert(0 && "Bad add type!"); abort();
258       case Type::LongTyID:
259       case Type::ULongTyID:
260         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
261                          getConstantValue(CE->getOperand(1)).LongVal;
262         break;
263       case Type::IntTyID:
264       case Type::UIntTyID:
265         Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
266                         getConstantValue(CE->getOperand(1)).IntVal;
267         break;
268       case Type::ShortTyID:
269       case Type::UShortTyID:
270         Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
271                           getConstantValue(CE->getOperand(1)).ShortVal;
272         break;
273       case Type::SByteTyID:
274       case Type::UByteTyID:
275         Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
276                           getConstantValue(CE->getOperand(1)).SByteVal;
277         break;
278       case Type::FloatTyID:
279         Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
280                           getConstantValue(CE->getOperand(1)).FloatVal;
281         break;
282       case Type::DoubleTyID:
283         Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
284                            getConstantValue(CE->getOperand(1)).DoubleVal;
285         break;
286       }
287       return Result;
288     default:
289       break;
290     }
291     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
292     abort();
293   }
294
295   switch (C->getType()->getTypeID()) {
296 #define GET_CONST_VAL(TY, CTY, CLASS) \
297   case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
298     GET_CONST_VAL(Bool   , bool          , ConstantBool);
299     GET_CONST_VAL(UByte  , unsigned char , ConstantUInt);
300     GET_CONST_VAL(SByte  , signed char   , ConstantSInt);
301     GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
302     GET_CONST_VAL(Short  , signed short  , ConstantSInt);
303     GET_CONST_VAL(UInt   , unsigned int  , ConstantUInt);
304     GET_CONST_VAL(Int    , signed int    , ConstantSInt);
305     GET_CONST_VAL(ULong  , uint64_t      , ConstantUInt);
306     GET_CONST_VAL(Long   , int64_t       , ConstantSInt);
307     GET_CONST_VAL(Float  , float         , ConstantFP);
308     GET_CONST_VAL(Double , double        , ConstantFP);
309 #undef GET_CONST_VAL
310   case Type::PointerTyID:
311     if (isa<ConstantPointerNull>(C))
312       Result.PointerVal = 0;
313     else if (const Function *F = dyn_cast<Function>(C))
314       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
315     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
316       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
317     else
318       assert(0 && "Unknown constant pointer type!");
319     break;
320   default:
321     std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
322     abort();
323   }
324   return Result;
325 }
326
327 /// FIXME: document
328 ///
329 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
330                                          const Type *Ty) {
331   if (getTargetData().isLittleEndian()) {
332     switch (Ty->getTypeID()) {
333     case Type::BoolTyID:
334     case Type::UByteTyID:
335     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
336     case Type::UShortTyID:
337     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
338                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
339                             break;
340     Store4BytesLittleEndian:
341     case Type::FloatTyID:
342     case Type::UIntTyID:
343     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
344                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
345                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
346                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
347                             break;
348     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
349                               goto Store4BytesLittleEndian;
350     case Type::DoubleTyID:
351     case Type::ULongTyID:
352     case Type::LongTyID:
353       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal      );
354       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >>  8);
355       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
356       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
357       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
358       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
359       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
360       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
361       break;
362     default:
363       std::cout << "Cannot store value of type " << *Ty << "!\n";
364     }
365   } else {
366     switch (Ty->getTypeID()) {
367     case Type::BoolTyID:
368     case Type::UByteTyID:
369     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
370     case Type::UShortTyID:
371     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
372                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
373                             break;
374     Store4BytesBigEndian:
375     case Type::FloatTyID:
376     case Type::UIntTyID:
377     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
378                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
379                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
380                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
381                             break;
382     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
383                               goto Store4BytesBigEndian;
384     case Type::DoubleTyID:
385     case Type::ULongTyID:
386     case Type::LongTyID:
387       Ptr->Untyped[7] = (unsigned char)(Val.ULongVal      );
388       Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >>  8);
389       Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
390       Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
391       Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
392       Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
393       Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
394       Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
395       break;
396     default:
397       std::cout << "Cannot store value of type " << *Ty << "!\n";
398     }
399   }
400 }
401
402 /// FIXME: document
403 ///
404 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
405                                                   const Type *Ty) {
406   GenericValue Result;
407   if (getTargetData().isLittleEndian()) {
408     switch (Ty->getTypeID()) {
409     case Type::BoolTyID:
410     case Type::UByteTyID:
411     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
412     case Type::UShortTyID:
413     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
414                                               ((unsigned)Ptr->Untyped[1] << 8);
415                             break;
416     Load4BytesLittleEndian:
417     case Type::FloatTyID:
418     case Type::UIntTyID:
419     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
420                                             ((unsigned)Ptr->Untyped[1] <<  8) |
421                                             ((unsigned)Ptr->Untyped[2] << 16) |
422                                             ((unsigned)Ptr->Untyped[3] << 24);
423                             break;
424     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
425                               goto Load4BytesLittleEndian;
426     case Type::DoubleTyID:
427     case Type::ULongTyID:
428     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
429                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
430                                              ((uint64_t)Ptr->Untyped[2] << 16) |
431                                              ((uint64_t)Ptr->Untyped[3] << 24) |
432                                              ((uint64_t)Ptr->Untyped[4] << 32) |
433                                              ((uint64_t)Ptr->Untyped[5] << 40) |
434                                              ((uint64_t)Ptr->Untyped[6] << 48) |
435                                              ((uint64_t)Ptr->Untyped[7] << 56);
436                             break;
437     default:
438       std::cout << "Cannot load value of type " << *Ty << "!\n";
439       abort();
440     }
441   } else {
442     switch (Ty->getTypeID()) {
443     case Type::BoolTyID:
444     case Type::UByteTyID:
445     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
446     case Type::UShortTyID:
447     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
448                                               ((unsigned)Ptr->Untyped[0] << 8);
449                             break;
450     Load4BytesBigEndian:
451     case Type::FloatTyID:
452     case Type::UIntTyID:
453     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
454                                             ((unsigned)Ptr->Untyped[2] <<  8) |
455                                             ((unsigned)Ptr->Untyped[1] << 16) |
456                                             ((unsigned)Ptr->Untyped[0] << 24);
457                             break;
458     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
459                               goto Load4BytesBigEndian;
460     case Type::DoubleTyID:
461     case Type::ULongTyID:
462     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
463                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
464                                              ((uint64_t)Ptr->Untyped[5] << 16) |
465                                              ((uint64_t)Ptr->Untyped[4] << 24) |
466                                              ((uint64_t)Ptr->Untyped[3] << 32) |
467                                              ((uint64_t)Ptr->Untyped[2] << 40) |
468                                              ((uint64_t)Ptr->Untyped[1] << 48) |
469                                              ((uint64_t)Ptr->Untyped[0] << 56);
470                             break;
471     default:
472       std::cout << "Cannot load value of type " << *Ty << "!\n";
473       abort();
474     }
475   }
476   return Result;
477 }
478
479 // InitializeMemory - Recursive function to apply a Constant value into the
480 // specified memory location...
481 //
482 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
483   if (isa<UndefValue>(Init)) {
484     return;
485   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
486     unsigned ElementSize =
487       getTargetData().getTypeSize(CP->getType()->getElementType());
488     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
489       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
490     return;
491   } else if (Init->getType()->isFirstClassType()) {
492     GenericValue Val = getConstantValue(Init);
493     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
494     return;
495   } else if (isa<ConstantAggregateZero>(Init)) {
496     memset(Addr, 0, (size_t)getTargetData().getTypeSize(Init->getType()));
497     return;
498   }
499
500   switch (Init->getType()->getTypeID()) {
501   case Type::ArrayTyID: {
502     const ConstantArray *CPA = cast<ConstantArray>(Init);
503     unsigned ElementSize =
504       getTargetData().getTypeSize(CPA->getType()->getElementType());
505     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
506       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
507     return;
508   }
509
510   case Type::StructTyID: {
511     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
512     const StructLayout *SL =
513       getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
514     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
515       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
516     return;
517   }
518
519   default:
520     std::cerr << "Bad Type: " << *Init->getType() << "\n";
521     assert(0 && "Unknown constant type to initialize memory with!");
522   }
523 }
524
525 /// EmitGlobals - Emit all of the global variables to memory, storing their
526 /// addresses into GlobalAddress.  This must make sure to copy the contents of
527 /// their initializers into the memory.
528 ///
529 void ExecutionEngine::emitGlobals() {
530   const TargetData &TD = getTargetData();
531
532   // Loop over all of the global variables in the program, allocating the memory
533   // to hold them.
534   Module &M = getModule();
535   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
536        I != E; ++I)
537     if (!I->isExternal()) {
538       // Get the type of the global...
539       const Type *Ty = I->getType()->getElementType();
540
541       // Allocate some memory for it!
542       unsigned Size = TD.getTypeSize(Ty);
543       addGlobalMapping(I, new char[Size]);
544     } else {
545       // External variable reference. Try to use the dynamic loader to
546       // get a pointer to it.
547       if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
548                             I->getName().c_str()))
549         addGlobalMapping(I, SymAddr);
550       else {
551         std::cerr << "Could not resolve external global address: "
552                   << I->getName() << "\n";
553         abort();
554       }
555     }
556
557   // Now that all of the globals are set up in memory, loop through them all and
558   // initialize their contents.
559   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
560        I != E; ++I)
561     if (!I->isExternal())
562       EmitGlobalVariable(I);
563 }
564
565 // EmitGlobalVariable - This method emits the specified global variable to the
566 // address specified in GlobalAddresses, or allocates new memory if it's not
567 // already in the map.
568 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
569   void *GA = getPointerToGlobalIfAvailable(GV);
570   DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
571
572   const Type *ElTy = GV->getType()->getElementType();
573   size_t GVSize = (size_t)getTargetData().getTypeSize(ElTy);
574   if (GA == 0) {
575     // If it's not already specified, allocate memory for the global.
576     GA = new char[GVSize];
577     addGlobalMapping(GV, GA);
578   }
579
580   InitializeMemory(GV->getInitializer(), GA);
581   NumInitBytes += (unsigned)GVSize;
582   ++NumGlobals;
583 }