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