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