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