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