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.
112ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1136d8dd189SChris Lattner   MutexGuard locked(lock);
1146d8dd189SChris Lattner 
115ee181730SChris Lattner   std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
116ee181730SChris Lattner 
1176d8dd189SChris Lattner   // Deleting from the mapping?
1186d8dd189SChris Lattner   if (Addr == 0) {
119ee181730SChris Lattner     std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
120ee181730SChris Lattner     void *OldVal;
121ee181730SChris Lattner     if (I == Map.end())
122ee181730SChris Lattner       OldVal = 0;
123ee181730SChris Lattner     else {
124ee181730SChris Lattner       OldVal = I->second;
125ee181730SChris Lattner       Map.erase(I);
1266d8dd189SChris Lattner     }
1276d8dd189SChris Lattner 
128ee181730SChris Lattner     if (!state.getGlobalAddressReverseMap(locked).empty())
129ee181730SChris Lattner       state.getGlobalAddressReverseMap(locked).erase(Addr);
130ee181730SChris Lattner     return OldVal;
131ee181730SChris Lattner   }
132ee181730SChris Lattner 
133ee181730SChris Lattner   void *&CurVal = Map[GV];
134ee181730SChris Lattner   void *OldVal = CurVal;
135ee181730SChris Lattner 
1366d8dd189SChris Lattner   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
1376d8dd189SChris Lattner     state.getGlobalAddressReverseMap(locked).erase(CurVal);
1386d8dd189SChris Lattner   CurVal = Addr;
1396d8dd189SChris Lattner 
1406d8dd189SChris Lattner   // If we are using the reverse mapping, add it too
1416d8dd189SChris Lattner   if (!state.getGlobalAddressReverseMap(locked).empty()) {
1426d8dd189SChris Lattner     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
1436d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1446d8dd189SChris Lattner     V = GV;
1456d8dd189SChris Lattner   }
146ee181730SChris Lattner   return OldVal;
1476d8dd189SChris Lattner }
1486d8dd189SChris Lattner 
1496d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified
1506d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null.
1516d8dd189SChris Lattner ///
1526d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
1536d8dd189SChris Lattner   MutexGuard locked(lock);
1546d8dd189SChris Lattner 
1556d8dd189SChris Lattner   std::map<const GlobalValue*, void*>::iterator I =
1566d8dd189SChris Lattner   state.getGlobalAddressMap(locked).find(GV);
1576d8dd189SChris Lattner   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
1586d8dd189SChris Lattner }
1596d8dd189SChris Lattner 
160748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts
161748e8579SChris Lattner /// at the specified address.
162748e8579SChris Lattner ///
163748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
16479876f52SReid Spencer   MutexGuard locked(lock);
16579876f52SReid Spencer 
166748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
16779876f52SReid Spencer   if (state.getGlobalAddressReverseMap(locked).empty()) {
1686d8dd189SChris Lattner     for (std::map<const GlobalValue*, void *>::iterator
1696d8dd189SChris Lattner          I = state.getGlobalAddressMap(locked).begin(),
1706d8dd189SChris Lattner          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
1716d8dd189SChris Lattner       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
1726d8dd189SChris Lattner                                                                      I->first));
173748e8579SChris Lattner   }
174748e8579SChris Lattner 
175748e8579SChris Lattner   std::map<void *, const GlobalValue*>::iterator I =
17679876f52SReid Spencer     state.getGlobalAddressReverseMap(locked).find(Addr);
17779876f52SReid Spencer   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
178748e8579SChris Lattner }
1795a0d4829SChris Lattner 
1805a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of
1815a0d4829SChris Lattner // pointers to null terminated strings.
1825a0d4829SChris Lattner //
1835a0d4829SChris Lattner static void *CreateArgv(ExecutionEngine *EE,
1845a0d4829SChris Lattner                         const std::vector<std::string> &InputArgv) {
18520a631fdSOwen Anderson   unsigned PtrSize = EE->getTargetData()->getPointerSize();
1865a0d4829SChris Lattner   char *Result = new char[(InputArgv.size()+1)*PtrSize];
1875a0d4829SChris Lattner 
1885834fdb3SBill Wendling   DOUT << "ARGV = " << (void*)Result << "\n";
189edf07887SChristopher Lamb   const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
1905a0d4829SChris Lattner 
1915a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
1925a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
1935a0d4829SChris Lattner     char *Dest = new char[Size];
1945834fdb3SBill Wendling     DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
1955a0d4829SChris Lattner 
1965a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
1975a0d4829SChris Lattner     Dest[Size-1] = 0;
1985a0d4829SChris Lattner 
1995a0d4829SChris Lattner     // Endian safe: Result[i] = (PointerTy)Dest;
2005a0d4829SChris Lattner     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
2015a0d4829SChris Lattner                            SBytePtr);
2025a0d4829SChris Lattner   }
2035a0d4829SChris Lattner 
2045a0d4829SChris Lattner   // Null terminate it
2055a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
2065a0d4829SChris Lattner                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
2075a0d4829SChris Lattner                          SBytePtr);
2085a0d4829SChris Lattner   return Result;
2095a0d4829SChris Lattner }
2105a0d4829SChris Lattner 
211faae50b6SChris Lattner 
212faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of
2130621caefSChris Lattner /// the static constructors or destructors for a program, depending on the
214faae50b6SChris Lattner /// value of isDtors.
215faae50b6SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
216faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
2170621caefSChris Lattner 
2180621caefSChris Lattner   // Execute global ctors/dtors for each module in the program.
2190621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
2200621caefSChris Lattner     GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
221fe36eaebSChris Lattner 
222fe36eaebSChris Lattner     // If this global has internal linkage, or if it has a use, then it must be
223fe36eaebSChris Lattner     // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
2240621caefSChris Lattner     // this is the case, don't execute any of the global ctors, __main will do
2250621caefSChris Lattner     // it.
2265301e7c6SReid Spencer     if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
227faae50b6SChris Lattner 
2280621caefSChris Lattner     // Should be an array of '{ int, void ()* }' structs.  The first value is
2290621caefSChris Lattner     // the init priority, which we ignore.
230faae50b6SChris Lattner     ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
2310621caefSChris Lattner     if (!InitList) continue;
232faae50b6SChris Lattner     for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
2330621caefSChris Lattner       if (ConstantStruct *CS =
2340621caefSChris Lattner           dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
2350621caefSChris Lattner         if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
236faae50b6SChris Lattner 
237faae50b6SChris Lattner         Constant *FP = CS->getOperand(1);
238faae50b6SChris Lattner         if (FP->isNullValue())
2390621caefSChris Lattner           break;  // Found a null terminator, exit.
240faae50b6SChris Lattner 
241faae50b6SChris Lattner         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
2426c38f0bbSReid Spencer           if (CE->isCast())
243faae50b6SChris Lattner             FP = CE->getOperand(0);
244faae50b6SChris Lattner         if (Function *F = dyn_cast<Function>(FP)) {
245faae50b6SChris Lattner           // Execute the ctor/dtor function!
246faae50b6SChris Lattner           runFunction(F, std::vector<GenericValue>());
247faae50b6SChris Lattner         }
248faae50b6SChris Lattner       }
249faae50b6SChris Lattner   }
2500621caefSChris Lattner }
251faae50b6SChris Lattner 
2521202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
2531202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
2541202d1b1SDuncan Sands   unsigned PtrSize = EE->getTargetData()->getPointerSize();
2551202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
2561202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
2571202d1b1SDuncan Sands       return false;
2581202d1b1SDuncan Sands   return true;
2591202d1b1SDuncan Sands }
2601202d1b1SDuncan Sands 
2615a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to
2625a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv,
2635a0d4829SChris Lattner /// and envp parameters.
2645a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
2655a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
2665a0d4829SChris Lattner                                        const char * const * envp) {
2675a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
2685a0d4829SChris Lattner   GenericValue GVArgc;
26987aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
2708c32c111SAnton Korobeynikov 
2718c32c111SAnton Korobeynikov   // Check main() type
272b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
2738c32c111SAnton Korobeynikov   const FunctionType *FTy = Fn->getFunctionType();
274edf07887SChristopher Lamb   const Type* PPInt8Ty =
275edf07887SChristopher Lamb     PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
2768c32c111SAnton Korobeynikov   switch (NumArgs) {
2778c32c111SAnton Korobeynikov   case 3:
2788c32c111SAnton Korobeynikov    if (FTy->getParamType(2) != PPInt8Ty) {
2798c32c111SAnton Korobeynikov      cerr << "Invalid type for third argument of main() supplied\n";
2808c32c111SAnton Korobeynikov      abort();
2818c32c111SAnton Korobeynikov    }
282b781886dSAnton Korobeynikov    // FALLS THROUGH
2838c32c111SAnton Korobeynikov   case 2:
2848c32c111SAnton Korobeynikov    if (FTy->getParamType(1) != PPInt8Ty) {
2858c32c111SAnton Korobeynikov      cerr << "Invalid type for second argument of main() supplied\n";
2868c32c111SAnton Korobeynikov      abort();
2878c32c111SAnton Korobeynikov    }
288b781886dSAnton Korobeynikov    // FALLS THROUGH
2898c32c111SAnton Korobeynikov   case 1:
2908c32c111SAnton Korobeynikov    if (FTy->getParamType(0) != Type::Int32Ty) {
2918c32c111SAnton Korobeynikov      cerr << "Invalid type for first argument of main() supplied\n";
2928c32c111SAnton Korobeynikov      abort();
2938c32c111SAnton Korobeynikov    }
294b781886dSAnton Korobeynikov    // FALLS THROUGH
2958c32c111SAnton Korobeynikov   case 0:
2968c32c111SAnton Korobeynikov    if (FTy->getReturnType() != Type::Int32Ty &&
2978c32c111SAnton Korobeynikov        FTy->getReturnType() != Type::VoidTy) {
2988c32c111SAnton Korobeynikov      cerr << "Invalid return type of main() supplied\n";
2998c32c111SAnton Korobeynikov      abort();
3008c32c111SAnton Korobeynikov    }
3018c32c111SAnton Korobeynikov    break;
3028c32c111SAnton Korobeynikov   default:
3038c32c111SAnton Korobeynikov    cerr << "Invalid number of arguments of main() supplied\n";
3048c32c111SAnton Korobeynikov    abort();
3058c32c111SAnton Korobeynikov   }
3068c32c111SAnton Korobeynikov 
307b1cad0b3SChris Lattner   if (NumArgs) {
3085a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
309b1cad0b3SChris Lattner     if (NumArgs > 1) {
3105a0d4829SChris Lattner       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
3111202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
312b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
313b1cad0b3SChris Lattner       if (NumArgs > 2) {
3145a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3155a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3165a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
3175a0d4829SChris Lattner         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
318b1cad0b3SChris Lattner       }
319b1cad0b3SChris Lattner     }
320b1cad0b3SChris Lattner   }
32187aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
3225a0d4829SChris Lattner }
3235a0d4829SChris Lattner 
324260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an
325260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created,
326260b0c88SMisha Brukman /// NULL is returned.
327857c21b4SMisha Brukman ///
3282f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
329603682adSReid Spencer                                          bool ForceInterpreter,
330603682adSReid Spencer                                          std::string *ErrorStr) {
3314bd3bd5bSBrian Gaeke   ExecutionEngine *EE = 0;
3324bd3bd5bSBrian Gaeke 
333a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
334a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
335a53414fdSNick Lewycky   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
336a53414fdSNick Lewycky     return 0;
337a53414fdSNick Lewycky 
338c8c6c03dSChris Lattner   // Unless the interpreter was explicitly selected, try making a JIT.
3392d52c1b8SChris Lattner   if (!ForceInterpreter && JITCtor)
340603682adSReid Spencer     EE = JITCtor(MP, ErrorStr);
3414bd3bd5bSBrian Gaeke 
3424bd3bd5bSBrian Gaeke   // If we can't make a JIT, make an interpreter instead.
3432d52c1b8SChris Lattner   if (EE == 0 && InterpCtor)
344603682adSReid Spencer     EE = InterpCtor(MP, ErrorStr);
345c8c6c03dSChris Lattner 
3464bd3bd5bSBrian Gaeke   return EE;
3474bd3bd5bSBrian Gaeke }
3484bd3bd5bSBrian Gaeke 
349b5163bb9SChris Lattner ExecutionEngine *ExecutionEngine::create(Module *M) {
350b5163bb9SChris Lattner   return create(new ExistingModuleProvider(M));
351b5163bb9SChris Lattner }
352b5163bb9SChris Lattner 
353857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global
354857c21b4SMisha Brukman /// value.  This may involve code generation if it's a function.
355857c21b4SMisha Brukman ///
356996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
3571678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
358996fe010SChris Lattner     return getPointerToFunction(F);
359996fe010SChris Lattner 
36079876f52SReid Spencer   MutexGuard locked(lock);
36169e84901SJeff Cohen   void *p = state.getGlobalAddressMap(locked)[GV];
36269e84901SJeff Cohen   if (p)
36369e84901SJeff Cohen     return p;
36469e84901SJeff Cohen 
36569e84901SJeff Cohen   // Global variable might have been added since interpreter started.
36669e84901SJeff Cohen   if (GlobalVariable *GVar =
36769e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
36869e84901SJeff Cohen     EmitGlobalVariable(GVar);
36969e84901SJeff Cohen   else
3704da5e17cSChris Lattner     assert(0 && "Global hasn't had an address allocated yet!");
37179876f52SReid Spencer   return state.getGlobalAddressMap(locked)[GV];
372996fe010SChris Lattner }
373996fe010SChris Lattner 
3746c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting
3756c38f0bbSReid Spencer /// part is if C is a ConstantExpr.
3762dc9f132SReid Spencer /// @brief Get a GenericValue for a Constant*
377996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
3786c38f0bbSReid Spencer   // If its undefined, return the garbage.
3794fd528f2SReid Spencer   if (isa<UndefValue>(C))
3804fd528f2SReid Spencer     return GenericValue();
3819de0d14dSChris Lattner 
3826c38f0bbSReid Spencer   // If the value is a ConstantExpr
3836c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3844fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
3859de0d14dSChris Lattner     switch (CE->getOpcode()) {
3869de0d14dSChris Lattner     case Instruction::GetElementPtr: {
3876c38f0bbSReid Spencer       // Compute the index
3884fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
389c44bd78aSChris Lattner       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
3909de0d14dSChris Lattner       uint64_t Offset =
3914fd528f2SReid Spencer         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
3929de0d14dSChris Lattner 
39387aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
39487aa65f4SReid Spencer       Result = PTOGV(tmp + Offset);
3959de0d14dSChris Lattner       return Result;
3969de0d14dSChris Lattner     }
3974fd528f2SReid Spencer     case Instruction::Trunc: {
3984fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
3994fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4004fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
4014fd528f2SReid Spencer       return GV;
4024fd528f2SReid Spencer     }
4034fd528f2SReid Spencer     case Instruction::ZExt: {
4044fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4054fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4064fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
4074fd528f2SReid Spencer       return GV;
4084fd528f2SReid Spencer     }
4094fd528f2SReid Spencer     case Instruction::SExt: {
4104fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4114fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4124fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
4134fd528f2SReid Spencer       return GV;
4144fd528f2SReid Spencer     }
4154fd528f2SReid Spencer     case Instruction::FPTrunc: {
416a1336cf5SDale Johannesen       // FIXME long double
4174fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4184fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
4194fd528f2SReid Spencer       return GV;
4204fd528f2SReid Spencer     }
4214fd528f2SReid Spencer     case Instruction::FPExt:{
422a1336cf5SDale Johannesen       // FIXME long double
4234fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4244fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
4254fd528f2SReid Spencer       return GV;
4264fd528f2SReid Spencer     }
4274fd528f2SReid Spencer     case Instruction::UIToFP: {
4284fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4294fd528f2SReid Spencer       if (CE->getType() == Type::FloatTy)
4304fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
431a1336cf5SDale Johannesen       else if (CE->getType() == Type::DoubleTy)
4324fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
433a1336cf5SDale Johannesen       else if (CE->getType() == Type::X86_FP80Ty) {
434a1336cf5SDale Johannesen         const uint64_t zero[] = {0, 0};
435a1336cf5SDale Johannesen         APFloat apf = APFloat(APInt(80, 2, zero));
436ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
437ca24fd90SDan Gohman                                    false,
4389150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
439a1336cf5SDale Johannesen         GV.IntVal = apf.convertToAPInt();
440a1336cf5SDale Johannesen       }
4414fd528f2SReid Spencer       return GV;
4424fd528f2SReid Spencer     }
4434fd528f2SReid Spencer     case Instruction::SIToFP: {
4444fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4454fd528f2SReid Spencer       if (CE->getType() == Type::FloatTy)
4464fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
447a1336cf5SDale Johannesen       else if (CE->getType() == Type::DoubleTy)
4484fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
449a1336cf5SDale Johannesen       else if (CE->getType() == Type::X86_FP80Ty) {
450a1336cf5SDale Johannesen         const uint64_t zero[] = { 0, 0};
451a1336cf5SDale Johannesen         APFloat apf = APFloat(APInt(80, 2, zero));
452ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
453ca24fd90SDan Gohman                                    true,
4549150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
455a1336cf5SDale Johannesen         GV.IntVal = apf.convertToAPInt();
456a1336cf5SDale Johannesen       }
4574fd528f2SReid Spencer       return GV;
4584fd528f2SReid Spencer     }
4594fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
4604fd528f2SReid Spencer     case Instruction::FPToSI: {
4614fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4624fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
4634fd528f2SReid Spencer       if (Op0->getType() == Type::FloatTy)
4644fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
465a1336cf5SDale Johannesen       else if (Op0->getType() == Type::DoubleTy)
4664fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
467a1336cf5SDale Johannesen       else if (Op0->getType() == Type::X86_FP80Ty) {
468a1336cf5SDale Johannesen         APFloat apf = APFloat(GV.IntVal);
469a1336cf5SDale Johannesen         uint64_t v;
470a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
471a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
472a1336cf5SDale Johannesen                                    APFloat::rmTowardZero);
473a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
474a1336cf5SDale Johannesen       }
4754fd528f2SReid Spencer       return GV;
4764fd528f2SReid Spencer     }
4776c38f0bbSReid Spencer     case Instruction::PtrToInt: {
4784fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4794fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
4804fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
4814fd528f2SReid Spencer       return GV;
4824fd528f2SReid Spencer     }
4834fd528f2SReid Spencer     case Instruction::IntToPtr: {
4844fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4854fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
4864fd528f2SReid Spencer       if (PtrWidth != GV.IntVal.getBitWidth())
4874fd528f2SReid Spencer         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
4884fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
4894fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
4906c38f0bbSReid Spencer       return GV;
4916c38f0bbSReid Spencer     }
4926c38f0bbSReid Spencer     case Instruction::BitCast: {
4934fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
4944fd528f2SReid Spencer       const Type* DestTy = CE->getType();
4954fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
4964fd528f2SReid Spencer         default: assert(0 && "Invalid bitcast operand");
4974fd528f2SReid Spencer         case Type::IntegerTyID:
4984fd528f2SReid Spencer           assert(DestTy->isFloatingPoint() && "invalid bitcast");
4994fd528f2SReid Spencer           if (DestTy == Type::FloatTy)
5004fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
5014fd528f2SReid Spencer           else if (DestTy == Type::DoubleTy)
5024fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
5036c38f0bbSReid Spencer           break;
5044fd528f2SReid Spencer         case Type::FloatTyID:
5054fd528f2SReid Spencer           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
5064fd528f2SReid Spencer           GV.IntVal.floatToBits(GV.FloatVal);
5074fd528f2SReid Spencer           break;
5084fd528f2SReid Spencer         case Type::DoubleTyID:
5094fd528f2SReid Spencer           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
5104fd528f2SReid Spencer           GV.IntVal.doubleToBits(GV.DoubleVal);
5114fd528f2SReid Spencer           break;
5124fd528f2SReid Spencer         case Type::PointerTyID:
5134fd528f2SReid Spencer           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
5144fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
5156c38f0bbSReid Spencer       }
5164fd528f2SReid Spencer       return GV;
51768cbcc3eSChris Lattner     }
51868cbcc3eSChris Lattner     case Instruction::Add:
5194fd528f2SReid Spencer     case Instruction::Sub:
5204fd528f2SReid Spencer     case Instruction::Mul:
5214fd528f2SReid Spencer     case Instruction::UDiv:
5224fd528f2SReid Spencer     case Instruction::SDiv:
5234fd528f2SReid Spencer     case Instruction::URem:
5244fd528f2SReid Spencer     case Instruction::SRem:
5254fd528f2SReid Spencer     case Instruction::And:
5264fd528f2SReid Spencer     case Instruction::Or:
5274fd528f2SReid Spencer     case Instruction::Xor: {
5284fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
5294fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
5304fd528f2SReid Spencer       GenericValue GV;
531c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
532c4e6bb5fSChris Lattner       default: assert(0 && "Bad add type!"); abort();
5337a9c62baSReid Spencer       case Type::IntegerTyID:
5344fd528f2SReid Spencer         switch (CE->getOpcode()) {
5354fd528f2SReid Spencer           default: assert(0 && "Invalid integer opcode");
5364fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
5374fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
5384fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
5394fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
5404fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
5414fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
5424fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
5434fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
5444fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
5454fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
5464fd528f2SReid Spencer         }
547c4e6bb5fSChris Lattner         break;
548c4e6bb5fSChris Lattner       case Type::FloatTyID:
5494fd528f2SReid Spencer         switch (CE->getOpcode()) {
5504fd528f2SReid Spencer           default: assert(0 && "Invalid float opcode"); abort();
5514fd528f2SReid Spencer           case Instruction::Add:
5524fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
5534fd528f2SReid Spencer           case Instruction::Sub:
5544fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
5554fd528f2SReid Spencer           case Instruction::Mul:
5564fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
5574fd528f2SReid Spencer           case Instruction::FDiv:
5584fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
5594fd528f2SReid Spencer           case Instruction::FRem:
5604fd528f2SReid Spencer             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
5614fd528f2SReid Spencer         }
562c4e6bb5fSChris Lattner         break;
563c4e6bb5fSChris Lattner       case Type::DoubleTyID:
5644fd528f2SReid Spencer         switch (CE->getOpcode()) {
5654fd528f2SReid Spencer           default: assert(0 && "Invalid double opcode"); abort();
5664fd528f2SReid Spencer           case Instruction::Add:
5674fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
5684fd528f2SReid Spencer           case Instruction::Sub:
5694fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
5704fd528f2SReid Spencer           case Instruction::Mul:
5714fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
5724fd528f2SReid Spencer           case Instruction::FDiv:
5734fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
5744fd528f2SReid Spencer           case Instruction::FRem:
5754fd528f2SReid Spencer             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
5764fd528f2SReid Spencer         }
577c4e6bb5fSChris Lattner         break;
578a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
579a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
580a1336cf5SDale Johannesen       case Type::FP128TyID: {
581a1336cf5SDale Johannesen         APFloat apfLHS = APFloat(LHS.IntVal);
582a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
583a1336cf5SDale Johannesen           default: assert(0 && "Invalid long double opcode"); abort();
584a1336cf5SDale Johannesen           case Instruction::Add:
585a1336cf5SDale Johannesen             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
586a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
587a1336cf5SDale Johannesen             break;
588a1336cf5SDale Johannesen           case Instruction::Sub:
589a1336cf5SDale Johannesen             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
590a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
591a1336cf5SDale Johannesen             break;
592a1336cf5SDale Johannesen           case Instruction::Mul:
593a1336cf5SDale Johannesen             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
594a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
595a1336cf5SDale Johannesen             break;
596a1336cf5SDale Johannesen           case Instruction::FDiv:
597a1336cf5SDale Johannesen             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
598a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
599a1336cf5SDale Johannesen             break;
600a1336cf5SDale Johannesen           case Instruction::FRem:
601a1336cf5SDale Johannesen             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
602a1336cf5SDale Johannesen             GV.IntVal = apfLHS.convertToAPInt();
603a1336cf5SDale Johannesen             break;
604a1336cf5SDale Johannesen           }
605a1336cf5SDale Johannesen         }
606a1336cf5SDale Johannesen         break;
607c4e6bb5fSChris Lattner       }
6084fd528f2SReid Spencer       return GV;
6094fd528f2SReid Spencer     }
6109de0d14dSChris Lattner     default:
61168cbcc3eSChris Lattner       break;
61268cbcc3eSChris Lattner     }
6134fd528f2SReid Spencer     cerr << "ConstantExpr not handled: " << *CE << "\n";
6149de0d14dSChris Lattner     abort();
6159de0d14dSChris Lattner   }
616996fe010SChris Lattner 
6174fd528f2SReid Spencer   GenericValue Result;
6186b727599SChris Lattner   switch (C->getType()->getTypeID()) {
61987aa65f4SReid Spencer   case Type::FloatTyID:
620bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
6217a9c62baSReid Spencer     break;
62287aa65f4SReid Spencer   case Type::DoubleTyID:
623bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
62487aa65f4SReid Spencer     break;
625a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
626a1336cf5SDale Johannesen   case Type::FP128TyID:
627a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
628a1336cf5SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
629a1336cf5SDale Johannesen     break;
63087aa65f4SReid Spencer   case Type::IntegerTyID:
63187aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
63287aa65f4SReid Spencer     break;
633996fe010SChris Lattner   case Type::PointerTyID:
6346a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
635996fe010SChris Lattner       Result.PointerVal = 0;
6366a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
6376a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
6386a0fd73bSReid Spencer     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
6396a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
640e6492f10SChris Lattner     else
641996fe010SChris Lattner       assert(0 && "Unknown constant pointer type!");
642996fe010SChris Lattner     break;
643996fe010SChris Lattner   default:
6444fd528f2SReid Spencer     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
6459de0d14dSChris Lattner     abort();
646996fe010SChris Lattner   }
647996fe010SChris Lattner   return Result;
648996fe010SChris Lattner }
649996fe010SChris Lattner 
6501202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
6511202d1b1SDuncan Sands /// with the integer held in IntVal.
6521202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
6531202d1b1SDuncan Sands                              unsigned StoreBytes) {
6541202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
6551202d1b1SDuncan Sands   uint8_t *Src = (uint8_t *)IntVal.getRawData();
6565c65cb46SDuncan Sands 
657fde55674SDuncan Sands   if (sys::littleEndianHost())
6581202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
6591202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
6605c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
6615c65cb46SDuncan Sands   else {
6625c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
6631202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
6641202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
6655c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
6665c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
6675c65cb46SDuncan Sands       // May not be aligned so use memcpy.
6685c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
6695c65cb46SDuncan Sands       Src += sizeof(uint64_t);
6705c65cb46SDuncan Sands     }
6715c65cb46SDuncan Sands 
6725c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
673815f8dd2SReid Spencer   }
6747a9c62baSReid Spencer }
6751202d1b1SDuncan Sands 
6761202d1b1SDuncan Sands /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
6771202d1b1SDuncan Sands /// is the address of the memory at which to store Val, cast to GenericValue *.
6781202d1b1SDuncan Sands /// It is not a pointer to a GenericValue containing the address at which to
6791202d1b1SDuncan Sands /// store Val.
6801202d1b1SDuncan Sands void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
6811202d1b1SDuncan Sands                                          const Type *Ty) {
6821202d1b1SDuncan Sands   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
6831202d1b1SDuncan Sands 
6841202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
6851202d1b1SDuncan Sands   case Type::IntegerTyID:
6861202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
6871202d1b1SDuncan Sands     break;
688996fe010SChris Lattner   case Type::FloatTyID:
68987aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
69087aa65f4SReid Spencer     break;
69187aa65f4SReid Spencer   case Type::DoubleTyID:
69287aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
693996fe010SChris Lattner     break;
694a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
695a1336cf5SDale Johannesen       uint16_t *Dest = (uint16_t*)Ptr;
696a1336cf5SDale Johannesen       const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
697a1336cf5SDale Johannesen       // This is endian dependent, but it will only work on x86 anyway.
698a1336cf5SDale Johannesen       Dest[0] = Src[4];
699a1336cf5SDale Johannesen       Dest[1] = Src[0];
700a1336cf5SDale Johannesen       Dest[2] = Src[1];
701a1336cf5SDale Johannesen       Dest[3] = Src[2];
702a1336cf5SDale Johannesen       Dest[4] = Src[3];
703a1336cf5SDale Johannesen       break;
704a1336cf5SDale Johannesen     }
7057a9c62baSReid Spencer   case Type::PointerTyID:
7061202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
7071202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
7081202d1b1SDuncan Sands       memset(Ptr, 0, StoreBytes);
7091202d1b1SDuncan Sands 
71087aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
711996fe010SChris Lattner     break;
712996fe010SChris Lattner   default:
713f3baad3eSBill Wendling     cerr << "Cannot store value of type " << *Ty << "!\n";
714996fe010SChris Lattner   }
7151202d1b1SDuncan Sands 
7161202d1b1SDuncan Sands   if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
7171202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
7181202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
719996fe010SChris Lattner }
720996fe010SChris Lattner 
7211202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
7221202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
7231202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
7241202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
7251202d1b1SDuncan Sands   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
7265c65cb46SDuncan Sands 
727fde55674SDuncan Sands   if (sys::littleEndianHost())
7285c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
7295c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
7305c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
7315c65cb46SDuncan Sands   else {
7325c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
7335c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
7345c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
7355c65cb46SDuncan Sands     // a word.
7365c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
7375c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
7385c65cb46SDuncan Sands       // May not be aligned so use memcpy.
7395c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
7405c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
7415c65cb46SDuncan Sands     }
7425c65cb46SDuncan Sands 
7435c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
7445c65cb46SDuncan Sands   }
7457a9c62baSReid Spencer }
7461202d1b1SDuncan Sands 
7471202d1b1SDuncan Sands /// FIXME: document
7481202d1b1SDuncan Sands ///
7491202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
7501202d1b1SDuncan Sands                                           GenericValue *Ptr,
7511202d1b1SDuncan Sands                                           const Type *Ty) {
7521202d1b1SDuncan Sands   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
7531202d1b1SDuncan Sands 
7541202d1b1SDuncan Sands   if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
7551202d1b1SDuncan Sands     // Host and target are different endian - reverse copy the stored
7561202d1b1SDuncan Sands     // bytes into a buffer, and load from that.
7571202d1b1SDuncan Sands     uint8_t *Src = (uint8_t*)Ptr;
7581202d1b1SDuncan Sands     uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
7591202d1b1SDuncan Sands     std::reverse_copy(Src, Src + LoadBytes, Buf);
7601202d1b1SDuncan Sands     Ptr = (GenericValue*)Buf;
7611202d1b1SDuncan Sands   }
7621202d1b1SDuncan Sands 
7631202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
7641202d1b1SDuncan Sands   case Type::IntegerTyID:
7651202d1b1SDuncan Sands     // An APInt with all words initially zero.
7661202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
7671202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
7681202d1b1SDuncan Sands     break;
7697f389e8cSChris Lattner   case Type::FloatTyID:
77087aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
77187aa65f4SReid Spencer     break;
77287aa65f4SReid Spencer   case Type::DoubleTyID:
77387aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
7747f389e8cSChris Lattner     break;
7757a9c62baSReid Spencer   case Type::PointerTyID:
77687aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
7777f389e8cSChris Lattner     break;
778a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
779a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
78026d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
781ff306287SDuncan Sands     uint16_t *p = (uint16_t*)Ptr;
782ff306287SDuncan Sands     union {
783ff306287SDuncan Sands       uint16_t x[8];
784ff306287SDuncan Sands       uint64_t y[2];
785ff306287SDuncan Sands     };
786a1336cf5SDale Johannesen     x[0] = p[1];
787a1336cf5SDale Johannesen     x[1] = p[2];
788a1336cf5SDale Johannesen     x[2] = p[3];
789a1336cf5SDale Johannesen     x[3] = p[4];
790a1336cf5SDale Johannesen     x[4] = p[0];
791ff306287SDuncan Sands     Result.IntVal = APInt(80, 2, y);
792a1336cf5SDale Johannesen     break;
793a1336cf5SDale Johannesen   }
7947f389e8cSChris Lattner   default:
795f3baad3eSBill Wendling     cerr << "Cannot load value of type " << *Ty << "!\n";
7967f389e8cSChris Lattner     abort();
7977f389e8cSChris Lattner   }
7987f389e8cSChris Lattner }
7997f389e8cSChris Lattner 
800996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the
801996fe010SChris Lattner // specified memory location...
802996fe010SChris Lattner //
803996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
80461753bf8SChris Lattner   if (isa<UndefValue>(Init)) {
80561753bf8SChris Lattner     return;
806d84d35baSReid Spencer   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
80769d62138SRobert Bocchino     unsigned ElementSize =
80844b8721dSDuncan Sands       getTargetData()->getABITypeSize(CP->getType()->getElementType());
80969d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
81069d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
81169d62138SRobert Bocchino     return;
8121dd86b11SChris Lattner   } else if (isa<ConstantAggregateZero>(Init)) {
8131dd86b11SChris Lattner     memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
8141dd86b11SChris Lattner     return;
81561753bf8SChris Lattner   } else if (Init->getType()->isFirstClassType()) {
816996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
817996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
818996fe010SChris Lattner     return;
819996fe010SChris Lattner   }
820996fe010SChris Lattner 
8216b727599SChris Lattner   switch (Init->getType()->getTypeID()) {
822996fe010SChris Lattner   case Type::ArrayTyID: {
823996fe010SChris Lattner     const ConstantArray *CPA = cast<ConstantArray>(Init);
824996fe010SChris Lattner     unsigned ElementSize =
82544b8721dSDuncan Sands       getTargetData()->getABITypeSize(CPA->getType()->getElementType());
82683243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
82783243725SAlkis Evlogimenos       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
828996fe010SChris Lattner     return;
829996fe010SChris Lattner   }
830996fe010SChris Lattner 
831996fe010SChris Lattner   case Type::StructTyID: {
832996fe010SChris Lattner     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
833996fe010SChris Lattner     const StructLayout *SL =
83420a631fdSOwen Anderson       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
83583243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
836c473d8e4SChris Lattner       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
837996fe010SChris Lattner     return;
838996fe010SChris Lattner   }
839996fe010SChris Lattner 
840996fe010SChris Lattner   default:
841f3baad3eSBill Wendling     cerr << "Bad Type: " << *Init->getType() << "\n";
842996fe010SChris Lattner     assert(0 && "Unknown constant type to initialize memory with!");
843996fe010SChris Lattner   }
844996fe010SChris Lattner }
845996fe010SChris Lattner 
846996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
847996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
848996fe010SChris Lattner /// their initializers into the memory.
849996fe010SChris Lattner ///
850996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
85120a631fdSOwen Anderson   const TargetData *TD = getTargetData();
852996fe010SChris Lattner 
853996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
8540621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
8550621caefSChris Lattner   // to figure out how the different modules should link together.
8560621caefSChris Lattner   //
8570621caefSChris Lattner   std::map<std::pair<std::string, const Type*>,
8580621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
8590621caefSChris Lattner 
8600621caefSChris Lattner   if (Modules.size() != 1) {
8610621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
8620621caefSChris Lattner       Module &M = *Modules[m]->getModule();
8630621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
8640621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
8650621caefSChris Lattner         const GlobalValue *GV = I;
8665301e7c6SReid Spencer         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
8670621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
8680621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
8690621caefSChris Lattner 
8700621caefSChris Lattner         const GlobalValue *&GVEntry =
8710621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
8720621caefSChris Lattner 
8730621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
8740621caefSChris Lattner         // version.
8750621caefSChris Lattner         if (!GVEntry) {
8760621caefSChris Lattner           GVEntry = GV;
8770621caefSChris Lattner           continue;
8780621caefSChris Lattner         }
8790621caefSChris Lattner 
8800621caefSChris Lattner         // If the existing global is strong, never replace it.
881d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
882d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
883d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
8840621caefSChris Lattner           continue;
8850621caefSChris Lattner 
8860621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
887*ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
88812c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
8890621caefSChris Lattner           GVEntry = GV;
8900621caefSChris Lattner       }
8910621caefSChris Lattner     }
8920621caefSChris Lattner   }
8930621caefSChris Lattner 
8940621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
8950621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
8960621caefSChris Lattner     Module &M = *Modules[m]->getModule();
8978ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
8980621caefSChris Lattner          I != E; ++I) {
8990621caefSChris Lattner       // In the multi-module case, see what this global maps to.
9000621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
9010621caefSChris Lattner         if (const GlobalValue *GVEntry =
9020621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
9030621caefSChris Lattner           // If something else is the canonical global, ignore this one.
9040621caefSChris Lattner           if (GVEntry != &*I) {
9050621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
9060621caefSChris Lattner             continue;
9070621caefSChris Lattner           }
9080621caefSChris Lattner         }
9090621caefSChris Lattner       }
9100621caefSChris Lattner 
9115301e7c6SReid Spencer       if (!I->isDeclaration()) {
9120621caefSChris Lattner         // Get the type of the global.
913996fe010SChris Lattner         const Type *Ty = I->getType()->getElementType();
914996fe010SChris Lattner 
915996fe010SChris Lattner         // Allocate some memory for it!
91644b8721dSDuncan Sands         unsigned Size = TD->getABITypeSize(Ty);
9176bbe3eceSChris Lattner         addGlobalMapping(I, new char[Size]);
918996fe010SChris Lattner       } else {
919e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
920e8bbcfc2SBrian Gaeke         // get a pointer to it.
9210621caefSChris Lattner         if (void *SymAddr =
9220621caefSChris Lattner             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
923748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
9249de0d14dSChris Lattner         else {
925f3baad3eSBill Wendling           cerr << "Could not resolve external global address: "
9269de0d14dSChris Lattner                << I->getName() << "\n";
9279de0d14dSChris Lattner           abort();
9289de0d14dSChris Lattner         }
929996fe010SChris Lattner       }
9300621caefSChris Lattner     }
9310621caefSChris Lattner 
9320621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
9330621caefSChris Lattner     // canonical location.
9340621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
9350621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
9360621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
9370621caefSChris Lattner         const GlobalValue *CGV =
9380621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
9390621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
9400621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
9410621caefSChris Lattner         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
9420621caefSChris Lattner       }
9430621caefSChris Lattner     }
944996fe010SChris Lattner 
9457a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
9467a9c62baSReid Spencer     // and initialize their contents.
9478ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
9480621caefSChris Lattner          I != E; ++I) {
9495301e7c6SReid Spencer       if (!I->isDeclaration()) {
9500621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
9510621caefSChris Lattner           if (const GlobalValue *GVEntry =
9520621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
9530621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
9540621caefSChris Lattner               continue;
9550621caefSChris Lattner         }
9566bbe3eceSChris Lattner         EmitGlobalVariable(I);
9576bbe3eceSChris Lattner       }
9580621caefSChris Lattner     }
9590621caefSChris Lattner   }
9600621caefSChris Lattner }
9616bbe3eceSChris Lattner 
9626bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
9636bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
9646bbe3eceSChris Lattner // already in the map.
965fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
966748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
9675834fdb3SBill Wendling   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
968dc631735SChris Lattner 
969fbcc0aa1SChris Lattner   const Type *ElTy = GV->getType()->getElementType();
97044b8721dSDuncan Sands   size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
9716bbe3eceSChris Lattner   if (GA == 0) {
9726bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
973d215992bSChris Lattner     GA = new char[GVSize];
974748e8579SChris Lattner     addGlobalMapping(GV, GA);
9756bbe3eceSChris Lattner   }
976fbcc0aa1SChris Lattner 
9776bbe3eceSChris Lattner   InitializeMemory(GV->getInitializer(), GA);
978df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
9796bbe3eceSChris Lattner   ++NumGlobals;
980996fe010SChris Lattner }
981