1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2996fe010SChris Lattner //
3482202a6SJohn Criswell //                     The LLVM Compiler Infrastructure
4482202a6SJohn Criswell //
5482202a6SJohn Criswell // This file was developed by the LLVM research group and is distributed under
6482202a6SJohn Criswell // the University of Illinois Open Source 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"
21260b0c88SMisha Brukman #include "llvm/ExecutionEngine/ExecutionEngine.h"
22ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h"
237c16caa3SReid Spencer #include "llvm/Support/Debug.h"
246d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
2570e37278SReid Spencer #include "llvm/System/DynamicLibrary.h"
2670e37278SReid Spencer #include "llvm/Target/TargetData.h"
2729681deeSChris Lattner using namespace llvm;
28996fe010SChris Lattner 
29c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
31996fe010SChris Lattner 
322d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
332d52c1b8SChris Lattner ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
342d52c1b8SChris Lattner 
350621caefSChris Lattner ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
3687aee74cSChris Lattner   LazyCompilationDisabled = false;
370621caefSChris Lattner   Modules.push_back(P);
38260b0c88SMisha Brukman   assert(P && "ModuleProvider is null?");
39260b0c88SMisha Brukman }
40260b0c88SMisha Brukman 
410621caefSChris Lattner ExecutionEngine::ExecutionEngine(Module *M) {
4287aee74cSChris Lattner   LazyCompilationDisabled = false;
43260b0c88SMisha Brukman   assert(M && "Module is null?");
440621caefSChris Lattner   Modules.push_back(new ExistingModuleProvider(M));
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 
530621caefSChris Lattner /// FindFunctionNamed - Search all of the active modules to find the one that
540621caefSChris Lattner /// defines FnName.  This is very slow operation and shouldn't be used for
550621caefSChris Lattner /// general code.
560621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
570621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
581241d6d5SReid Spencer     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
590621caefSChris Lattner       return F;
600621caefSChris Lattner   }
610621caefSChris Lattner   return 0;
620621caefSChris Lattner }
630621caefSChris Lattner 
640621caefSChris Lattner 
656d8dd189SChris Lattner /// addGlobalMapping - Tell the execution engine that the specified global is
666d8dd189SChris Lattner /// at the specified location.  This is used internally as functions are JIT'd
676d8dd189SChris Lattner /// and as global variables are laid out in memory.  It can and should also be
686d8dd189SChris Lattner /// used by clients of the EE that want to have an LLVM global overlay
696d8dd189SChris Lattner /// existing data in memory.
706d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
716d8dd189SChris Lattner   MutexGuard locked(lock);
726d8dd189SChris Lattner 
736d8dd189SChris Lattner   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
746d8dd189SChris Lattner   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
756d8dd189SChris Lattner   CurVal = Addr;
766d8dd189SChris Lattner 
776d8dd189SChris Lattner   // If we are using the reverse mapping, add it too
786d8dd189SChris Lattner   if (!state.getGlobalAddressReverseMap(locked).empty()) {
796d8dd189SChris Lattner     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
806d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
816d8dd189SChris Lattner     V = GV;
826d8dd189SChris Lattner   }
836d8dd189SChris Lattner }
846d8dd189SChris Lattner 
856d8dd189SChris Lattner /// clearAllGlobalMappings - Clear all global mappings and start over again
866d8dd189SChris Lattner /// use in dynamic compilation scenarios when you want to move globals
876d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
886d8dd189SChris Lattner   MutexGuard locked(lock);
896d8dd189SChris Lattner 
906d8dd189SChris Lattner   state.getGlobalAddressMap(locked).clear();
916d8dd189SChris Lattner   state.getGlobalAddressReverseMap(locked).clear();
926d8dd189SChris Lattner }
936d8dd189SChris Lattner 
946d8dd189SChris Lattner /// updateGlobalMapping - Replace an existing mapping for GV with a new
956d8dd189SChris Lattner /// address.  This updates both maps as required.  If "Addr" is null, the
966d8dd189SChris Lattner /// entry for the global is removed from the mappings.
976d8dd189SChris Lattner void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
986d8dd189SChris Lattner   MutexGuard locked(lock);
996d8dd189SChris Lattner 
1006d8dd189SChris Lattner   // Deleting from the mapping?
1016d8dd189SChris Lattner   if (Addr == 0) {
1026d8dd189SChris Lattner     state.getGlobalAddressMap(locked).erase(GV);
1036d8dd189SChris Lattner     if (!state.getGlobalAddressReverseMap(locked).empty())
1046d8dd189SChris Lattner       state.getGlobalAddressReverseMap(locked).erase(Addr);
1056d8dd189SChris Lattner     return;
1066d8dd189SChris Lattner   }
1076d8dd189SChris Lattner 
1086d8dd189SChris Lattner   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
1096d8dd189SChris Lattner   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
1106d8dd189SChris Lattner     state.getGlobalAddressReverseMap(locked).erase(CurVal);
1116d8dd189SChris Lattner   CurVal = Addr;
1126d8dd189SChris Lattner 
1136d8dd189SChris Lattner   // If we are using the reverse mapping, add it too
1146d8dd189SChris Lattner   if (!state.getGlobalAddressReverseMap(locked).empty()) {
1156d8dd189SChris Lattner     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
1166d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1176d8dd189SChris Lattner     V = GV;
1186d8dd189SChris Lattner   }
1196d8dd189SChris Lattner }
1206d8dd189SChris Lattner 
1216d8dd189SChris Lattner /// getPointerToGlobalIfAvailable - This returns the address of the specified
1226d8dd189SChris Lattner /// global value if it is has already been codegen'd, otherwise it returns null.
1236d8dd189SChris Lattner ///
1246d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
1256d8dd189SChris Lattner   MutexGuard locked(lock);
1266d8dd189SChris Lattner 
1276d8dd189SChris Lattner   std::map<const GlobalValue*, void*>::iterator I =
1286d8dd189SChris Lattner   state.getGlobalAddressMap(locked).find(GV);
1296d8dd189SChris Lattner   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
1306d8dd189SChris Lattner }
1316d8dd189SChris Lattner 
132748e8579SChris Lattner /// getGlobalValueAtAddress - Return the LLVM global value object that starts
133748e8579SChris Lattner /// at the specified address.
134748e8579SChris Lattner ///
135748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
13679876f52SReid Spencer   MutexGuard locked(lock);
13779876f52SReid Spencer 
138748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
13979876f52SReid Spencer   if (state.getGlobalAddressReverseMap(locked).empty()) {
1406d8dd189SChris Lattner     for (std::map<const GlobalValue*, void *>::iterator
1416d8dd189SChris Lattner          I = state.getGlobalAddressMap(locked).begin(),
1426d8dd189SChris Lattner          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
1436d8dd189SChris Lattner       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
1446d8dd189SChris Lattner                                                                      I->first));
145748e8579SChris Lattner   }
146748e8579SChris Lattner 
147748e8579SChris Lattner   std::map<void *, const GlobalValue*>::iterator I =
14879876f52SReid Spencer     state.getGlobalAddressReverseMap(locked).find(Addr);
14979876f52SReid Spencer   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
150748e8579SChris Lattner }
1515a0d4829SChris Lattner 
1525a0d4829SChris Lattner // CreateArgv - Turn a vector of strings into a nice argv style array of
1535a0d4829SChris Lattner // pointers to null terminated strings.
1545a0d4829SChris Lattner //
1555a0d4829SChris Lattner static void *CreateArgv(ExecutionEngine *EE,
1565a0d4829SChris Lattner                         const std::vector<std::string> &InputArgv) {
15720a631fdSOwen Anderson   unsigned PtrSize = EE->getTargetData()->getPointerSize();
1585a0d4829SChris Lattner   char *Result = new char[(InputArgv.size()+1)*PtrSize];
1595a0d4829SChris Lattner 
1605834fdb3SBill Wendling   DOUT << "ARGV = " << (void*)Result << "\n";
1610d54e78aSReid Spencer   const Type *SBytePtr = PointerType::get(Type::Int8Ty);
1625a0d4829SChris Lattner 
1635a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
1645a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
1655a0d4829SChris Lattner     char *Dest = new char[Size];
1665834fdb3SBill Wendling     DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
1675a0d4829SChris Lattner 
1685a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
1695a0d4829SChris Lattner     Dest[Size-1] = 0;
1705a0d4829SChris Lattner 
1715a0d4829SChris Lattner     // Endian safe: Result[i] = (PointerTy)Dest;
1725a0d4829SChris Lattner     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
1735a0d4829SChris Lattner                            SBytePtr);
1745a0d4829SChris Lattner   }
1755a0d4829SChris Lattner 
1765a0d4829SChris Lattner   // Null terminate it
1775a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
1785a0d4829SChris Lattner                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
1795a0d4829SChris Lattner                          SBytePtr);
1805a0d4829SChris Lattner   return Result;
1815a0d4829SChris Lattner }
1825a0d4829SChris Lattner 
183faae50b6SChris Lattner 
184faae50b6SChris Lattner /// runStaticConstructorsDestructors - This method is used to execute all of
1850621caefSChris Lattner /// the static constructors or destructors for a program, depending on the
186faae50b6SChris Lattner /// value of isDtors.
187faae50b6SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
188faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
1890621caefSChris Lattner 
1900621caefSChris Lattner   // Execute global ctors/dtors for each module in the program.
1910621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1920621caefSChris Lattner     GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
193fe36eaebSChris Lattner 
194fe36eaebSChris Lattner     // If this global has internal linkage, or if it has a use, then it must be
195fe36eaebSChris Lattner     // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
1960621caefSChris Lattner     // this is the case, don't execute any of the global ctors, __main will do
1970621caefSChris Lattner     // it.
1985301e7c6SReid Spencer     if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
199faae50b6SChris Lattner 
2000621caefSChris Lattner     // Should be an array of '{ int, void ()* }' structs.  The first value is
2010621caefSChris Lattner     // the init priority, which we ignore.
202faae50b6SChris Lattner     ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
2030621caefSChris Lattner     if (!InitList) continue;
204faae50b6SChris Lattner     for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
2050621caefSChris Lattner       if (ConstantStruct *CS =
2060621caefSChris Lattner           dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
2070621caefSChris Lattner         if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
208faae50b6SChris Lattner 
209faae50b6SChris Lattner         Constant *FP = CS->getOperand(1);
210faae50b6SChris Lattner         if (FP->isNullValue())
2110621caefSChris Lattner           break;  // Found a null terminator, exit.
212faae50b6SChris Lattner 
213faae50b6SChris Lattner         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
2146c38f0bbSReid Spencer           if (CE->isCast())
215faae50b6SChris Lattner             FP = CE->getOperand(0);
216faae50b6SChris Lattner         if (Function *F = dyn_cast<Function>(FP)) {
217faae50b6SChris Lattner           // Execute the ctor/dtor function!
218faae50b6SChris Lattner           runFunction(F, std::vector<GenericValue>());
219faae50b6SChris Lattner         }
220faae50b6SChris Lattner       }
221faae50b6SChris Lattner   }
2220621caefSChris Lattner }
223faae50b6SChris Lattner 
2245a0d4829SChris Lattner /// runFunctionAsMain - This is a helper function which wraps runFunction to
2255a0d4829SChris Lattner /// handle the common task of starting up main with the specified argc, argv,
2265a0d4829SChris Lattner /// and envp parameters.
2275a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
2285a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
2295a0d4829SChris Lattner                                        const char * const * envp) {
2305a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
2315a0d4829SChris Lattner   GenericValue GVArgc;
23287aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
233b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
234b1cad0b3SChris Lattner   if (NumArgs) {
2355a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
236b1cad0b3SChris Lattner     if (NumArgs > 1) {
2375a0d4829SChris Lattner       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
238b1cad0b3SChris Lattner       assert(((char **)GVTOP(GVArgs[1]))[0] &&
239b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
240b1cad0b3SChris Lattner       if (NumArgs > 2) {
2415a0d4829SChris Lattner         std::vector<std::string> EnvVars;
2425a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
2435a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
2445a0d4829SChris Lattner         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
245b1cad0b3SChris Lattner       }
246b1cad0b3SChris Lattner     }
247b1cad0b3SChris Lattner   }
24887aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
2495a0d4829SChris Lattner }
2505a0d4829SChris Lattner 
251260b0c88SMisha Brukman /// If possible, create a JIT, unless the caller specifically requests an
252260b0c88SMisha Brukman /// Interpreter or there's an error. If even an Interpreter cannot be created,
253260b0c88SMisha Brukman /// NULL is returned.
254857c21b4SMisha Brukman ///
2552f1e2002SMisha Brukman ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
256603682adSReid Spencer                                          bool ForceInterpreter,
257603682adSReid Spencer                                          std::string *ErrorStr) {
2584bd3bd5bSBrian Gaeke   ExecutionEngine *EE = 0;
2594bd3bd5bSBrian Gaeke 
260c8c6c03dSChris Lattner   // Unless the interpreter was explicitly selected, try making a JIT.
2612d52c1b8SChris Lattner   if (!ForceInterpreter && JITCtor)
262603682adSReid Spencer     EE = JITCtor(MP, ErrorStr);
2634bd3bd5bSBrian Gaeke 
2644bd3bd5bSBrian Gaeke   // If we can't make a JIT, make an interpreter instead.
2652d52c1b8SChris Lattner   if (EE == 0 && InterpCtor)
266603682adSReid Spencer     EE = InterpCtor(MP, ErrorStr);
267c8c6c03dSChris Lattner 
2680b2de9f2SChris Lattner   if (EE) {
26970e37278SReid Spencer     // Make sure we can resolve symbols in the program as well. The zero arg
27070e37278SReid Spencer     // to the function tells DynamicLibrary to load the program, not a library.
27163539389SChris Lattner     try {
27270e37278SReid Spencer       sys::DynamicLibrary::LoadLibraryPermanently(0);
27363539389SChris Lattner     } catch (...) {
27463539389SChris Lattner     }
2750b2de9f2SChris Lattner   }
27670e37278SReid Spencer 
2774bd3bd5bSBrian Gaeke   return EE;
2784bd3bd5bSBrian Gaeke }
2794bd3bd5bSBrian Gaeke 
280857c21b4SMisha Brukman /// getPointerToGlobal - This returns the address of the specified global
281857c21b4SMisha Brukman /// value.  This may involve code generation if it's a function.
282857c21b4SMisha Brukman ///
283996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
2841678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
285996fe010SChris Lattner     return getPointerToFunction(F);
286996fe010SChris Lattner 
28779876f52SReid Spencer   MutexGuard locked(lock);
28869e84901SJeff Cohen   void *p = state.getGlobalAddressMap(locked)[GV];
28969e84901SJeff Cohen   if (p)
29069e84901SJeff Cohen     return p;
29169e84901SJeff Cohen 
29269e84901SJeff Cohen   // Global variable might have been added since interpreter started.
29369e84901SJeff Cohen   if (GlobalVariable *GVar =
29469e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
29569e84901SJeff Cohen     EmitGlobalVariable(GVar);
29669e84901SJeff Cohen   else
2974da5e17cSChris Lattner     assert(0 && "Global hasn't had an address allocated yet!");
29879876f52SReid Spencer   return state.getGlobalAddressMap(locked)[GV];
299996fe010SChris Lattner }
300996fe010SChris Lattner 
3016c38f0bbSReid Spencer /// This function converts a Constant* into a GenericValue. The interesting
3026c38f0bbSReid Spencer /// part is if C is a ConstantExpr.
3036c38f0bbSReid Spencer /// @brief Get a GenericValue for a Constnat*
304996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
3056c38f0bbSReid Spencer   // Declare the result as garbage.
306996fe010SChris Lattner   GenericValue Result;
3076c38f0bbSReid Spencer 
3086c38f0bbSReid Spencer   // If its undefined, return the garbage.
309d7a7a3f4SChris Lattner   if (isa<UndefValue>(C)) return Result;
3109de0d14dSChris Lattner 
3116c38f0bbSReid Spencer   // If the value is a ConstantExpr
3126c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3139de0d14dSChris Lattner     switch (CE->getOpcode()) {
3149de0d14dSChris Lattner     case Instruction::GetElementPtr: {
3156c38f0bbSReid Spencer       // Compute the index
31668cbcc3eSChris Lattner       Result = getConstantValue(CE->getOperand(0));
317c44bd78aSChris Lattner       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
3189de0d14dSChris Lattner       uint64_t Offset =
319c44bd78aSChris Lattner         TD->getIndexedOffset(CE->getOperand(0)->getType(),
320c44bd78aSChris Lattner                              &Indices[0], Indices.size());
3219de0d14dSChris Lattner 
32287aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
32387aa65f4SReid Spencer       Result = PTOGV(tmp + Offset);
3249de0d14dSChris Lattner       return Result;
3259de0d14dSChris Lattner     }
3266c38f0bbSReid Spencer     case Instruction::Trunc:
3276c38f0bbSReid Spencer     case Instruction::ZExt:
3286c38f0bbSReid Spencer     case Instruction::SExt:
3296c38f0bbSReid Spencer     case Instruction::FPTrunc:
3306c38f0bbSReid Spencer     case Instruction::FPExt:
3316c38f0bbSReid Spencer     case Instruction::UIToFP:
3326c38f0bbSReid Spencer     case Instruction::SIToFP:
3336c38f0bbSReid Spencer     case Instruction::FPToUI:
3346c38f0bbSReid Spencer     case Instruction::FPToSI:
3356c38f0bbSReid Spencer       break;
3366c38f0bbSReid Spencer     case Instruction::PtrToInt: {
33768cbcc3eSChris Lattner       Constant *Op = CE->getOperand(0);
3385def7a57SChris Lattner       GenericValue GV = getConstantValue(Op);
3396c38f0bbSReid Spencer       return GV;
3406c38f0bbSReid Spencer     }
3416c38f0bbSReid Spencer     case Instruction::BitCast: {
3426c38f0bbSReid Spencer       // Bit casts are no-ops but we can only return the GV of the operand if
3436c38f0bbSReid Spencer       // they are the same basic type (pointer->pointer, packed->packed, etc.)
3446c38f0bbSReid Spencer       Constant *Op = CE->getOperand(0);
3456c38f0bbSReid Spencer       GenericValue GV = getConstantValue(Op);
3466b727599SChris Lattner       if (Op->getType()->getTypeID() == C->getType()->getTypeID())
3475def7a57SChris Lattner         return GV;
3486c38f0bbSReid Spencer       break;
3496c38f0bbSReid Spencer     }
3506c38f0bbSReid Spencer     case Instruction::IntToPtr: {
3516c38f0bbSReid Spencer       // IntToPtr casts are just so special. Cast to intptr_t first.
3526c38f0bbSReid Spencer       Constant *Op = CE->getOperand(0);
3536c38f0bbSReid Spencer       GenericValue GV = getConstantValue(Op);
35487aa65f4SReid Spencer       return PTOGV((void*)(uintptr_t)GV.IntVal.getZExtValue());
35568cbcc3eSChris Lattner       break;
35668cbcc3eSChris Lattner     }
35768cbcc3eSChris Lattner     case Instruction::Add:
358c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
359c4e6bb5fSChris Lattner       default: assert(0 && "Bad add type!"); abort();
3607a9c62baSReid Spencer       case Type::IntegerTyID:
36187aa65f4SReid Spencer         Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal + \
36287aa65f4SReid Spencer                         getConstantValue(CE->getOperand(1)).IntVal;
363c4e6bb5fSChris Lattner         break;
364c4e6bb5fSChris Lattner       case Type::FloatTyID:
365c4e6bb5fSChris Lattner         Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
366c4e6bb5fSChris Lattner                           getConstantValue(CE->getOperand(1)).FloatVal;
367c4e6bb5fSChris Lattner         break;
368c4e6bb5fSChris Lattner       case Type::DoubleTyID:
369c4e6bb5fSChris Lattner         Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
370c4e6bb5fSChris Lattner                            getConstantValue(CE->getOperand(1)).DoubleVal;
371c4e6bb5fSChris Lattner         break;
372c4e6bb5fSChris Lattner       }
37368cbcc3eSChris Lattner       return Result;
3749de0d14dSChris Lattner     default:
37568cbcc3eSChris Lattner       break;
37668cbcc3eSChris Lattner     }
377f3baad3eSBill Wendling     cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
3789de0d14dSChris Lattner     abort();
3799de0d14dSChris Lattner   }
380996fe010SChris Lattner 
3816b727599SChris Lattner   switch (C->getType()->getTypeID()) {
38287aa65f4SReid Spencer   case Type::FloatTyID:
38387aa65f4SReid Spencer     Result.FloatVal = (float)cast<ConstantFP>(C)->getValue();
3847a9c62baSReid Spencer     break;
38587aa65f4SReid Spencer   case Type::DoubleTyID:
38687aa65f4SReid Spencer     Result.DoubleVal = (double)cast<ConstantFP>(C)->getValue();
38787aa65f4SReid Spencer     break;
38887aa65f4SReid Spencer   case Type::IntegerTyID:
38987aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
39087aa65f4SReid Spencer     break;
391996fe010SChris Lattner   case Type::PointerTyID:
3926a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
393996fe010SChris Lattner       Result.PointerVal = 0;
3946a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
3956a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
3966a0fd73bSReid Spencer     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
3976a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
398e6492f10SChris Lattner     else
399996fe010SChris Lattner       assert(0 && "Unknown constant pointer type!");
400996fe010SChris Lattner     break;
401996fe010SChris Lattner   default:
402f3baad3eSBill Wendling     cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
4039de0d14dSChris Lattner     abort();
404996fe010SChris Lattner   }
405996fe010SChris Lattner   return Result;
406996fe010SChris Lattner }
407996fe010SChris Lattner 
4084ca2ea5bSNate Begeman /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
4094ca2ea5bSNate Begeman /// is the address of the memory at which to store Val, cast to GenericValue *.
4104ca2ea5bSNate Begeman /// It is not a pointer to a GenericValue containing the address at which to
4114ca2ea5bSNate Begeman /// store Val.
412857c21b4SMisha Brukman ///
413*4e42790cSReid Spencer void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
414996fe010SChris Lattner                                          const Type *Ty) {
4156b727599SChris Lattner   switch (Ty->getTypeID()) {
4167a9c62baSReid Spencer   case Type::IntegerTyID: {
4177a9c62baSReid Spencer     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
41801f7e06dSReid Spencer     GenericValue TmpVal = Val;
4197a9c62baSReid Spencer     if (BitWidth <= 8)
42087aa65f4SReid Spencer       *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
4217a9c62baSReid Spencer     else if (BitWidth <= 16) {
42287aa65f4SReid Spencer       *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
4237a9c62baSReid Spencer     } else if (BitWidth <= 32) {
42487aa65f4SReid Spencer       *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
4257a9c62baSReid Spencer     } else if (BitWidth <= 64) {
426*4e42790cSReid Spencer       *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
427815f8dd2SReid Spencer     } else {
428815f8dd2SReid Spencer       uint64_t *Dest = (uint64_t*)Ptr;
42987aa65f4SReid Spencer       const uint64_t *Src = Val.IntVal.getRawData();
43087aa65f4SReid Spencer       for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
431815f8dd2SReid Spencer         Dest[i] = Src[i];
432815f8dd2SReid Spencer     }
433996fe010SChris Lattner     break;
4347a9c62baSReid Spencer   }
435996fe010SChris Lattner   case Type::FloatTyID:
43687aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
43787aa65f4SReid Spencer     break;
43887aa65f4SReid Spencer   case Type::DoubleTyID:
43987aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
440996fe010SChris Lattner     break;
4417a9c62baSReid Spencer   case Type::PointerTyID:
44287aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
443996fe010SChris Lattner     break;
444996fe010SChris Lattner   default:
445f3baad3eSBill Wendling     cerr << "Cannot store value of type " << *Ty << "!\n";
446996fe010SChris Lattner   }
447996fe010SChris Lattner }
448996fe010SChris Lattner 
449857c21b4SMisha Brukman /// FIXME: document
450857c21b4SMisha Brukman ///
45100919f57SReid Spencer void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
45200919f57SReid Spencer                                                   GenericValue *Ptr,
4537f389e8cSChris Lattner                                                   const Type *Ty) {
4546b727599SChris Lattner   switch (Ty->getTypeID()) {
4557a9c62baSReid Spencer   case Type::IntegerTyID: {
4567a9c62baSReid Spencer     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4577a9c62baSReid Spencer     if (BitWidth <= 8)
45887aa65f4SReid Spencer       Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
4597a9c62baSReid Spencer     else if (BitWidth <= 16) {
46087aa65f4SReid Spencer       Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
4617a9c62baSReid Spencer     } else if (BitWidth <= 32) {
46287aa65f4SReid Spencer       Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
4637a9c62baSReid Spencer     } else if (BitWidth <= 64) {
46487aa65f4SReid Spencer       Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
4657a9c62baSReid Spencer     } else
46687aa65f4SReid Spencer       Result.IntVal = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
4677f389e8cSChris Lattner     break;
4687a9c62baSReid Spencer   }
4697f389e8cSChris Lattner   case Type::FloatTyID:
47087aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
47187aa65f4SReid Spencer     break;
47287aa65f4SReid Spencer   case Type::DoubleTyID:
47387aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
4747f389e8cSChris Lattner     break;
4757a9c62baSReid Spencer   case Type::PointerTyID:
47687aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
4777f389e8cSChris Lattner     break;
4787f389e8cSChris Lattner   default:
479f3baad3eSBill Wendling     cerr << "Cannot load value of type " << *Ty << "!\n";
4807f389e8cSChris Lattner     abort();
4817f389e8cSChris Lattner   }
4827f389e8cSChris Lattner }
4837f389e8cSChris Lattner 
484996fe010SChris Lattner // InitializeMemory - Recursive function to apply a Constant value into the
485996fe010SChris Lattner // specified memory location...
486996fe010SChris Lattner //
487996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
48861753bf8SChris Lattner   if (isa<UndefValue>(Init)) {
48961753bf8SChris Lattner     return;
490d84d35baSReid Spencer   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
49169d62138SRobert Bocchino     unsigned ElementSize =
49220a631fdSOwen Anderson       getTargetData()->getTypeSize(CP->getType()->getElementType());
49369d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
49469d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
49569d62138SRobert Bocchino     return;
49661753bf8SChris Lattner   } else if (Init->getType()->isFirstClassType()) {
497996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
498996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
499996fe010SChris Lattner     return;
500834b1272SChris Lattner   } else if (isa<ConstantAggregateZero>(Init)) {
50120a631fdSOwen Anderson     memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
502834b1272SChris Lattner     return;
503996fe010SChris Lattner   }
504996fe010SChris Lattner 
5056b727599SChris Lattner   switch (Init->getType()->getTypeID()) {
506996fe010SChris Lattner   case Type::ArrayTyID: {
507996fe010SChris Lattner     const ConstantArray *CPA = cast<ConstantArray>(Init);
508996fe010SChris Lattner     unsigned ElementSize =
50920a631fdSOwen Anderson       getTargetData()->getTypeSize(CPA->getType()->getElementType());
51083243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
51183243725SAlkis Evlogimenos       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
512996fe010SChris Lattner     return;
513996fe010SChris Lattner   }
514996fe010SChris Lattner 
515996fe010SChris Lattner   case Type::StructTyID: {
516996fe010SChris Lattner     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
517996fe010SChris Lattner     const StructLayout *SL =
51820a631fdSOwen Anderson       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
51983243725SAlkis Evlogimenos     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
520c473d8e4SChris Lattner       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
521996fe010SChris Lattner     return;
522996fe010SChris Lattner   }
523996fe010SChris Lattner 
524996fe010SChris Lattner   default:
525f3baad3eSBill Wendling     cerr << "Bad Type: " << *Init->getType() << "\n";
526996fe010SChris Lattner     assert(0 && "Unknown constant type to initialize memory with!");
527996fe010SChris Lattner   }
528996fe010SChris Lattner }
529996fe010SChris Lattner 
530996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
531996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
532996fe010SChris Lattner /// their initializers into the memory.
533996fe010SChris Lattner ///
534996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
53520a631fdSOwen Anderson   const TargetData *TD = getTargetData();
536996fe010SChris Lattner 
537996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
5380621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
5390621caefSChris Lattner   // to figure out how the different modules should link together.
5400621caefSChris Lattner   //
5410621caefSChris Lattner   std::map<std::pair<std::string, const Type*>,
5420621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
5430621caefSChris Lattner 
5440621caefSChris Lattner   if (Modules.size() != 1) {
5450621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
5460621caefSChris Lattner       Module &M = *Modules[m]->getModule();
5470621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
5480621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
5490621caefSChris Lattner         const GlobalValue *GV = I;
5505301e7c6SReid Spencer         if (GV->hasInternalLinkage() || GV->isDeclaration() ||
5510621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
5520621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
5530621caefSChris Lattner 
5540621caefSChris Lattner         const GlobalValue *&GVEntry =
5550621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
5560621caefSChris Lattner 
5570621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
5580621caefSChris Lattner         // version.
5590621caefSChris Lattner         if (!GVEntry) {
5600621caefSChris Lattner           GVEntry = GV;
5610621caefSChris Lattner           continue;
5620621caefSChris Lattner         }
5630621caefSChris Lattner 
5640621caefSChris Lattner         // If the existing global is strong, never replace it.
565d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
566d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
567d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
5680621caefSChris Lattner           continue;
5690621caefSChris Lattner 
5700621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
5710621caefSChris Lattner         // symbol.
57212c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
5730621caefSChris Lattner           GVEntry = GV;
5740621caefSChris Lattner       }
5750621caefSChris Lattner     }
5760621caefSChris Lattner   }
5770621caefSChris Lattner 
5780621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
5790621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
5800621caefSChris Lattner     Module &M = *Modules[m]->getModule();
5818ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
5820621caefSChris Lattner          I != E; ++I) {
5830621caefSChris Lattner       // In the multi-module case, see what this global maps to.
5840621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
5850621caefSChris Lattner         if (const GlobalValue *GVEntry =
5860621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
5870621caefSChris Lattner           // If something else is the canonical global, ignore this one.
5880621caefSChris Lattner           if (GVEntry != &*I) {
5890621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
5900621caefSChris Lattner             continue;
5910621caefSChris Lattner           }
5920621caefSChris Lattner         }
5930621caefSChris Lattner       }
5940621caefSChris Lattner 
5955301e7c6SReid Spencer       if (!I->isDeclaration()) {
5960621caefSChris Lattner         // Get the type of the global.
597996fe010SChris Lattner         const Type *Ty = I->getType()->getElementType();
598996fe010SChris Lattner 
599996fe010SChris Lattner         // Allocate some memory for it!
60020a631fdSOwen Anderson         unsigned Size = TD->getTypeSize(Ty);
6016bbe3eceSChris Lattner         addGlobalMapping(I, new char[Size]);
602996fe010SChris Lattner       } else {
603e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
604e8bbcfc2SBrian Gaeke         // get a pointer to it.
6050621caefSChris Lattner         if (void *SymAddr =
6060621caefSChris Lattner             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
607748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
6089de0d14dSChris Lattner         else {
609f3baad3eSBill Wendling           cerr << "Could not resolve external global address: "
6109de0d14dSChris Lattner                << I->getName() << "\n";
6119de0d14dSChris Lattner           abort();
6129de0d14dSChris Lattner         }
613996fe010SChris Lattner       }
6140621caefSChris Lattner     }
6150621caefSChris Lattner 
6160621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
6170621caefSChris Lattner     // canonical location.
6180621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
6190621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
6200621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
6210621caefSChris Lattner         const GlobalValue *CGV =
6220621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
6230621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
6240621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
6250621caefSChris Lattner         addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
6260621caefSChris Lattner       }
6270621caefSChris Lattner     }
628996fe010SChris Lattner 
6297a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
6307a9c62baSReid Spencer     // and initialize their contents.
6318ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
6320621caefSChris Lattner          I != E; ++I) {
6335301e7c6SReid Spencer       if (!I->isDeclaration()) {
6340621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
6350621caefSChris Lattner           if (const GlobalValue *GVEntry =
6360621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
6370621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
6380621caefSChris Lattner               continue;
6390621caefSChris Lattner         }
6406bbe3eceSChris Lattner         EmitGlobalVariable(I);
6416bbe3eceSChris Lattner       }
6420621caefSChris Lattner     }
6430621caefSChris Lattner   }
6440621caefSChris Lattner }
6456bbe3eceSChris Lattner 
6466bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
6476bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
6486bbe3eceSChris Lattner // already in the map.
649fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
650748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
6515834fdb3SBill Wendling   DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
652dc631735SChris Lattner 
653fbcc0aa1SChris Lattner   const Type *ElTy = GV->getType()->getElementType();
65420a631fdSOwen Anderson   size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
6556bbe3eceSChris Lattner   if (GA == 0) {
6566bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
657d215992bSChris Lattner     GA = new char[GVSize];
658748e8579SChris Lattner     addGlobalMapping(GV, GA);
6596bbe3eceSChris Lattner   }
660fbcc0aa1SChris Lattner 
6616bbe3eceSChris Lattner   InitializeMemory(GV->getInitializer(), GA);
662df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
6636bbe3eceSChris Lattner   ++NumGlobals;
664996fe010SChris Lattner }
665