1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2996fe010SChris Lattner //
3482202a6SJohn Criswell //                     The LLVM Compiler Infrastructure
4482202a6SJohn Criswell //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7482202a6SJohn Criswell //
8482202a6SJohn Criswell //===----------------------------------------------------------------------===//
9482202a6SJohn Criswell //
10996fe010SChris Lattner // This file defines the common interface used by the various execution engine
11996fe010SChris Lattner // subclasses.
12996fe010SChris Lattner //
13996fe010SChris Lattner //===----------------------------------------------------------------------===//
14996fe010SChris Lattner 
15ee937c80SChris Lattner #define DEBUG_TYPE "jit"
16996fe010SChris Lattner #include "llvm/Constants.h"
17260b0c88SMisha Brukman #include "llvm/DerivedTypes.h"
18996fe010SChris Lattner #include "llvm/Module.h"
19260b0c88SMisha Brukman #include "llvm/ModuleProvider.h"
2070e37278SReid Spencer #include "llvm/ADT/Statistic.h"
211202d1b1SDuncan Sands #include "llvm/Config/alloca.h"
22260b0c88SMisha Brukman #include "llvm/ExecutionEngine/ExecutionEngine.h"
23ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h"
247c16caa3SReid Spencer #include "llvm/Support/Debug.h"
256d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
2670e37278SReid Spencer #include "llvm/System/DynamicLibrary.h"
27fde55674SDuncan Sands #include "llvm/System/Host.h"
2870e37278SReid Spencer #include "llvm/Target/TargetData.h"
29579f0713SAnton Korobeynikov #include <cmath>
30579f0713SAnton Korobeynikov #include <cstring>
3129681deeSChris Lattner using namespace llvm;
32996fe010SChris Lattner 
33c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
35996fe010SChris Lattner 
362d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
372d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
3821ad494fSNicolas Geoffray ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
3921ad494fSNicolas Geoffray 
402d52c1b8SChris Lattner 
41fd6f3257SChris Lattner ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
4287aee74cSChris Lattner   LazyCompilationDisabled = false;
430621caefSChris Lattner   Modules.push_back(P);
44260b0c88SMisha Brukman   assert(P && "ModuleProvider is null?");
45260b0c88SMisha Brukman }
46260b0c88SMisha Brukman 
4792f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
48603682adSReid Spencer   clearAllGlobalMappings();
490621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
500621caefSChris Lattner     delete Modules[i];
5192f8b30dSBrian Gaeke }
5292f8b30dSBrian Gaeke 
53324fe890SDevang Patel /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54324fe890SDevang Patel /// Release module from ModuleProvider.
55324fe890SDevang Patel Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
56324fe890SDevang Patel                                               std::string *ErrInfo) {
57324fe890SDevang Patel   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
58324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
59324fe890SDevang Patel     ModuleProvider *MP = *I;
60324fe890SDevang Patel     if (MP == P) {
61324fe890SDevang Patel       Modules.erase(I);
62324fe890SDevang Patel       return MP->releaseModule(ErrInfo);
63324fe890SDevang Patel     }
64324fe890SDevang Patel   }
65324fe890SDevang Patel   return NULL;
66324fe890SDevang Patel }
67324fe890SDevang Patel 
680621caefSChris Lattner /// FindFunctionNamed - Search all of the active modules to find the one that
690621caefSChris Lattner /// defines FnName.  This is very slow operation and shouldn't be used for
700621caefSChris Lattner /// general code.
710621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
720621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
731241d6d5SReid Spencer     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
740621caefSChris Lattner       return F;
750621caefSChris Lattner   }
760621caefSChris Lattner   return 0;
770621caefSChris Lattner }
780621caefSChris Lattner 
790621caefSChris Lattner 
806d8dd189SChris Lattner /// addGlobalMapping - Tell the execution engine that the specified global is
816d8dd189SChris Lattner /// at the specified location.  This is used internally as functions are JIT'd
826d8dd189SChris Lattner /// and as global variables are laid out in memory.  It can and should also be
836d8dd189SChris Lattner /// used by clients of the EE that want to have an LLVM global overlay
846d8dd189SChris Lattner /// existing data in memory.
856d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
866d8dd189SChris Lattner   MutexGuard locked(lock);
876d8dd189SChris Lattner 
886d8dd189SChris Lattner   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
896d8dd189SChris Lattner   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
906d8dd189SChris Lattner   CurVal = Addr;
916d8dd189SChris Lattner 
926d8dd189SChris Lattner   // If we are using the reverse mapping, add it too
936d8dd189SChris Lattner   if (!state.getGlobalAddressReverseMap(locked).empty()) {
946d8dd189SChris Lattner     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
956d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
966d8dd189SChris Lattner     V = GV;
976d8dd189SChris Lattner   }
986d8dd189SChris Lattner }
996d8dd189SChris Lattner 
1006d8dd189SChris Lattner /// clearAllGlobalMappings - Clear all global mappings and start over again
1016d8dd189SChris Lattner /// use in dynamic compilation scenarios when you want to move globals
1026d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1036d8dd189SChris Lattner   MutexGuard locked(lock);
1046d8dd189SChris Lattner 
1056d8dd189SChris Lattner   state.getGlobalAddressMap(locked).clear();
1066d8dd189SChris Lattner   state.getGlobalAddressReverseMap(locked).clear();
1076d8dd189SChris Lattner }
1086d8dd189SChris Lattner 
1096d8dd189SChris Lattner /// updateGlobalMapping - Replace an existing mapping for GV with a new
1106d8dd189SChris Lattner /// address.  This updates both maps as required.  If "Addr" is null, the
1116d8dd189SChris Lattner /// entry for the global is removed from the mappings.
1126d8dd189SChris Lattner void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1136d8dd189SChris Lattner   MutexGuard locked(lock);
1146d8dd189SChris Lattner 
1156d8dd189SChris Lattner   // Deleting from the mapping?
1166d8dd189SChris Lattner   if (Addr == 0) {
1176d8dd189SChris Lattner     state.getGlobalAddressMap(locked).erase(GV);
1186d8dd189SChris Lattner     if (!state.getGlobalAddressReverseMap(locked).empty())
1196d8dd189SChris Lattner       state.getGlobalAddressReverseMap(locked).erase(Addr);
1206d8dd189SChris Lattner     return;
1216d8dd189SChris Lattner   }
1226d8dd189SChris Lattner 
1236d8dd189SChris Lattner   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
1246d8dd189SChris Lattner   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
1256d8dd189SChris Lattner     state.getGlobalAddressReverseMap(locked).erase(CurVal);
1266d8dd189SChris Lattner   CurVal = Addr;
1276d8dd189SChris Lattner 
1286d8dd189SChris Lattner   // If we are using the reverse mapping, add it too
1296d8dd189SChris Lattner   if (!state.getGlobalAddressReverseMap(locked).empty()) {
1306d8dd189SChris Lattner     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
1316d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1326d8dd189SChris Lattner     V = GV;
1336d8dd189SChris Lattner   }
1346d8dd189SChris Lattner }
1356d8dd189SChris Lattner 
1366d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified
1376d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null.
1386d8dd189SChris Lattner ///
1396d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
1406d8dd189SChris Lattner   MutexGuard locked(lock);
1416d8dd189SChris Lattner 
1426d8dd189SChris Lattner   std::map<const GlobalValue*, void*>::iterator I =
1436d8dd189SChris Lattner   state.getGlobalAddressMap(locked).find(GV);
1446d8dd189SChris Lattner   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
1456d8dd189SChris Lattner }
1466d8dd189SChris Lattner 
147748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts
148748e8579SChris Lattner /// at the specified address.
149748e8579SChris Lattner ///
150748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
15179876f52SReid Spencer   MutexGuard locked(lock);
15279876f52SReid Spencer 
153748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
15479876f52SReid Spencer   if (state.getGlobalAddressReverseMap(locked).empty()) {
1556d8dd189SChris Lattner     for (std::map<const GlobalValue*, void *>::iterator
1566d8dd189SChris Lattner          I = state.getGlobalAddressMap(locked).begin(),
1576d8dd189SChris Lattner          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
1586d8dd189SChris Lattner       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
1596d8dd189SChris Lattner                                                                      I->first));
160748e8579SChris Lattner   }
161748e8579SChris Lattner 
162748e8579SChris Lattner   std::map<void *, const GlobalValue*>::iterator I =
16379876f52SReid Spencer     state.getGlobalAddressReverseMap(locked).find(Addr);
16479876f52SReid Spencer   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
165748e8579SChris Lattner }
1665a0d4829SChris Lattner 
1675a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of
1685a0d4829SChris Lattner // pointers to null terminated strings.
1695a0d4829SChris Lattner //
1705a0d4829SChris Lattner static void *CreateArgv(ExecutionEngine *EE,
1715a0d4829SChris Lattner                         const std::vector<std::string> &InputArgv) {
17220a631fdSOwen Anderson   unsigned PtrSize = EE->getTargetData()->getPointerSize();
1735a0d4829SChris Lattner   char *Result = new char[(InputArgv.size()+1)*PtrSize];
1745a0d4829SChris Lattner 
1755834fdb3SBill Wendling   DOUT << "ARGV = " << (void*)Result << "\n";
176edf07887SChristopher Lamb   const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
1775a0d4829SChris Lattner 
1785a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
1795a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
1805a0d4829SChris Lattner     char *Dest = new char[Size];
1815834fdb3SBill Wendling     DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
1825a0d4829SChris Lattner 
1835a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
1845a0d4829SChris Lattner     Dest[Size-1] = 0;
1855a0d4829SChris Lattner 
1865a0d4829SChris Lattner     // Endian safe: Result[i] = (PointerTy)Dest;
1875a0d4829SChris Lattner     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
1885a0d4829SChris Lattner                            SBytePtr);
1895a0d4829SChris Lattner   }
1905a0d4829SChris Lattner 
1915a0d4829SChris Lattner   // Null terminate it
1925a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
1935a0d4829SChris Lattner                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
1945a0d4829SChris Lattner                          SBytePtr);
1955a0d4829SChris Lattner   return Result;
1965a0d4829SChris Lattner }
1975a0d4829SChris Lattner 
198faae50b6SChris Lattner 
199faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of
2000621caefSChris Lattner /// the static constructors or destructors for a program, depending on the
201faae50b6SChris Lattner /// value of isDtors.
202faae50b6SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
203faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
2040621caefSChris Lattner 
2050621caefSChris Lattner   // Execute global ctors/dtors for each module in the program.
2060621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
2070621caefSChris Lattner     GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
208fe36eaebSChris Lattner 
209fe36eaebSChris Lattner     // If this global has internal linkage, or if it has a use, then it must be
210fe36eaebSChris Lattner     // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
2110621caefSChris Lattner     // this is the case, don't execute any of the global ctors, __main will do
2120621caefSChris Lattner     // it.
2135301e7c6SReid Spencer     if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
214faae50b6SChris Lattner 
2150621caefSChris Lattner     // Should be an array of '{ int, void ()* }' structs.  The first value is
2160621caefSChris Lattner     // the init priority, which we ignore.
217faae50b6SChris Lattner     ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
2180621caefSChris Lattner     if (!InitList) continue;
219faae50b6SChris Lattner     for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
2200621caefSChris Lattner       if (ConstantStruct *CS =
2210621caefSChris Lattner           dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
2220621caefSChris Lattner         if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
223faae50b6SChris Lattner 
224faae50b6SChris Lattner         Constant *FP = CS->getOperand(1);
225faae50b6SChris Lattner         if (FP->isNullValue())
2260621caefSChris Lattner           break;  // Found a null terminator, exit.
227faae50b6SChris Lattner 
228faae50b6SChris Lattner         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
2296c38f0bbSReid Spencer           if (CE->isCast())
230faae50b6SChris Lattner             FP = CE->getOperand(0);
231faae50b6SChris Lattner         if (Function *F = dyn_cast<Function>(FP)) {
232faae50b6SChris Lattner           // Execute the ctor/dtor function!
233faae50b6SChris Lattner           runFunction(F, std::vector<GenericValue>());
234faae50b6SChris Lattner         }
235faae50b6SChris Lattner       }
236faae50b6SChris Lattner   }
2370621caefSChris Lattner }
238faae50b6SChris Lattner 
2391202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
2401202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
2411202d1b1SDuncan Sands   unsigned PtrSize = EE->getTargetData()->getPointerSize();
2421202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
2431202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
2441202d1b1SDuncan Sands       return false;
2451202d1b1SDuncan Sands   return true;
2461202d1b1SDuncan Sands }
2471202d1b1SDuncan Sands 
2485a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to
2495a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv,
2505a0d4829SChris Lattner /// and envp parameters.
2515a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
2525a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
2535a0d4829SChris Lattner                                        const char * const * envp) {
2545a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
2555a0d4829SChris Lattner   GenericValue GVArgc;
25687aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
2578c32c111SAnton Korobeynikov 
2588c32c111SAnton Korobeynikov   // Check main() type
259b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
2608c32c111SAnton Korobeynikov   const FunctionType *FTy = Fn->getFunctionType();
261edf07887SChristopher Lamb   const Type* PPInt8Ty =
262edf07887SChristopher Lamb     PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
2638c32c111SAnton Korobeynikov   switch (NumArgs) {
2648c32c111SAnton Korobeynikov   case 3:
2658c32c111SAnton Korobeynikov    if (FTy->getParamType(2) != PPInt8Ty) {
2668c32c111SAnton Korobeynikov      cerr << "Invalid type for third argument of main() supplied\n";
2678c32c111SAnton Korobeynikov      abort();
2688c32c111SAnton Korobeynikov    }
269b781886dSAnton Korobeynikov    // FALLS THROUGH
2708c32c111SAnton Korobeynikov   case 2:
2718c32c111SAnton Korobeynikov    if (FTy->getParamType(1) != PPInt8Ty) {
2728c32c111SAnton Korobeynikov      cerr << "Invalid type for second argument of main() supplied\n";
2738c32c111SAnton Korobeynikov      abort();
2748c32c111SAnton Korobeynikov    }
275b781886dSAnton Korobeynikov    // FALLS THROUGH
2768c32c111SAnton Korobeynikov   case 1:
2778c32c111SAnton Korobeynikov    if (FTy->getParamType(0) != Type::Int32Ty) {
2788c32c111SAnton Korobeynikov      cerr << "Invalid type for first argument of main() supplied\n";
2798c32c111SAnton Korobeynikov      abort();
2808c32c111SAnton Korobeynikov    }
281b781886dSAnton Korobeynikov    // FALLS THROUGH
2828c32c111SAnton Korobeynikov   case 0:
2838c32c111SAnton Korobeynikov    if (FTy->getReturnType() != Type::Int32Ty &&
2848c32c111SAnton Korobeynikov        FTy->getReturnType() != Type::VoidTy) {
2858c32c111SAnton Korobeynikov      cerr << "Invalid return type of main() supplied\n";
2868c32c111SAnton Korobeynikov      abort();
2878c32c111SAnton Korobeynikov    }
2888c32c111SAnton Korobeynikov    break;
2898c32c111SAnton Korobeynikov   default:
2908c32c111SAnton Korobeynikov    cerr << "Invalid number of arguments of main() supplied\n";
2918c32c111SAnton Korobeynikov    abort();
2928c32c111SAnton Korobeynikov   }
2938c32c111SAnton Korobeynikov 
294b1cad0b3SChris Lattner   if (NumArgs) {
2955a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
296b1cad0b3SChris Lattner     if (NumArgs > 1) {
2975a0d4829SChris Lattner       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
2981202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
299b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
300b1cad0b3SChris Lattner       if (NumArgs > 2) {
3015a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3025a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3035a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
3045a0d4829SChris Lattner         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
305b1cad0b3SChris Lattner       }
306b1cad0b3SChris Lattner     }
307b1cad0b3SChris Lattner   }
30887aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
3095a0d4829SChris Lattner }
3105a0d4829SChris Lattner 
311260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an
312260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created,
313260b0c88SMisha Brukman /// NULL is returned.
314857c21b4SMisha Brukman ///
3152f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
316603682adSReid Spencer                                          bool ForceInterpreter,
317603682adSReid Spencer                                          std::string *ErrorStr) {
3184bd3bd5bSBrian Gaeke   ExecutionEngine *EE = 0;
3194bd3bd5bSBrian Gaeke 
320c8c6c03dSChris Lattner   // Unless the interpreter was explicitly selected, try making a JIT.
3212d52c1b8SChris Lattner   if (!ForceInterpreter && JITCtor)
322603682adSReid Spencer     EE = JITCtor(MP, ErrorStr);
3234bd3bd5bSBrian Gaeke 
3244bd3bd5bSBrian Gaeke   // If we can't make a JIT, make an interpreter instead.
3252d52c1b8SChris Lattner   if (EE == 0 && InterpCtor)
326603682adSReid Spencer     EE = InterpCtor(MP, ErrorStr);
327c8c6c03dSChris Lattner 
3280b2de9f2SChris Lattner   if (EE) {
32970e37278SReid Spencer     // Make sure we can resolve symbols in the program as well. The zero arg
33070e37278SReid Spencer     // to the function tells DynamicLibrary to load the program, not a library.
331edaf0b46SChris Lattner     if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
332edaf0b46SChris Lattner       delete EE;
333edaf0b46SChris Lattner       return 0;
33463539389SChris Lattner     }
3350b2de9f2SChris Lattner   }
33670e37278SReid Spencer 
3374bd3bd5bSBrian Gaeke   return EE;
3384bd3bd5bSBrian Gaeke }
3394bd3bd5bSBrian Gaeke 
340b5163bb9SChris Lattner ExecutionEngine *ExecutionEngine::create(Module *M) {
341b5163bb9SChris Lattner   return create(new ExistingModuleProvider(M));
342b5163bb9SChris Lattner }
343b5163bb9SChris Lattner 
344857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global
345857c21b4SMisha Brukman /// value.  This may involve code generation if it's a function.
346857c21b4SMisha Brukman ///
347996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
3481678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
349996fe010SChris Lattner     return getPointerToFunction(F);
350996fe010SChris Lattner 
35179876f52SReid Spencer   MutexGuard locked(lock);
35269e84901SJeff Cohen   void *p = state.getGlobalAddressMap(locked)[GV];
35369e84901SJeff Cohen   if (p)
35469e84901SJeff Cohen     return p;
35569e84901SJeff Cohen 
35669e84901SJeff Cohen   // Global variable might have been added since interpreter started.
35769e84901SJeff Cohen   if (GlobalVariable *GVar =
35869e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
35969e84901SJeff Cohen     EmitGlobalVariable(GVar);
36069e84901SJeff Cohen   else
3614da5e17cSChris Lattner     assert(0 && "Global hasn't had an address allocated yet!");
36279876f52SReid Spencer   return state.getGlobalAddressMap(locked)[GV];
363996fe010SChris Lattner }
364996fe010SChris Lattner 
3656c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting
3666c38f0bbSReid Spencer /// part is if C is a ConstantExpr.
3672dc9f132SReid Spencer /// @brief Get a GenericValue for a Constant*
368996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
3696c38f0bbSReid Spencer   // If its undefined, return the garbage.
3704fd528f2SReid Spencer   if (isa<UndefValue>(C))
3714fd528f2SReid Spencer     return GenericValue();
3729de0d14dSChris Lattner 
3736c38f0bbSReid Spencer   // If the value is a ConstantExpr
3746c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3754fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
3769de0d14dSChris Lattner     switch (CE->getOpcode()) {
3779de0d14dSChris Lattner     case Instruction::GetElementPtr: {
3786c38f0bbSReid Spencer       // Compute the index
3794fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
380c44bd78aSChris Lattner       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
3819de0d14dSChris Lattner       uint64_t Offset =
3824fd528f2SReid Spencer         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
3839de0d14dSChris Lattner 
38487aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
38587aa65f4SReid Spencer       Result = PTOGV(tmp + Offset);
3869de0d14dSChris Lattner       return Result;
3879de0d14dSChris Lattner     }
3884fd528f2SReid Spencer     case Instruction::Trunc: {
3894fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
3904fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
3914fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
3924fd528f2SReid Spencer       return GV;
3934fd528f2SReid Spencer     }
3944fd528f2SReid Spencer     case Instruction::ZExt: {
3954fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
3964fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
3974fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
3984fd528f2SReid Spencer       return GV;
3994fd528f2SReid Spencer     }
4004fd528f2SReid Spencer     case Instruction::SExt: {
4014fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4024fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4034fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
4044fd528f2SReid Spencer       return GV;
4054fd528f2SReid Spencer     }
4064fd528f2SReid Spencer     case Instruction::FPTrunc: {
407a1336cf5SDale Johannesen       // FIXME long double
4084fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4094fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
4104fd528f2SReid Spencer       return GV;
4114fd528f2SReid Spencer     }
4124fd528f2SReid Spencer     case Instruction::FPExt:{
413a1336cf5SDale Johannesen       // FIXME long double
4144fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4154fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
4164fd528f2SReid Spencer       return GV;
4174fd528f2SReid Spencer     }
4184fd528f2SReid Spencer     case Instruction::UIToFP: {
4194fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4204fd528f2SReid Spencer       if (CE->getType() == Type::FloatTy)
4214fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
422a1336cf5SDale Johannesen       else if (CE->getType() == Type::DoubleTy)
4234fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
424a1336cf5SDale Johannesen       else if (CE->getType() == Type::X86_FP80Ty) {
425a1336cf5SDale Johannesen         const uint64_t zero[] = {0, 0};
426a1336cf5SDale Johannesen         APFloat apf = APFloat(APInt(80, 2, zero));
427*ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
428*ca24fd90SDan Gohman                                    false,
4299150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
430a1336cf5SDale Johannesen         GV.IntVal = apf.convertToAPInt();
431a1336cf5SDale Johannesen       }
4324fd528f2SReid Spencer       return GV;
4334fd528f2SReid Spencer     }
4344fd528f2SReid Spencer     case Instruction::SIToFP: {
4354fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4364fd528f2SReid Spencer       if (CE->getType() == Type::FloatTy)
4374fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
438a1336cf5SDale Johannesen       else if (CE->getType() == Type::DoubleTy)
4394fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
440a1336cf5SDale Johannesen       else if (CE->getType() == Type::X86_FP80Ty) {
441a1336cf5SDale Johannesen         const uint64_t zero[] = { 0, 0};
442a1336cf5SDale Johannesen         APFloat apf = APFloat(APInt(80, 2, zero));
443*ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
444*ca24fd90SDan Gohman                                    true,
4459150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
446a1336cf5SDale Johannesen         GV.IntVal = apf.convertToAPInt();
447a1336cf5SDale Johannesen       }
4484fd528f2SReid Spencer       return GV;
4494fd528f2SReid Spencer     }
4504fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
4514fd528f2SReid Spencer     case Instruction::FPToSI: {
4524fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4534fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4544fd528f2SReid Spencer       if (Op0->getType() == Type::FloatTy)
4554fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
456a1336cf5SDale Johannesen       else if (Op0->getType() == Type::DoubleTy)
4574fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
458a1336cf5SDale Johannesen       else if (Op0->getType() == Type::X86_FP80Ty) {
459a1336cf5SDale Johannesen         APFloat apf = APFloat(GV.IntVal);
460a1336cf5SDale Johannesen         uint64_t v;
461a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
462a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
463a1336cf5SDale Johannesen                                    APFloat::rmTowardZero);
464a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
465a1336cf5SDale Johannesen       }
4664fd528f2SReid Spencer       return GV;
4674fd528f2SReid Spencer     }
4686c38f0bbSReid Spencer     case Instruction::PtrToInt: {
4694fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4704fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
4714fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
4724fd528f2SReid Spencer       return GV;
4734fd528f2SReid Spencer     }
4744fd528f2SReid Spencer     case Instruction::IntToPtr: {
4754fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4764fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
4774fd528f2SReid Spencer       if (PtrWidth != GV.IntVal.getBitWidth())
4784fd528f2SReid Spencer         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
4794fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
4804fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
4816c38f0bbSReid Spencer       return GV;
4826c38f0bbSReid Spencer     }
4836c38f0bbSReid Spencer     case Instruction::BitCast: {
4844fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4854fd528f2SReid Spencer       const Type* DestTy = CE->getType();
4864fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
4874fd528f2SReid Spencer         default: assert(0 && "Invalid bitcast operand");
4884fd528f2SReid Spencer         case Type::IntegerTyID:
4894fd528f2SReid Spencer           assert(DestTy->isFloatingPoint() && "invalid bitcast");
4904fd528f2SReid Spencer           if (DestTy == Type::FloatTy)
4914fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
4924fd528f2SReid Spencer           else if (DestTy == Type::DoubleTy)
4934fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
4946c38f0bbSReid Spencer           break;
4954fd528f2SReid Spencer         case Type::FloatTyID:
4964fd528f2SReid Spencer           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
4974fd528f2SReid Spencer           GV.IntVal.floatToBits(GV.FloatVal);
4984fd528f2SReid Spencer           break;
4994fd528f2SReid Spencer         case Type::DoubleTyID:
5004fd528f2SReid Spencer           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
5014fd528f2SReid Spencer           GV.IntVal.doubleToBits(GV.DoubleVal);
5024fd528f2SReid Spencer           break;
5034fd528f2SReid Spencer         case Type::PointerTyID:
5044fd528f2SReid Spencer           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
5054fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
5066c38f0bbSReid Spencer       }
5074fd528f2SReid Spencer       return GV;
50868cbcc3eSChris Lattner     }
50968cbcc3eSChris Lattner     case Instruction::Add:
5104fd528f2SReid Spencer     case Instruction::Sub:
5114fd528f2SReid Spencer     case Instruction::Mul:
5124fd528f2SReid Spencer     case Instruction::UDiv:
5134fd528f2SReid Spencer     case Instruction::SDiv:
5144fd528f2SReid Spencer     case Instruction::URem:
5154fd528f2SReid Spencer     case Instruction::SRem:
5164fd528f2SReid Spencer     case Instruction::And:
5174fd528f2SReid Spencer     case Instruction::Or:
5184fd528f2SReid Spencer     case Instruction::Xor: {
5194fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
5204fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
5214fd528f2SReid Spencer       GenericValue GV;
522c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
523c4e6bb5fSChris Lattner       default: assert(0 && "Bad add type!"); abort();
5247a9c62baSReid Spencer       case Type::IntegerTyID:
5254fd528f2SReid Spencer         switch (CE->getOpcode()) {
5264fd528f2SReid Spencer           default: assert(0 && "Invalid integer opcode");
5274fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
5284fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
5294fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
5304fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
5314fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
5324fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
5334fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
5344fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
5354fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
5364fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
5374fd528f2SReid Spencer         }
538c4e6bb5fSChris Lattner         break;
539c4e6bb5fSChris Lattner       case Type::FloatTyID:
5404fd528f2SReid Spencer         switch (CE->getOpcode()) {
5414fd528f2SReid Spencer           default: assert(0 && "Invalid float opcode"); abort();
5424fd528f2SReid Spencer           case Instruction::Add:
5434fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
5444fd528f2SReid Spencer           case Instruction::Sub:
5454fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
5464fd528f2SReid Spencer           case Instruction::Mul:
5474fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
5484fd528f2SReid Spencer           case Instruction::FDiv:
5494fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
5504fd528f2SReid Spencer           case Instruction::FRem:
5514fd528f2SReid Spencer             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
5524fd528f2SReid Spencer         }
553c4e6bb5fSChris Lattner         break;
554c4e6bb5fSChris Lattner       case Type::DoubleTyID:
5554fd528f2SReid Spencer         switch (CE->getOpcode()) {
5564fd528f2SReid Spencer           default: assert(0 && "Invalid double opcode"); abort();
5574fd528f2SReid Spencer           case Instruction::Add:
5584fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
5594fd528f2SReid Spencer           case Instruction::Sub:
5604fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
5614fd528f2SReid Spencer           case Instruction::Mul:
5624fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
5634fd528f2SReid Spencer           case Instruction::FDiv:
5644fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
5654fd528f2SReid Spencer           case Instruction::FRem:
5664fd528f2SReid Spencer             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
5674fd528f2SReid Spencer         }
568c4e6bb5fSChris Lattner         break;
569a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
570a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
571a1336cf5SDale Johannesen       case Type::FP128TyID: {
572a1336cf5SDale Johannesen         APFloat apfLHS = APFloat(LHS.IntVal);
573a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
574a1336cf5SDale Johannesen           default: assert(0 && "Invalid long double opcode"); abort();
575a1336cf5SDale Johannesen           case Instruction::Add:
576a1336cf5SDale Johannesen             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
577a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
578a1336cf5SDale Johannesen             break;
579a1336cf5SDale Johannesen           case Instruction::Sub:
580a1336cf5SDale Johannesen             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
581a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
582a1336cf5SDale Johannesen             break;
583a1336cf5SDale Johannesen           case Instruction::Mul:
584a1336cf5SDale Johannesen             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
585a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
586a1336cf5SDale Johannesen             break;
587a1336cf5SDale Johannesen           case Instruction::FDiv:
588a1336cf5SDale Johannesen             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
589a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
590a1336cf5SDale Johannesen             break;
591a1336cf5SDale Johannesen           case Instruction::FRem:
592a1336cf5SDale Johannesen             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
593a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
594a1336cf5SDale Johannesen             break;
595a1336cf5SDale Johannesen           }
596a1336cf5SDale Johannesen         }
597a1336cf5SDale Johannesen         break;
598c4e6bb5fSChris Lattner       }
5994fd528f2SReid Spencer       return GV;
6004fd528f2SReid Spencer     }
6019de0d14dSChris Lattner     default:
60268cbcc3eSChris Lattner       break;
60368cbcc3eSChris Lattner     }
6044fd528f2SReid Spencer     cerr << "ConstantExpr not handled: " << *CE << "\n";
6059de0d14dSChris Lattner     abort();
6069de0d14dSChris Lattner   }
607996fe010SChris Lattner 
6084fd528f2SReid Spencer   GenericValue Result;
6096b727599SChris Lattner   switch (C->getType()->getTypeID()) {
61087aa65f4SReid Spencer   case Type::FloatTyID:
611bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
6127a9c62baSReid Spencer     break;
61387aa65f4SReid Spencer   case Type::DoubleTyID:
614bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
61587aa65f4SReid Spencer     break;
616a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
617a1336cf5SDale Johannesen   case Type::FP128TyID:
618a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
619a1336cf5SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
620a1336cf5SDale Johannesen     break;
62187aa65f4SReid Spencer   case Type::IntegerTyID:
62287aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
62387aa65f4SReid Spencer     break;
624996fe010SChris Lattner   case Type::PointerTyID:
6256a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
626996fe010SChris Lattner       Result.PointerVal = 0;
6276a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
6286a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
6296a0fd73bSReid Spencer     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
6306a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
631e6492f10SChris Lattner     else
632996fe010SChris Lattner       assert(0 && "Unknown constant pointer type!");
633996fe010SChris Lattner     break;
634996fe010SChris Lattner   default:
6354fd528f2SReid Spencer     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
6369de0d14dSChris Lattner     abort();
637996fe010SChris Lattner   }
638996fe010SChris Lattner   return Result;
639996fe010SChris Lattner }
640996fe010SChris Lattner 
6411202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
6421202d1b1SDuncan Sands /// with the integer held in IntVal.
6431202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
6441202d1b1SDuncan Sands                              unsigned StoreBytes) {
6451202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
6461202d1b1SDuncan Sands   uint8_t *Src = (uint8_t *)IntVal.getRawData();
6475c65cb46SDuncan Sands 
648fde55674SDuncan Sands   if (sys::littleEndianHost())
6491202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
6501202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
6515c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
6525c65cb46SDuncan Sands   else {
6535c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
6541202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
6551202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
6565c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
6575c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
6585c65cb46SDuncan Sands       // May not be aligned so use memcpy.
6595c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
6605c65cb46SDuncan Sands       Src += sizeof(uint64_t);
6615c65cb46SDuncan Sands     }
6625c65cb46SDuncan Sands 
6635c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
664815f8dd2SReid Spencer   }
6657a9c62baSReid Spencer }
6661202d1b1SDuncan Sands 
6671202d1b1SDuncan Sands /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
6681202d1b1SDuncan Sands /// is the address of the memory at which to store Val, cast to GenericValue *.
6691202d1b1SDuncan Sands /// It is not a pointer to a GenericValue containing the address at which to
6701202d1b1SDuncan Sands /// store Val.
6711202d1b1SDuncan Sands void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
6721202d1b1SDuncan Sands                                          const Type *Ty) {
6731202d1b1SDuncan Sands   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
6741202d1b1SDuncan Sands 
6751202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
6761202d1b1SDuncan Sands   case Type::IntegerTyID:
6771202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
6781202d1b1SDuncan Sands     break;
679996fe010SChris Lattner   case Type::FloatTyID:
68087aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
68187aa65f4SReid Spencer     break;
68287aa65f4SReid Spencer   case Type::DoubleTyID:
68387aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
684996fe010SChris Lattner     break;
685a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
686a1336cf5SDale Johannesen       uint16_t *Dest = (uint16_t*)Ptr;
687a1336cf5SDale Johannesen       const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
688a1336cf5SDale Johannesen       // This is endian dependent, but it will only work on x86 anyway.
689a1336cf5SDale Johannesen       Dest[0] = Src[4];
690a1336cf5SDale Johannesen       Dest[1] = Src[0];
691a1336cf5SDale Johannesen       Dest[2] = Src[1];
692a1336cf5SDale Johannesen       Dest[3] = Src[2];
693a1336cf5SDale Johannesen       Dest[4] = Src[3];
694a1336cf5SDale Johannesen       break;
695a1336cf5SDale Johannesen     }
6967a9c62baSReid Spencer   case Type::PointerTyID:
6971202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
6981202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
6991202d1b1SDuncan Sands       memset(Ptr, 0, StoreBytes);
7001202d1b1SDuncan Sands 
70187aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
702996fe010SChris Lattner     break;
703996fe010SChris Lattner   default:
704f3baad3eSBill Wendling     cerr << "Cannot store value of type " << *Ty << "!\n";
705996fe010SChris Lattner   }
7061202d1b1SDuncan Sands 
7071202d1b1SDuncan Sands   if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
7081202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
7091202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
710996fe010SChris Lattner }
711996fe010SChris Lattner 
7121202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
7131202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
7141202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
7151202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
7161202d1b1SDuncan Sands   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
7175c65cb46SDuncan Sands 
718fde55674SDuncan Sands   if (sys::littleEndianHost())
7195c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
7205c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
7215c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
7225c65cb46SDuncan Sands   else {
7235c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
7245c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
7255c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
7265c65cb46SDuncan Sands     // a word.
7275c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
7285c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
7295c65cb46SDuncan Sands       // May not be aligned so use memcpy.
7305c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
7315c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
7325c65cb46SDuncan Sands     }
7335c65cb46SDuncan Sands 
7345c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
7355c65cb46SDuncan Sands   }
7367a9c62baSReid Spencer }
7371202d1b1SDuncan Sands 
7381202d1b1SDuncan Sands /// FIXME: document
7391202d1b1SDuncan Sands ///
7401202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
7411202d1b1SDuncan Sands                                                   GenericValue *Ptr,
7421202d1b1SDuncan Sands                                                   const Type *Ty) {
7431202d1b1SDuncan Sands   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
7441202d1b1SDuncan Sands 
7451202d1b1SDuncan Sands   if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
7461202d1b1SDuncan Sands     // Host and target are different endian - reverse copy the stored
7471202d1b1SDuncan Sands     // bytes into a buffer, and load from that.
7481202d1b1SDuncan Sands     uint8_t *Src = (uint8_t*)Ptr;
7491202d1b1SDuncan Sands     uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
7501202d1b1SDuncan Sands     std::reverse_copy(Src, Src + LoadBytes, Buf);
7511202d1b1SDuncan Sands     Ptr = (GenericValue*)Buf;
7521202d1b1SDuncan Sands   }
7531202d1b1SDuncan Sands 
7541202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
7551202d1b1SDuncan Sands   case Type::IntegerTyID:
7561202d1b1SDuncan Sands     // An APInt with all words initially zero.
7571202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
7581202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
7591202d1b1SDuncan Sands     break;
7607f389e8cSChris Lattner   case Type::FloatTyID:
76187aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
76287aa65f4SReid Spencer     break;
76387aa65f4SReid Spencer   case Type::DoubleTyID:
76487aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
7657f389e8cSChris Lattner     break;
7667a9c62baSReid Spencer   case Type::PointerTyID:
76787aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
7687f389e8cSChris Lattner     break;
769a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
770a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
77126d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
772ff306287SDuncan Sands     uint16_t *p = (uint16_t*)Ptr;
773ff306287SDuncan Sands     union {
774ff306287SDuncan Sands       uint16_t x[8];
775ff306287SDuncan Sands       uint64_t y[2];
776ff306287SDuncan Sands     };
777a1336cf5SDale Johannesen     x[0] = p[1];
778a1336cf5SDale Johannesen     x[1] = p[2];
779a1336cf5SDale Johannesen     x[2] = p[3];
780a1336cf5SDale Johannesen     x[3] = p[4];
781a1336cf5SDale Johannesen     x[4] = p[0];
782ff306287SDuncan Sands     Result.IntVal = APInt(80, 2, y);
783a1336cf5SDale Johannesen     break;
784a1336cf5SDale Johannesen   }
7857f389e8cSChris Lattner   default:
786f3baad3eSBill Wendling     cerr << "Cannot load value of type " << *Ty << "!\n";
7877f389e8cSChris Lattner     abort();
7887f389e8cSChris Lattner   }
7897f389e8cSChris Lattner }
7907f389e8cSChris Lattner 
791996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the
792996fe010SChris Lattner // specified memory location...
793996fe010SChris Lattner //
794996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
79561753bf8SChris Lattner   if (isa<UndefValue>(Init)) {
79661753bf8SChris Lattner     return;
797d84d35baSReid Spencer   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
79869d62138SRobert Bocchino     unsigned ElementSize =
79944b8721dSDuncan Sands       getTargetData()->getABITypeSize(CP->getType()->getElementType());
80069d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
80169d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
80269d62138SRobert Bocchino     return;
8031dd86b11SChris Lattner   } else if (isa<ConstantAggregateZero>(Init)) {
8041dd86b11SChris Lattner     memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
8051dd86b11SChris Lattner     return;
80661753bf8SChris Lattner   } else if (Init->getType()->isFirstClassType()) {
807996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
808996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
809996fe010SChris Lattner     return;
810996fe010SChris Lattner   }
811996fe010SChris Lattner 
8126b727599SChris Lattner   switch (Init->getType()->getTypeID()) {
813996fe010SChris Lattner   case Type::ArrayTyID: {
814996fe010SChris Lattner     const ConstantArray *CPA = cast<ConstantArray>(Init);
815996fe010SChris Lattner     unsigned ElementSize =
81644b8721dSDuncan Sands       getTargetData()->getABITypeSize(CPA->getType()->getElementType());
81783243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
81883243725SAlkis Evlogimenos       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
819996fe010SChris Lattner     return;
820996fe010SChris Lattner   }
821996fe010SChris Lattner 
822996fe010SChris Lattner   case Type::StructTyID: {
823996fe010SChris Lattner     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
824996fe010SChris Lattner     const StructLayout *SL =
82520a631fdSOwen Anderson       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
82683243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
827c473d8e4SChris Lattner       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
828996fe010SChris Lattner     return;
829996fe010SChris Lattner   }
830996fe010SChris Lattner 
831996fe010SChris Lattner   default:
832f3baad3eSBill Wendling     cerr << "Bad Type: " << *Init->getType() << "\n";
833996fe010SChris Lattner     assert(0 && "Unknown constant type to initialize memory with!");
834996fe010SChris Lattner   }
835996fe010SChris Lattner }
836996fe010SChris Lattner 
837996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
838996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
839996fe010SChris Lattner /// their initializers into the memory.
840996fe010SChris Lattner ///
841996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
84220a631fdSOwen Anderson   const TargetData *TD = getTargetData();
843996fe010SChris Lattner 
844996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
8450621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
8460621caefSChris Lattner   // to figure out how the different modules should link together.
8470621caefSChris Lattner   //
8480621caefSChris Lattner   std::map<std::pair<std::string, const Type*>,
8490621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
8500621caefSChris Lattner 
8510621caefSChris Lattner   if (Modules.size() != 1) {
8520621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
8530621caefSChris Lattner       Module &M = *Modules[m]->getModule();
8540621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
8550621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
8560621caefSChris Lattner         const GlobalValue *GV = I;
8575301e7c6SReid Spencer         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
8580621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
8590621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
8600621caefSChris Lattner 
8610621caefSChris Lattner         const GlobalValue *&GVEntry =
8620621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
8630621caefSChris Lattner 
8640621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
8650621caefSChris Lattner         // version.
8660621caefSChris Lattner         if (!GVEntry) {
8670621caefSChris Lattner           GVEntry = GV;
8680621caefSChris Lattner           continue;
8690621caefSChris Lattner         }
8700621caefSChris Lattner 
8710621caefSChris Lattner         // If the existing global is strong, never replace it.
872d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
873d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
874d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
8750621caefSChris Lattner           continue;
8760621caefSChris Lattner 
8770621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
8780621caefSChris Lattner         // symbol.
87912c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
8800621caefSChris Lattner           GVEntry = GV;
8810621caefSChris Lattner       }
8820621caefSChris Lattner     }
8830621caefSChris Lattner   }
8840621caefSChris Lattner 
8850621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
8860621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
8870621caefSChris Lattner     Module &M = *Modules[m]->getModule();
8888ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
8890621caefSChris Lattner          I != E; ++I) {
8900621caefSChris Lattner       // In the multi-module case, see what this global maps to.
8910621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
8920621caefSChris Lattner         if (const GlobalValue *GVEntry =
8930621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
8940621caefSChris Lattner           // If something else is the canonical global, ignore this one.
8950621caefSChris Lattner           if (GVEntry != &*I) {
8960621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
8970621caefSChris Lattner             continue;
8980621caefSChris Lattner           }
8990621caefSChris Lattner         }
9000621caefSChris Lattner       }
9010621caefSChris Lattner 
9025301e7c6SReid Spencer       if (!I->isDeclaration()) {
9030621caefSChris Lattner         // Get the type of the global.
904996fe010SChris Lattner         const Type *Ty = I->getType()->getElementType();
905996fe010SChris Lattner 
906996fe010SChris Lattner         // Allocate some memory for it!
90744b8721dSDuncan Sands         unsigned Size = TD->getABITypeSize(Ty);
9086bbe3eceSChris Lattner         addGlobalMapping(I, new char[Size]);
909996fe010SChris Lattner       } else {
910e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
911e8bbcfc2SBrian Gaeke         // get a pointer to it.
9120621caefSChris Lattner         if (void *SymAddr =
9130621caefSChris Lattner             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
914748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
9159de0d14dSChris Lattner         else {
916f3baad3eSBill Wendling           cerr << "Could not resolve external global address: "
9179de0d14dSChris Lattner                << I->getName() << "\n";
9189de0d14dSChris Lattner           abort();
9199de0d14dSChris Lattner         }
920996fe010SChris Lattner       }
9210621caefSChris Lattner     }
9220621caefSChris Lattner 
9230621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
9240621caefSChris Lattner     // canonical location.
9250621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
9260621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
9270621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
9280621caefSChris Lattner         const GlobalValue *CGV =
9290621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
9300621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
9310621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
9320621caefSChris Lattner         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
9330621caefSChris Lattner       }
9340621caefSChris Lattner     }
935996fe010SChris Lattner 
9367a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
9377a9c62baSReid Spencer     // and initialize their contents.
9388ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
9390621caefSChris Lattner          I != E; ++I) {
9405301e7c6SReid Spencer       if (!I->isDeclaration()) {
9410621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
9420621caefSChris Lattner           if (const GlobalValue *GVEntry =
9430621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
9440621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
9450621caefSChris Lattner               continue;
9460621caefSChris Lattner         }
9476bbe3eceSChris Lattner         EmitGlobalVariable(I);
9486bbe3eceSChris Lattner       }
9490621caefSChris Lattner     }
9500621caefSChris Lattner   }
9510621caefSChris Lattner }
9526bbe3eceSChris Lattner 
9536bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
9546bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
9556bbe3eceSChris Lattner // already in the map.
956fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
957748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
9585834fdb3SBill Wendling   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
959dc631735SChris Lattner 
960fbcc0aa1SChris Lattner   const Type *ElTy = GV->getType()->getElementType();
96144b8721dSDuncan Sands   size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
9626bbe3eceSChris Lattner   if (GA == 0) {
9636bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
964d215992bSChris Lattner     GA = new char[GVSize];
965748e8579SChris Lattner     addGlobalMapping(GV, GA);
9666bbe3eceSChris Lattner   }
967fbcc0aa1SChris Lattner 
9686bbe3eceSChris Lattner   InitializeMemory(GV->getInitializer(), GA);
969df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
9706bbe3eceSChris Lattner   ++NumGlobals;
971996fe010SChris Lattner }
972