1//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/ExecutionEngine/ExecutionEngine.h"
17
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Module.h"
21#include "llvm/ExecutionEngine/GenericValue.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MutexGuard.h"
27#include "llvm/Support/ValueHandle.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetMachine.h"
33#include <cmath>
34#include <cstring>
35using namespace llvm;
36
37STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38STATISTIC(NumGlobals  , "Number of global vars initialized");
39
40ExecutionEngine *(*ExecutionEngine::JITCtor)(
41  Module *M,
42  std::string *ErrorStr,
43  JITMemoryManager *JMM,
44  CodeGenOpt::Level OptLevel,
45  bool GVsWithCode,
46  TargetMachine *TM) = 0;
47ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
48  Module *M,
49  std::string *ErrorStr,
50  JITMemoryManager *JMM,
51  CodeGenOpt::Level OptLevel,
52  bool GVsWithCode,
53  TargetMachine *TM) = 0;
54ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55                                                std::string *ErrorStr) = 0;
56
57ExecutionEngine::ExecutionEngine(Module *M)
58  : EEState(*this),
59    LazyFunctionCreator(0),
60    ExceptionTableRegister(0),
61    ExceptionTableDeregister(0) {
62  CompilingLazily         = false;
63  GVCompilationDisabled   = false;
64  SymbolSearchingDisabled = false;
65  Modules.push_back(M);
66  assert(M && "Module is null?");
67}
68
69ExecutionEngine::~ExecutionEngine() {
70  clearAllGlobalMappings();
71  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
72    delete Modules[i];
73}
74
75void ExecutionEngine::DeregisterAllTables() {
76  if (ExceptionTableDeregister) {
77    DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78    DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79    for (; it != ite; ++it)
80      ExceptionTableDeregister(it->second);
81    AllExceptionTables.clear();
82  }
83}
84
85namespace {
86/// \brief Helper class which uses a value handler to automatically deletes the
87/// memory block when the GlobalVariable is destroyed.
88class GVMemoryBlock : public CallbackVH {
89  GVMemoryBlock(const GlobalVariable *GV)
90    : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
91
92public:
93  /// \brief Returns the address the GlobalVariable should be written into.  The
94  /// GVMemoryBlock object prefixes that.
95  static char *Create(const GlobalVariable *GV, const TargetData& TD) {
96    Type *ElTy = GV->getType()->getElementType();
97    size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98    void *RawMemory = ::operator new(
99      TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
100                                   TD.getPreferredAlignment(GV))
101      + GVSize);
102    new(RawMemory) GVMemoryBlock(GV);
103    return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
104  }
105
106  virtual void deleted() {
107    // We allocated with operator new and with some extra memory hanging off the
108    // end, so don't just delete this.  I'm not sure if this is actually
109    // required.
110    this->~GVMemoryBlock();
111    ::operator delete(this);
112  }
113};
114}  // anonymous namespace
115
116char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117  return GVMemoryBlock::Create(GV, *getTargetData());
118}
119
120bool ExecutionEngine::removeModule(Module *M) {
121  for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122        E = Modules.end(); I != E; ++I) {
123    Module *Found = *I;
124    if (Found == M) {
125      Modules.erase(I);
126      clearGlobalMappingsFromModule(M);
127      return true;
128    }
129  }
130  return false;
131}
132
133Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134  for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135    if (Function *F = Modules[i]->getFunction(FnName))
136      return F;
137  }
138  return 0;
139}
140
141
142void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143                                          const GlobalValue *ToUnmap) {
144  GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
145  void *OldVal;
146
147  // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
148  // GlobalAddressMap.
149  if (I == GlobalAddressMap.end())
150    OldVal = 0;
151  else {
152    OldVal = I->second;
153    GlobalAddressMap.erase(I);
154  }
155
156  GlobalAddressReverseMap.erase(OldVal);
157  return OldVal;
158}
159
160void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161  MutexGuard locked(lock);
162
163  DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
164        << "\' to [" << Addr << "]\n";);
165  void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
166  assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
167  CurVal = Addr;
168
169  // If we are using the reverse mapping, add it too.
170  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
171    AssertingVH<const GlobalValue> &V =
172      EEState.getGlobalAddressReverseMap(locked)[Addr];
173    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
174    V = GV;
175  }
176}
177
178void ExecutionEngine::clearAllGlobalMappings() {
179  MutexGuard locked(lock);
180
181  EEState.getGlobalAddressMap(locked).clear();
182  EEState.getGlobalAddressReverseMap(locked).clear();
183}
184
185void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186  MutexGuard locked(lock);
187
188  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189    EEState.RemoveMapping(locked, FI);
190  for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
191       GI != GE; ++GI)
192    EEState.RemoveMapping(locked, GI);
193}
194
195void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
196  MutexGuard locked(lock);
197
198  ExecutionEngineState::GlobalAddressMapTy &Map =
199    EEState.getGlobalAddressMap(locked);
200
201  // Deleting from the mapping?
202  if (Addr == 0)
203    return EEState.RemoveMapping(locked, GV);
204
205  void *&CurVal = Map[GV];
206  void *OldVal = CurVal;
207
208  if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209    EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
210  CurVal = Addr;
211
212  // If we are using the reverse mapping, add it too.
213  if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
214    AssertingVH<const GlobalValue> &V =
215      EEState.getGlobalAddressReverseMap(locked)[Addr];
216    assert((V == 0 || GV == 0) && "GlobalMapping already established!");
217    V = GV;
218  }
219  return OldVal;
220}
221
222void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223  MutexGuard locked(lock);
224
225  ExecutionEngineState::GlobalAddressMapTy::iterator I =
226    EEState.getGlobalAddressMap(locked).find(GV);
227  return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
228}
229
230const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
231  MutexGuard locked(lock);
232
233  // If we haven't computed the reverse mapping yet, do so first.
234  if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235    for (ExecutionEngineState::GlobalAddressMapTy::iterator
236         I = EEState.getGlobalAddressMap(locked).begin(),
237         E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238      EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239                                                          I->second, I->first));
240  }
241
242  std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243    EEState.getGlobalAddressReverseMap(locked).find(Addr);
244  return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
245}
246
247namespace {
248class ArgvArray {
249  char *Array;
250  std::vector<char*> Values;
251public:
252  ArgvArray() : Array(NULL) {}
253  ~ArgvArray() { clear(); }
254  void clear() {
255    delete[] Array;
256    Array = NULL;
257    for (size_t I = 0, E = Values.size(); I != E; ++I) {
258      delete[] Values[I];
259    }
260    Values.clear();
261  }
262  /// Turn a vector of strings into a nice argv style array of pointers to null
263  /// terminated strings.
264  void *reset(LLVMContext &C, ExecutionEngine *EE,
265              const std::vector<std::string> &InputArgv);
266};
267}  // anonymous namespace
268void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269                       const std::vector<std::string> &InputArgv) {
270  clear();  // Free the old contents.
271  unsigned PtrSize = EE->getTargetData()->getPointerSize();
272  Array = new char[(InputArgv.size()+1)*PtrSize];
273
274  DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275  Type *SBytePtr = Type::getInt8PtrTy(C);
276
277  for (unsigned i = 0; i != InputArgv.size(); ++i) {
278    unsigned Size = InputArgv[i].size()+1;
279    char *Dest = new char[Size];
280    Values.push_back(Dest);
281    DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
282
283    std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
284    Dest[Size-1] = 0;
285
286    // Endian safe: Array[i] = (PointerTy)Dest;
287    EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
288                           SBytePtr);
289  }
290
291  // Null terminate it
292  EE->StoreValueToMemory(PTOGV(0),
293                         (GenericValue*)(Array+InputArgv.size()*PtrSize),
294                         SBytePtr);
295  return Array;
296}
297
298void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
299                                                       bool isDtors) {
300  const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
301  GlobalVariable *GV = module->getNamedGlobal(Name);
302
303  // If this global has internal linkage, or if it has a use, then it must be
304  // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
305  // this is the case, don't execute any of the global ctors, __main will do
306  // it.
307  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
308
309  // Should be an array of '{ i32, void ()* }' structs.  The first value is
310  // the init priority, which we ignore.
311  if (isa<ConstantAggregateZero>(GV->getInitializer()))
312    return;
313  ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
314  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315    if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
316      continue;
317    ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
318
319    Constant *FP = CS->getOperand(1);
320    if (FP->isNullValue())
321      continue;  // Found a sentinal value, ignore.
322
323    // Strip off constant expression casts.
324    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325      if (CE->isCast())
326        FP = CE->getOperand(0);
327
328    // Execute the ctor/dtor function!
329    if (Function *F = dyn_cast<Function>(FP))
330      runFunction(F, std::vector<GenericValue>());
331
332    // FIXME: It is marginally lame that we just do nothing here if we see an
333    // entry we don't recognize. It might not be unreasonable for the verifier
334    // to not even allow this and just assert here.
335  }
336}
337
338void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
339  // Execute global ctors/dtors for each module in the program.
340  for (unsigned i = 0, e = Modules.size(); i != e; ++i)
341    runStaticConstructorsDestructors(Modules[i], isDtors);
342}
343
344#ifndef NDEBUG
345/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
346static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
347  unsigned PtrSize = EE->getTargetData()->getPointerSize();
348  for (unsigned i = 0; i < PtrSize; ++i)
349    if (*(i + (uint8_t*)Loc))
350      return false;
351  return true;
352}
353#endif
354
355int ExecutionEngine::runFunctionAsMain(Function *Fn,
356                                       const std::vector<std::string> &argv,
357                                       const char * const * envp) {
358  std::vector<GenericValue> GVArgs;
359  GenericValue GVArgc;
360  GVArgc.IntVal = APInt(32, argv.size());
361
362  // Check main() type
363  unsigned NumArgs = Fn->getFunctionType()->getNumParams();
364  FunctionType *FTy = Fn->getFunctionType();
365  Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366
367  // Check the argument types.
368  if (NumArgs > 3)
369    report_fatal_error("Invalid number of arguments of main() supplied");
370  if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
371    report_fatal_error("Invalid type for third argument of main() supplied");
372  if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
373    report_fatal_error("Invalid type for second argument of main() supplied");
374  if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
375    report_fatal_error("Invalid type for first argument of main() supplied");
376  if (!FTy->getReturnType()->isIntegerTy() &&
377      !FTy->getReturnType()->isVoidTy())
378    report_fatal_error("Invalid return type of main() supplied");
379
380  ArgvArray CArgv;
381  ArgvArray CEnv;
382  if (NumArgs) {
383    GVArgs.push_back(GVArgc); // Arg #0 = argc.
384    if (NumArgs > 1) {
385      // Arg #1 = argv.
386      GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
387      assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
388             "argv[0] was null after CreateArgv");
389      if (NumArgs > 2) {
390        std::vector<std::string> EnvVars;
391        for (unsigned i = 0; envp[i]; ++i)
392          EnvVars.push_back(envp[i]);
393        // Arg #2 = envp.
394        GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
395      }
396    }
397  }
398
399  return runFunction(Fn, GVArgs).IntVal.getZExtValue();
400}
401
402ExecutionEngine *ExecutionEngine::create(Module *M,
403                                         bool ForceInterpreter,
404                                         std::string *ErrorStr,
405                                         CodeGenOpt::Level OptLevel,
406                                         bool GVsWithCode) {
407  return EngineBuilder(M)
408      .setEngineKind(ForceInterpreter
409                     ? EngineKind::Interpreter
410                     : EngineKind::JIT)
411      .setErrorStr(ErrorStr)
412      .setOptLevel(OptLevel)
413      .setAllocateGVsWithCode(GVsWithCode)
414      .create();
415}
416
417/// createJIT - This is the factory method for creating a JIT for the current
418/// machine, it does not fall back to the interpreter.  This takes ownership
419/// of the module.
420ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421                                            std::string *ErrorStr,
422                                            JITMemoryManager *JMM,
423                                            CodeGenOpt::Level OptLevel,
424                                            bool GVsWithCode,
425                                            Reloc::Model RM,
426                                            CodeModel::Model CMM) {
427  if (ExecutionEngine::JITCtor == 0) {
428    if (ErrorStr)
429      *ErrorStr = "JIT has not been linked in.";
430    return 0;
431  }
432
433  // Use the defaults for extra parameters.  Users can use EngineBuilder to
434  // set them.
435  StringRef MArch = "";
436  StringRef MCPU = "";
437  SmallVector<std::string, 1> MAttrs;
438
439  TargetMachine *TM =
440    EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, RM, CMM, ErrorStr);
441  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
442
443  return ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, GVsWithCode, TM);
444}
445
446ExecutionEngine *EngineBuilder::create() {
447  // Make sure we can resolve symbols in the program as well. The zero arg
448  // to the function tells DynamicLibrary to load the program, not a library.
449  if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
450    return 0;
451
452  // If the user specified a memory manager but didn't specify which engine to
453  // create, we assume they only want the JIT, and we fail if they only want
454  // the interpreter.
455  if (JMM) {
456    if (WhichEngine & EngineKind::JIT)
457      WhichEngine = EngineKind::JIT;
458    else {
459      if (ErrorStr)
460        *ErrorStr = "Cannot create an interpreter with a memory manager.";
461      return 0;
462    }
463  }
464
465  // Unless the interpreter was explicitly selected or the JIT is not linked,
466  // try making a JIT.
467  if (WhichEngine & EngineKind::JIT) {
468    if (TargetMachine *TM = EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs,
469                                                        RelocModel, CMModel,
470                                                        ErrorStr)) {
471      if (UseMCJIT && ExecutionEngine::MCJITCtor) {
472        ExecutionEngine *EE =
473          ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
474                                     AllocateGVsWithCode, TM);
475        if (EE) return EE;
476      } else if (ExecutionEngine::JITCtor) {
477        ExecutionEngine *EE =
478          ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
479                                   AllocateGVsWithCode, TM);
480        if (EE) return EE;
481      }
482    }
483  }
484
485  // If we can't make a JIT and we didn't request one specifically, try making
486  // an interpreter instead.
487  if (WhichEngine & EngineKind::Interpreter) {
488    if (ExecutionEngine::InterpCtor)
489      return ExecutionEngine::InterpCtor(M, ErrorStr);
490    if (ErrorStr)
491      *ErrorStr = "Interpreter has not been linked in.";
492    return 0;
493  }
494
495  if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
496    if (ErrorStr)
497      *ErrorStr = "JIT has not been linked in.";
498  }
499
500  return 0;
501}
502
503void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
504  if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
505    return getPointerToFunction(F);
506
507  MutexGuard locked(lock);
508  if (void *P = EEState.getGlobalAddressMap(locked)[GV])
509    return P;
510
511  // Global variable might have been added since interpreter started.
512  if (GlobalVariable *GVar =
513          const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
514    EmitGlobalVariable(GVar);
515  else
516    llvm_unreachable("Global hasn't had an address allocated yet!");
517
518  return EEState.getGlobalAddressMap(locked)[GV];
519}
520
521/// \brief Converts a Constant* into a GenericValue, including handling of
522/// ConstantExpr values.
523GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
524  // If its undefined, return the garbage.
525  if (isa<UndefValue>(C)) {
526    GenericValue Result;
527    switch (C->getType()->getTypeID()) {
528    case Type::IntegerTyID:
529    case Type::X86_FP80TyID:
530    case Type::FP128TyID:
531    case Type::PPC_FP128TyID:
532      // Although the value is undefined, we still have to construct an APInt
533      // with the correct bit width.
534      Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
535      break;
536    default:
537      break;
538    }
539    return Result;
540  }
541
542  // Otherwise, if the value is a ConstantExpr...
543  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
544    Constant *Op0 = CE->getOperand(0);
545    switch (CE->getOpcode()) {
546    case Instruction::GetElementPtr: {
547      // Compute the index
548      GenericValue Result = getConstantValue(Op0);
549      SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
550      uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
551
552      char* tmp = (char*) Result.PointerVal;
553      Result = PTOGV(tmp + Offset);
554      return Result;
555    }
556    case Instruction::Trunc: {
557      GenericValue GV = getConstantValue(Op0);
558      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
559      GV.IntVal = GV.IntVal.trunc(BitWidth);
560      return GV;
561    }
562    case Instruction::ZExt: {
563      GenericValue GV = getConstantValue(Op0);
564      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
565      GV.IntVal = GV.IntVal.zext(BitWidth);
566      return GV;
567    }
568    case Instruction::SExt: {
569      GenericValue GV = getConstantValue(Op0);
570      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
571      GV.IntVal = GV.IntVal.sext(BitWidth);
572      return GV;
573    }
574    case Instruction::FPTrunc: {
575      // FIXME long double
576      GenericValue GV = getConstantValue(Op0);
577      GV.FloatVal = float(GV.DoubleVal);
578      return GV;
579    }
580    case Instruction::FPExt:{
581      // FIXME long double
582      GenericValue GV = getConstantValue(Op0);
583      GV.DoubleVal = double(GV.FloatVal);
584      return GV;
585    }
586    case Instruction::UIToFP: {
587      GenericValue GV = getConstantValue(Op0);
588      if (CE->getType()->isFloatTy())
589        GV.FloatVal = float(GV.IntVal.roundToDouble());
590      else if (CE->getType()->isDoubleTy())
591        GV.DoubleVal = GV.IntVal.roundToDouble();
592      else if (CE->getType()->isX86_FP80Ty()) {
593        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
594        (void)apf.convertFromAPInt(GV.IntVal,
595                                   false,
596                                   APFloat::rmNearestTiesToEven);
597        GV.IntVal = apf.bitcastToAPInt();
598      }
599      return GV;
600    }
601    case Instruction::SIToFP: {
602      GenericValue GV = getConstantValue(Op0);
603      if (CE->getType()->isFloatTy())
604        GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
605      else if (CE->getType()->isDoubleTy())
606        GV.DoubleVal = GV.IntVal.signedRoundToDouble();
607      else if (CE->getType()->isX86_FP80Ty()) {
608        APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
609        (void)apf.convertFromAPInt(GV.IntVal,
610                                   true,
611                                   APFloat::rmNearestTiesToEven);
612        GV.IntVal = apf.bitcastToAPInt();
613      }
614      return GV;
615    }
616    case Instruction::FPToUI: // double->APInt conversion handles sign
617    case Instruction::FPToSI: {
618      GenericValue GV = getConstantValue(Op0);
619      uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
620      if (Op0->getType()->isFloatTy())
621        GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
622      else if (Op0->getType()->isDoubleTy())
623        GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
624      else if (Op0->getType()->isX86_FP80Ty()) {
625        APFloat apf = APFloat(GV.IntVal);
626        uint64_t v;
627        bool ignored;
628        (void)apf.convertToInteger(&v, BitWidth,
629                                   CE->getOpcode()==Instruction::FPToSI,
630                                   APFloat::rmTowardZero, &ignored);
631        GV.IntVal = v; // endian?
632      }
633      return GV;
634    }
635    case Instruction::PtrToInt: {
636      GenericValue GV = getConstantValue(Op0);
637      uint32_t PtrWidth = TD->getPointerSizeInBits();
638      GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
639      return GV;
640    }
641    case Instruction::IntToPtr: {
642      GenericValue GV = getConstantValue(Op0);
643      uint32_t PtrWidth = TD->getPointerSizeInBits();
644      if (PtrWidth != GV.IntVal.getBitWidth())
645        GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
646      assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
647      GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
648      return GV;
649    }
650    case Instruction::BitCast: {
651      GenericValue GV = getConstantValue(Op0);
652      Type* DestTy = CE->getType();
653      switch (Op0->getType()->getTypeID()) {
654        default: llvm_unreachable("Invalid bitcast operand");
655        case Type::IntegerTyID:
656          assert(DestTy->isFloatingPointTy() && "invalid bitcast");
657          if (DestTy->isFloatTy())
658            GV.FloatVal = GV.IntVal.bitsToFloat();
659          else if (DestTy->isDoubleTy())
660            GV.DoubleVal = GV.IntVal.bitsToDouble();
661          break;
662        case Type::FloatTyID:
663          assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
664          GV.IntVal = APInt::floatToBits(GV.FloatVal);
665          break;
666        case Type::DoubleTyID:
667          assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
668          GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
669          break;
670        case Type::PointerTyID:
671          assert(DestTy->isPointerTy() && "Invalid bitcast");
672          break; // getConstantValue(Op0)  above already converted it
673      }
674      return GV;
675    }
676    case Instruction::Add:
677    case Instruction::FAdd:
678    case Instruction::Sub:
679    case Instruction::FSub:
680    case Instruction::Mul:
681    case Instruction::FMul:
682    case Instruction::UDiv:
683    case Instruction::SDiv:
684    case Instruction::URem:
685    case Instruction::SRem:
686    case Instruction::And:
687    case Instruction::Or:
688    case Instruction::Xor: {
689      GenericValue LHS = getConstantValue(Op0);
690      GenericValue RHS = getConstantValue(CE->getOperand(1));
691      GenericValue GV;
692      switch (CE->getOperand(0)->getType()->getTypeID()) {
693      default: llvm_unreachable("Bad add type!");
694      case Type::IntegerTyID:
695        switch (CE->getOpcode()) {
696          default: llvm_unreachable("Invalid integer opcode");
697          case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
698          case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
699          case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
700          case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
701          case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
702          case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
703          case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
704          case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
705          case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
706          case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
707        }
708        break;
709      case Type::FloatTyID:
710        switch (CE->getOpcode()) {
711          default: llvm_unreachable("Invalid float opcode");
712          case Instruction::FAdd:
713            GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
714          case Instruction::FSub:
715            GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
716          case Instruction::FMul:
717            GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
718          case Instruction::FDiv:
719            GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
720          case Instruction::FRem:
721            GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
722        }
723        break;
724      case Type::DoubleTyID:
725        switch (CE->getOpcode()) {
726          default: llvm_unreachable("Invalid double opcode");
727          case Instruction::FAdd:
728            GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
729          case Instruction::FSub:
730            GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
731          case Instruction::FMul:
732            GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
733          case Instruction::FDiv:
734            GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
735          case Instruction::FRem:
736            GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
737        }
738        break;
739      case Type::X86_FP80TyID:
740      case Type::PPC_FP128TyID:
741      case Type::FP128TyID: {
742        APFloat apfLHS = APFloat(LHS.IntVal);
743        switch (CE->getOpcode()) {
744          default: llvm_unreachable("Invalid long double opcode");
745          case Instruction::FAdd:
746            apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
747            GV.IntVal = apfLHS.bitcastToAPInt();
748            break;
749          case Instruction::FSub:
750            apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
751            GV.IntVal = apfLHS.bitcastToAPInt();
752            break;
753          case Instruction::FMul:
754            apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
755            GV.IntVal = apfLHS.bitcastToAPInt();
756            break;
757          case Instruction::FDiv:
758            apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
759            GV.IntVal = apfLHS.bitcastToAPInt();
760            break;
761          case Instruction::FRem:
762            apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
763            GV.IntVal = apfLHS.bitcastToAPInt();
764            break;
765          }
766        }
767        break;
768      }
769      return GV;
770    }
771    default:
772      break;
773    }
774
775    SmallString<256> Msg;
776    raw_svector_ostream OS(Msg);
777    OS << "ConstantExpr not handled: " << *CE;
778    report_fatal_error(OS.str());
779  }
780
781  // Otherwise, we have a simple constant.
782  GenericValue Result;
783  switch (C->getType()->getTypeID()) {
784  case Type::FloatTyID:
785    Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
786    break;
787  case Type::DoubleTyID:
788    Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
789    break;
790  case Type::X86_FP80TyID:
791  case Type::FP128TyID:
792  case Type::PPC_FP128TyID:
793    Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
794    break;
795  case Type::IntegerTyID:
796    Result.IntVal = cast<ConstantInt>(C)->getValue();
797    break;
798  case Type::PointerTyID:
799    if (isa<ConstantPointerNull>(C))
800      Result.PointerVal = 0;
801    else if (const Function *F = dyn_cast<Function>(C))
802      Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
803    else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
804      Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
805    else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
806      Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
807                                                        BA->getBasicBlock())));
808    else
809      llvm_unreachable("Unknown constant pointer type!");
810    break;
811  default:
812    SmallString<256> Msg;
813    raw_svector_ostream OS(Msg);
814    OS << "ERROR: Constant unimplemented for type: " << *C->getType();
815    report_fatal_error(OS.str());
816  }
817
818  return Result;
819}
820
821/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
822/// with the integer held in IntVal.
823static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
824                             unsigned StoreBytes) {
825  assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
826  uint8_t *Src = (uint8_t *)IntVal.getRawData();
827
828  if (sys::isLittleEndianHost()) {
829    // Little-endian host - the source is ordered from LSB to MSB.  Order the
830    // destination from LSB to MSB: Do a straight copy.
831    memcpy(Dst, Src, StoreBytes);
832  } else {
833    // Big-endian host - the source is an array of 64 bit words ordered from
834    // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
835    // from MSB to LSB: Reverse the word order, but not the bytes in a word.
836    while (StoreBytes > sizeof(uint64_t)) {
837      StoreBytes -= sizeof(uint64_t);
838      // May not be aligned so use memcpy.
839      memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
840      Src += sizeof(uint64_t);
841    }
842
843    memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
844  }
845}
846
847void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
848                                         GenericValue *Ptr, Type *Ty) {
849  const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
850
851  switch (Ty->getTypeID()) {
852  case Type::IntegerTyID:
853    StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
854    break;
855  case Type::FloatTyID:
856    *((float*)Ptr) = Val.FloatVal;
857    break;
858  case Type::DoubleTyID:
859    *((double*)Ptr) = Val.DoubleVal;
860    break;
861  case Type::X86_FP80TyID:
862    memcpy(Ptr, Val.IntVal.getRawData(), 10);
863    break;
864  case Type::PointerTyID:
865    // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
866    if (StoreBytes != sizeof(PointerTy))
867      memset(&(Ptr->PointerVal), 0, StoreBytes);
868
869    *((PointerTy*)Ptr) = Val.PointerVal;
870    break;
871  default:
872    dbgs() << "Cannot store value of type " << *Ty << "!\n";
873  }
874
875  if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
876    // Host and target are different endian - reverse the stored bytes.
877    std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
878}
879
880/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
881/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
882static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
883  assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
884  uint8_t *Dst = (uint8_t *)IntVal.getRawData();
885
886  if (sys::isLittleEndianHost())
887    // Little-endian host - the destination must be ordered from LSB to MSB.
888    // The source is ordered from LSB to MSB: Do a straight copy.
889    memcpy(Dst, Src, LoadBytes);
890  else {
891    // Big-endian - the destination is an array of 64 bit words ordered from
892    // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
893    // ordered from MSB to LSB: Reverse the word order, but not the bytes in
894    // a word.
895    while (LoadBytes > sizeof(uint64_t)) {
896      LoadBytes -= sizeof(uint64_t);
897      // May not be aligned so use memcpy.
898      memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
899      Dst += sizeof(uint64_t);
900    }
901
902    memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
903  }
904}
905
906/// FIXME: document
907///
908void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
909                                          GenericValue *Ptr,
910                                          Type *Ty) {
911  const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
912
913  switch (Ty->getTypeID()) {
914  case Type::IntegerTyID:
915    // An APInt with all words initially zero.
916    Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
917    LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
918    break;
919  case Type::FloatTyID:
920    Result.FloatVal = *((float*)Ptr);
921    break;
922  case Type::DoubleTyID:
923    Result.DoubleVal = *((double*)Ptr);
924    break;
925  case Type::PointerTyID:
926    Result.PointerVal = *((PointerTy*)Ptr);
927    break;
928  case Type::X86_FP80TyID: {
929    // This is endian dependent, but it will only work on x86 anyway.
930    // FIXME: Will not trap if loading a signaling NaN.
931    uint64_t y[2];
932    memcpy(y, Ptr, 10);
933    Result.IntVal = APInt(80, y);
934    break;
935  }
936  default:
937    SmallString<256> Msg;
938    raw_svector_ostream OS(Msg);
939    OS << "Cannot load value of type " << *Ty << "!";
940    report_fatal_error(OS.str());
941  }
942}
943
944void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
945  DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
946  DEBUG(Init->dump());
947  if (isa<UndefValue>(Init)) {
948    return;
949  } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
950    unsigned ElementSize =
951      getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
952    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
953      InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
954    return;
955  } else if (isa<ConstantAggregateZero>(Init)) {
956    memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
957    return;
958  } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
959    unsigned ElementSize =
960      getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
961    for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
962      InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
963    return;
964  } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
965    const StructLayout *SL =
966      getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
967    for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
968      InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
969    return;
970  } else if (Init->getType()->isFirstClassType()) {
971    GenericValue Val = getConstantValue(Init);
972    StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
973    return;
974  }
975
976  DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
977  llvm_unreachable("Unknown constant type to initialize memory with!");
978}
979
980/// EmitGlobals - Emit all of the global variables to memory, storing their
981/// addresses into GlobalAddress.  This must make sure to copy the contents of
982/// their initializers into the memory.
983void ExecutionEngine::emitGlobals() {
984  // Loop over all of the global variables in the program, allocating the memory
985  // to hold them.  If there is more than one module, do a prepass over globals
986  // to figure out how the different modules should link together.
987  std::map<std::pair<std::string, Type*>,
988           const GlobalValue*> LinkedGlobalsMap;
989
990  if (Modules.size() != 1) {
991    for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
992      Module &M = *Modules[m];
993      for (Module::const_global_iterator I = M.global_begin(),
994           E = M.global_end(); I != E; ++I) {
995        const GlobalValue *GV = I;
996        if (GV->hasLocalLinkage() || GV->isDeclaration() ||
997            GV->hasAppendingLinkage() || !GV->hasName())
998          continue;// Ignore external globals and globals with internal linkage.
999
1000        const GlobalValue *&GVEntry =
1001          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1002
1003        // If this is the first time we've seen this global, it is the canonical
1004        // version.
1005        if (!GVEntry) {
1006          GVEntry = GV;
1007          continue;
1008        }
1009
1010        // If the existing global is strong, never replace it.
1011        if (GVEntry->hasExternalLinkage() ||
1012            GVEntry->hasDLLImportLinkage() ||
1013            GVEntry->hasDLLExportLinkage())
1014          continue;
1015
1016        // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1017        // symbol.  FIXME is this right for common?
1018        if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1019          GVEntry = GV;
1020      }
1021    }
1022  }
1023
1024  std::vector<const GlobalValue*> NonCanonicalGlobals;
1025  for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1026    Module &M = *Modules[m];
1027    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1028         I != E; ++I) {
1029      // In the multi-module case, see what this global maps to.
1030      if (!LinkedGlobalsMap.empty()) {
1031        if (const GlobalValue *GVEntry =
1032              LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1033          // If something else is the canonical global, ignore this one.
1034          if (GVEntry != &*I) {
1035            NonCanonicalGlobals.push_back(I);
1036            continue;
1037          }
1038        }
1039      }
1040
1041      if (!I->isDeclaration()) {
1042        addGlobalMapping(I, getMemoryForGV(I));
1043      } else {
1044        // External variable reference. Try to use the dynamic loader to
1045        // get a pointer to it.
1046        if (void *SymAddr =
1047            sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1048          addGlobalMapping(I, SymAddr);
1049        else {
1050          report_fatal_error("Could not resolve external global address: "
1051                            +I->getName());
1052        }
1053      }
1054    }
1055
1056    // If there are multiple modules, map the non-canonical globals to their
1057    // canonical location.
1058    if (!NonCanonicalGlobals.empty()) {
1059      for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1060        const GlobalValue *GV = NonCanonicalGlobals[i];
1061        const GlobalValue *CGV =
1062          LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1063        void *Ptr = getPointerToGlobalIfAvailable(CGV);
1064        assert(Ptr && "Canonical global wasn't codegen'd!");
1065        addGlobalMapping(GV, Ptr);
1066      }
1067    }
1068
1069    // Now that all of the globals are set up in memory, loop through them all
1070    // and initialize their contents.
1071    for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1072         I != E; ++I) {
1073      if (!I->isDeclaration()) {
1074        if (!LinkedGlobalsMap.empty()) {
1075          if (const GlobalValue *GVEntry =
1076                LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1077            if (GVEntry != &*I)  // Not the canonical variable.
1078              continue;
1079        }
1080        EmitGlobalVariable(I);
1081      }
1082    }
1083  }
1084}
1085
1086// EmitGlobalVariable - This method emits the specified global variable to the
1087// address specified in GlobalAddresses, or allocates new memory if it's not
1088// already in the map.
1089void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1090  void *GA = getPointerToGlobalIfAvailable(GV);
1091
1092  if (GA == 0) {
1093    // If it's not already specified, allocate memory for the global.
1094    GA = getMemoryForGV(GV);
1095    addGlobalMapping(GV, GA);
1096  }
1097
1098  // Don't initialize if it's thread local, let the client do it.
1099  if (!GV->isThreadLocal())
1100    InitializeMemory(GV->getInitializer(), GA);
1101
1102  Type *ElTy = GV->getType()->getElementType();
1103  size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1104  NumInitBytes += (unsigned)GVSize;
1105  ++NumGlobals;
1106}
1107
1108ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1109  : EE(EE), GlobalAddressMap(this) {
1110}
1111
1112sys::Mutex *
1113ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1114  return &EES->EE.lock;
1115}
1116
1117void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1118                                                      const GlobalValue *Old) {
1119  void *OldVal = EES->GlobalAddressMap.lookup(Old);
1120  EES->GlobalAddressReverseMap.erase(OldVal);
1121}
1122
1123void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1124                                                    const GlobalValue *,
1125                                                    const GlobalValue *) {
1126  assert(false && "The ExecutionEngine doesn't know how to handle a"
1127         " RAUW on a value it has a global mapping for.");
1128}
1129