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