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