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"
166bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h"
176bf87df5SJeffrey Yasskin 
18996fe010SChris Lattner #include "llvm/Constants.h"
19260b0c88SMisha Brukman #include "llvm/DerivedTypes.h"
20996fe010SChris Lattner #include "llvm/Module.h"
21ad481312SChris Lattner #include "llvm/ExecutionEngine/GenericValue.h"
22868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h"
23390d78b3SChris Lattner #include "llvm/ADT/Statistic.h"
247c16caa3SReid Spencer #include "llvm/Support/Debug.h"
256c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h"
266d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
276bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h"
28ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h"
29447762daSMichael J. Spencer #include "llvm/Support/DynamicLibrary.h"
30447762daSMichael J. Spencer #include "llvm/Support/Host.h"
3170e37278SReid Spencer #include "llvm/Target/TargetData.h"
328418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h"
33579f0713SAnton Korobeynikov #include <cmath>
34579f0713SAnton Korobeynikov #include <cstring>
3529681deeSChris Lattner using namespace llvm;
36996fe010SChris Lattner 
37c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
39996fe010SChris Lattner 
4031faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)(
4131faefffSJeffrey Yasskin   Module *M,
42fc8a2d5aSReid Kleckner   std::string *ErrorStr,
43fc8a2d5aSReid Kleckner   JITMemoryManager *JMM,
44fc8a2d5aSReid Kleckner   CodeGenOpt::Level OptLevel,
45700d08e1SEric Christopher   bool GVsWithCode,
468418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
4770ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
4870ff8b05SDaniel Dunbar   Module *M,
4970ff8b05SDaniel Dunbar   std::string *ErrorStr,
5070ff8b05SDaniel Dunbar   JITMemoryManager *JMM,
5170ff8b05SDaniel Dunbar   CodeGenOpt::Level OptLevel,
5270ff8b05SDaniel Dunbar   bool GVsWithCode,
538418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
54091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55fc8a2d5aSReid Kleckner                                                 std::string *ErrorStr) = 0;
562d52c1b8SChris Lattner 
57091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M)
58f98e981cSJeffrey Yasskin   : EEState(*this),
59abc7901eSDuncan Sands     LazyFunctionCreator(0),
60abc7901eSDuncan Sands     ExceptionTableRegister(0),
61abc7901eSDuncan Sands     ExceptionTableDeregister(0) {
624567db45SJeffrey Yasskin   CompilingLazily         = false;
63cdc0060eSEvan Cheng   GVCompilationDisabled   = false;
6484a9055eSEvan Cheng   SymbolSearchingDisabled = false;
65091217beSJeffrey Yasskin   Modules.push_back(M);
66091217beSJeffrey Yasskin   assert(M && "Module is null?");
67260b0c88SMisha Brukman }
68260b0c88SMisha Brukman 
6992f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
70603682adSReid Spencer   clearAllGlobalMappings();
710621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
720621caefSChris Lattner     delete Modules[i];
7392f8b30dSBrian Gaeke }
7492f8b30dSBrian Gaeke 
75abc7901eSDuncan Sands void ExecutionEngine::DeregisterAllTables() {
76abc7901eSDuncan Sands   if (ExceptionTableDeregister) {
77f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79f045b7abSEric Christopher     for (; it != ite; ++it)
80f045b7abSEric Christopher       ExceptionTableDeregister(it->second);
81abc7901eSDuncan Sands     AllExceptionTables.clear();
82abc7901eSDuncan Sands   }
83abc7901eSDuncan Sands }
84abc7901eSDuncan Sands 
85a4044332SJeffrey Yasskin namespace {
86868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the
87868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed.
88a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH {
89a4044332SJeffrey Yasskin   GVMemoryBlock(const GlobalVariable *GV)
90a4044332SJeffrey Yasskin     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
91a4044332SJeffrey Yasskin 
92a4044332SJeffrey Yasskin public:
93868e3f09SDaniel Dunbar   /// \brief Returns the address the GlobalVariable should be written into.  The
94868e3f09SDaniel Dunbar   /// GVMemoryBlock object prefixes that.
95a4044332SJeffrey Yasskin   static char *Create(const GlobalVariable *GV, const TargetData& TD) {
965457ce9aSNicolas Geoffray     const Type *ElTy = GV->getType()->getElementType();
97a4044332SJeffrey Yasskin     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98a4044332SJeffrey Yasskin     void *RawMemory = ::operator new(
99a4044332SJeffrey Yasskin       TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
100a4044332SJeffrey Yasskin                                    TD.getPreferredAlignment(GV))
101a4044332SJeffrey Yasskin       + GVSize);
102a4044332SJeffrey Yasskin     new(RawMemory) GVMemoryBlock(GV);
103a4044332SJeffrey Yasskin     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
104a4044332SJeffrey Yasskin   }
105a4044332SJeffrey Yasskin 
106a4044332SJeffrey Yasskin   virtual void deleted() {
107a4044332SJeffrey Yasskin     // We allocated with operator new and with some extra memory hanging off the
108a4044332SJeffrey Yasskin     // end, so don't just delete this.  I'm not sure if this is actually
109a4044332SJeffrey Yasskin     // required.
110a4044332SJeffrey Yasskin     this->~GVMemoryBlock();
111a4044332SJeffrey Yasskin     ::operator delete(this);
112a4044332SJeffrey Yasskin   }
113a4044332SJeffrey Yasskin };
114a4044332SJeffrey Yasskin }  // anonymous namespace
115a4044332SJeffrey Yasskin 
116a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117a4044332SJeffrey Yasskin   return GVMemoryBlock::Create(GV, *getTargetData());
1185457ce9aSNicolas Geoffray }
1195457ce9aSNicolas Geoffray 
120091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) {
121091217beSJeffrey Yasskin   for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
123091217beSJeffrey Yasskin     Module *Found = *I;
124091217beSJeffrey Yasskin     if (Found == M) {
125324fe890SDevang Patel       Modules.erase(I);
126091217beSJeffrey Yasskin       clearGlobalMappingsFromModule(M);
127091217beSJeffrey Yasskin       return true;
128324fe890SDevang Patel     }
129324fe890SDevang Patel   }
130091217beSJeffrey Yasskin   return false;
131617001d8SNate Begeman }
132617001d8SNate Begeman 
1330621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
1340621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135091217beSJeffrey Yasskin     if (Function *F = Modules[i]->getFunction(FnName))
1360621caefSChris Lattner       return F;
1370621caefSChris Lattner   }
1380621caefSChris Lattner   return 0;
1390621caefSChris Lattner }
1400621caefSChris Lattner 
1410621caefSChris Lattner 
142868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143868e3f09SDaniel Dunbar                                           const GlobalValue *ToUnmap) {
144d0fc8f80SJeffrey Yasskin   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
145307c053fSJeffrey Yasskin   void *OldVal;
146868e3f09SDaniel Dunbar 
147868e3f09SDaniel Dunbar   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
148868e3f09SDaniel Dunbar   // GlobalAddressMap.
149307c053fSJeffrey Yasskin   if (I == GlobalAddressMap.end())
150307c053fSJeffrey Yasskin     OldVal = 0;
151307c053fSJeffrey Yasskin   else {
152307c053fSJeffrey Yasskin     OldVal = I->second;
153307c053fSJeffrey Yasskin     GlobalAddressMap.erase(I);
154307c053fSJeffrey Yasskin   }
155307c053fSJeffrey Yasskin 
156307c053fSJeffrey Yasskin   GlobalAddressReverseMap.erase(OldVal);
157307c053fSJeffrey Yasskin   return OldVal;
158307c053fSJeffrey Yasskin }
159307c053fSJeffrey Yasskin 
1606d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
1616d8dd189SChris Lattner   MutexGuard locked(lock);
1626d8dd189SChris Lattner 
1630967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
1649813b0b0SDaniel Dunbar         << "\' to [" << Addr << "]\n";);
165d0fc8f80SJeffrey Yasskin   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
1666d8dd189SChris Lattner   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
1676d8dd189SChris Lattner   CurVal = Addr;
1686d8dd189SChris Lattner 
169868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
170f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
1716bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
172f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
1736d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1746d8dd189SChris Lattner     V = GV;
1756d8dd189SChris Lattner   }
1766d8dd189SChris Lattner }
1776d8dd189SChris Lattner 
1786d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1796d8dd189SChris Lattner   MutexGuard locked(lock);
1806d8dd189SChris Lattner 
181f98e981cSJeffrey Yasskin   EEState.getGlobalAddressMap(locked).clear();
182f98e981cSJeffrey Yasskin   EEState.getGlobalAddressReverseMap(locked).clear();
1836d8dd189SChris Lattner }
1846d8dd189SChris Lattner 
1858f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
1868f83fc4dSNate Begeman   MutexGuard locked(lock);
1878f83fc4dSNate Begeman 
188868e3f09SDaniel Dunbar   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, FI);
1908f83fc4dSNate Begeman   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
191868e3f09SDaniel Dunbar        GI != GE; ++GI)
192f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, GI);
1938f83fc4dSNate Begeman }
1948f83fc4dSNate Begeman 
195ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1966d8dd189SChris Lattner   MutexGuard locked(lock);
1976d8dd189SChris Lattner 
198d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy &Map =
199f98e981cSJeffrey Yasskin     EEState.getGlobalAddressMap(locked);
200ee181730SChris Lattner 
2016d8dd189SChris Lattner   // Deleting from the mapping?
202868e3f09SDaniel Dunbar   if (Addr == 0)
203f98e981cSJeffrey Yasskin     return EEState.RemoveMapping(locked, GV);
204ee181730SChris Lattner 
205d0fc8f80SJeffrey Yasskin   void *&CurVal = Map[GV];
206ee181730SChris Lattner   void *OldVal = CurVal;
207ee181730SChris Lattner 
208f98e981cSJeffrey Yasskin   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
2106d8dd189SChris Lattner   CurVal = Addr;
2116d8dd189SChris Lattner 
212868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
213f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
2146bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
215f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
2166d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
2176d8dd189SChris Lattner     V = GV;
2186d8dd189SChris Lattner   }
219ee181730SChris Lattner   return OldVal;
2206d8dd189SChris Lattner }
2216d8dd189SChris Lattner 
2226d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
2236d8dd189SChris Lattner   MutexGuard locked(lock);
2246d8dd189SChris Lattner 
225d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy::iterator I =
226d0fc8f80SJeffrey Yasskin     EEState.getGlobalAddressMap(locked).find(GV);
227f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
2286d8dd189SChris Lattner }
2296d8dd189SChris Lattner 
230748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
23179876f52SReid Spencer   MutexGuard locked(lock);
23279876f52SReid Spencer 
233748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
234f98e981cSJeffrey Yasskin   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235d0fc8f80SJeffrey Yasskin     for (ExecutionEngineState::GlobalAddressMapTy::iterator
236f98e981cSJeffrey Yasskin          I = EEState.getGlobalAddressMap(locked).begin(),
237f98e981cSJeffrey Yasskin          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238e4f47434SDaniel Dunbar       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239e4f47434SDaniel Dunbar                                                           I->second, I->first));
240748e8579SChris Lattner   }
241748e8579SChris Lattner 
2426bf87df5SJeffrey Yasskin   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).find(Addr);
244f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
245748e8579SChris Lattner }
2465a0d4829SChris Lattner 
247bfd38abbSJeffrey Yasskin namespace {
248bfd38abbSJeffrey Yasskin class ArgvArray {
249bfd38abbSJeffrey Yasskin   char *Array;
250bfd38abbSJeffrey Yasskin   std::vector<char*> Values;
251bfd38abbSJeffrey Yasskin public:
252bfd38abbSJeffrey Yasskin   ArgvArray() : Array(NULL) {}
253bfd38abbSJeffrey Yasskin   ~ArgvArray() { clear(); }
254bfd38abbSJeffrey Yasskin   void clear() {
255bfd38abbSJeffrey Yasskin     delete[] Array;
256bfd38abbSJeffrey Yasskin     Array = NULL;
257bfd38abbSJeffrey Yasskin     for (size_t I = 0, E = Values.size(); I != E; ++I) {
258bfd38abbSJeffrey Yasskin       delete[] Values[I];
259bfd38abbSJeffrey Yasskin     }
260bfd38abbSJeffrey Yasskin     Values.clear();
261bfd38abbSJeffrey Yasskin   }
262bfd38abbSJeffrey Yasskin   /// Turn a vector of strings into a nice argv style array of pointers to null
263bfd38abbSJeffrey Yasskin   /// terminated strings.
264bfd38abbSJeffrey Yasskin   void *reset(LLVMContext &C, ExecutionEngine *EE,
265bfd38abbSJeffrey Yasskin               const std::vector<std::string> &InputArgv);
266bfd38abbSJeffrey Yasskin };
267bfd38abbSJeffrey Yasskin }  // anonymous namespace
268bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
2695a0d4829SChris Lattner                        const std::vector<std::string> &InputArgv) {
270bfd38abbSJeffrey Yasskin   clear();  // Free the old contents.
27120a631fdSOwen Anderson   unsigned PtrSize = EE->getTargetData()->getPointerSize();
272bfd38abbSJeffrey Yasskin   Array = new char[(InputArgv.size()+1)*PtrSize];
2735a0d4829SChris Lattner 
274bfd38abbSJeffrey Yasskin   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
2759ed7b16bSDuncan Sands   const Type *SBytePtr = Type::getInt8PtrTy(C);
2765a0d4829SChris Lattner 
2775a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
2785a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
2795a0d4829SChris Lattner     char *Dest = new char[Size];
280bfd38abbSJeffrey Yasskin     Values.push_back(Dest);
2810967d2dfSDavid Greene     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
2825a0d4829SChris Lattner 
2835a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
2845a0d4829SChris Lattner     Dest[Size-1] = 0;
2855a0d4829SChris Lattner 
286bfd38abbSJeffrey Yasskin     // Endian safe: Array[i] = (PointerTy)Dest;
287bfd38abbSJeffrey Yasskin     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
2885a0d4829SChris Lattner                            SBytePtr);
2895a0d4829SChris Lattner   }
2905a0d4829SChris Lattner 
2915a0d4829SChris Lattner   // Null terminate it
2925a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
293bfd38abbSJeffrey Yasskin                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
2945a0d4829SChris Lattner                          SBytePtr);
295bfd38abbSJeffrey Yasskin   return Array;
2965a0d4829SChris Lattner }
2975a0d4829SChris Lattner 
29841fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
29941fa2bd1SChris Lattner                                                        bool isDtors) {
300faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
3011a9a0b7bSEvan Cheng   GlobalVariable *GV = module->getNamedGlobal(Name);
302fe36eaebSChris Lattner 
303fe36eaebSChris Lattner   // If this global has internal linkage, or if it has a use, then it must be
304fe36eaebSChris Lattner   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
3050621caefSChris Lattner   // this is the case, don't execute any of the global ctors, __main will do
3060621caefSChris Lattner   // it.
3076de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
308faae50b6SChris Lattner 
3090cbfcb2bSNick Lewycky   // Should be an array of '{ i32, void ()* }' structs.  The first value is
3100621caefSChris Lattner   // the init priority, which we ignore.
3110f857898SNick Lewycky   if (isa<ConstantAggregateZero>(GV->getInitializer()))
3120f857898SNick Lewycky     return;
313466d0c1fSNick Lewycky   ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
314868e3f09SDaniel Dunbar   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
3150f857898SNick Lewycky     if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
3160f857898SNick Lewycky       continue;
317466d0c1fSNick Lewycky     ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
318faae50b6SChris Lattner 
319faae50b6SChris Lattner     Constant *FP = CS->getOperand(1);
320faae50b6SChris Lattner     if (FP->isNullValue())
3210f857898SNick Lewycky       continue;  // Found a sentinal value, ignore.
322faae50b6SChris Lattner 
323868e3f09SDaniel Dunbar     // Strip off constant expression casts.
324faae50b6SChris Lattner     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
3256c38f0bbSReid Spencer       if (CE->isCast())
326faae50b6SChris Lattner         FP = CE->getOperand(0);
327868e3f09SDaniel Dunbar 
328faae50b6SChris Lattner     // Execute the ctor/dtor function!
329868e3f09SDaniel Dunbar     if (Function *F = dyn_cast<Function>(FP))
330faae50b6SChris Lattner       runFunction(F, std::vector<GenericValue>());
331868e3f09SDaniel Dunbar 
332868e3f09SDaniel Dunbar     // FIXME: It is marginally lame that we just do nothing here if we see an
333868e3f09SDaniel Dunbar     // entry we don't recognize. It might not be unreasonable for the verifier
334868e3f09SDaniel Dunbar     // to not even allow this and just assert here.
335faae50b6SChris Lattner   }
336faae50b6SChris Lattner }
3371a9a0b7bSEvan Cheng 
3381a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
3391a9a0b7bSEvan Cheng   // Execute global ctors/dtors for each module in the program.
340868e3f09SDaniel Dunbar   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
341868e3f09SDaniel Dunbar     runStaticConstructorsDestructors(Modules[i], isDtors);
3420621caefSChris Lattner }
343faae50b6SChris Lattner 
344cf3e3017SDan Gohman #ifndef NDEBUG
3451202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
3461202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
3471202d1b1SDuncan Sands   unsigned PtrSize = EE->getTargetData()->getPointerSize();
3481202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
3491202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
3501202d1b1SDuncan Sands       return false;
3511202d1b1SDuncan Sands   return true;
3521202d1b1SDuncan Sands }
353cf3e3017SDan Gohman #endif
3541202d1b1SDuncan Sands 
3555a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
3565a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
3575a0d4829SChris Lattner                                        const char * const * envp) {
3585a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
3595a0d4829SChris Lattner   GenericValue GVArgc;
36087aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
3618c32c111SAnton Korobeynikov 
3628c32c111SAnton Korobeynikov   // Check main() type
363b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
3648c32c111SAnton Korobeynikov   const FunctionType *FTy = Fn->getFunctionType();
365ccce8baeSBenjamin Kramer   const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366868e3f09SDaniel Dunbar 
367868e3f09SDaniel Dunbar   // Check the argument types.
368868e3f09SDaniel Dunbar   if (NumArgs > 3)
3692104b8d3SChris Lattner     report_fatal_error("Invalid number of arguments of main() supplied");
370868e3f09SDaniel Dunbar   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
371868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for third argument of main() supplied");
372868e3f09SDaniel Dunbar   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
373868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for second argument of main() supplied");
374868e3f09SDaniel Dunbar   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
375868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for first argument of main() supplied");
376868e3f09SDaniel Dunbar   if (!FTy->getReturnType()->isIntegerTy() &&
377868e3f09SDaniel Dunbar       !FTy->getReturnType()->isVoidTy())
378868e3f09SDaniel Dunbar     report_fatal_error("Invalid return type of main() supplied");
3798c32c111SAnton Korobeynikov 
380bfd38abbSJeffrey Yasskin   ArgvArray CArgv;
381bfd38abbSJeffrey Yasskin   ArgvArray CEnv;
382b1cad0b3SChris Lattner   if (NumArgs) {
3835a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
384b1cad0b3SChris Lattner     if (NumArgs > 1) {
38555f1c09eSOwen Anderson       // Arg #1 = argv.
386bfd38abbSJeffrey Yasskin       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
3871202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
388b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
389b1cad0b3SChris Lattner       if (NumArgs > 2) {
3905a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3915a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3925a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
39355f1c09eSOwen Anderson         // Arg #2 = envp.
394bfd38abbSJeffrey Yasskin         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
395b1cad0b3SChris Lattner       }
396b1cad0b3SChris Lattner     }
397b1cad0b3SChris Lattner   }
398868e3f09SDaniel Dunbar 
39987aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
4005a0d4829SChris Lattner }
4015a0d4829SChris Lattner 
402091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M,
403603682adSReid Spencer                                          bool ForceInterpreter,
4047ff05bf5SEvan Cheng                                          std::string *ErrorStr,
40570415d97SJeffrey Yasskin                                          CodeGenOpt::Level OptLevel,
40670415d97SJeffrey Yasskin                                          bool GVsWithCode) {
407091217beSJeffrey Yasskin   return EngineBuilder(M)
408fc8a2d5aSReid Kleckner       .setEngineKind(ForceInterpreter
409fc8a2d5aSReid Kleckner                      ? EngineKind::Interpreter
410fc8a2d5aSReid Kleckner                      : EngineKind::JIT)
411fc8a2d5aSReid Kleckner       .setErrorStr(ErrorStr)
412fc8a2d5aSReid Kleckner       .setOptLevel(OptLevel)
413fc8a2d5aSReid Kleckner       .setAllocateGVsWithCode(GVsWithCode)
414fc8a2d5aSReid Kleckner       .create();
415fc8a2d5aSReid Kleckner }
4164bd3bd5bSBrian Gaeke 
417*0bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current
418*0bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter.  This takes ownership
419*0bd34fbdSDylan Noblesmith /// of the module.
420*0bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421*0bd34fbdSDylan Noblesmith                                             std::string *ErrorStr,
422*0bd34fbdSDylan Noblesmith                                             JITMemoryManager *JMM,
423*0bd34fbdSDylan Noblesmith                                             CodeGenOpt::Level OptLevel,
424*0bd34fbdSDylan Noblesmith                                             bool GVsWithCode,
425*0bd34fbdSDylan Noblesmith                                             CodeModel::Model CMM) {
426*0bd34fbdSDylan Noblesmith   if (ExecutionEngine::JITCtor == 0) {
427*0bd34fbdSDylan Noblesmith     if (ErrorStr)
428*0bd34fbdSDylan Noblesmith       *ErrorStr = "JIT has not been linked in.";
429*0bd34fbdSDylan Noblesmith     return 0;
430*0bd34fbdSDylan Noblesmith   }
431*0bd34fbdSDylan Noblesmith 
432*0bd34fbdSDylan Noblesmith   // Use the defaults for extra parameters.  Users can use EngineBuilder to
433*0bd34fbdSDylan Noblesmith   // set them.
434*0bd34fbdSDylan Noblesmith   StringRef MArch = "";
435*0bd34fbdSDylan Noblesmith   StringRef MCPU = "";
436*0bd34fbdSDylan Noblesmith   SmallVector<std::string, 1> MAttrs;
437*0bd34fbdSDylan Noblesmith 
438*0bd34fbdSDylan Noblesmith   TargetMachine *TM =
439*0bd34fbdSDylan Noblesmith           EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
440*0bd34fbdSDylan Noblesmith   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
441*0bd34fbdSDylan Noblesmith   TM->setCodeModel(CMM);
442*0bd34fbdSDylan Noblesmith 
443*0bd34fbdSDylan Noblesmith   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, GVsWithCode, TM);
444*0bd34fbdSDylan Noblesmith }
445*0bd34fbdSDylan Noblesmith 
446fc8a2d5aSReid Kleckner ExecutionEngine *EngineBuilder::create() {
447a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
448a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
449a53414fdSNick Lewycky   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
450a53414fdSNick Lewycky     return 0;
451a53414fdSNick Lewycky 
452fc8a2d5aSReid Kleckner   // If the user specified a memory manager but didn't specify which engine to
453fc8a2d5aSReid Kleckner   // create, we assume they only want the JIT, and we fail if they only want
454fc8a2d5aSReid Kleckner   // the interpreter.
455fc8a2d5aSReid Kleckner   if (JMM) {
45641fa2bd1SChris Lattner     if (WhichEngine & EngineKind::JIT)
457fc8a2d5aSReid Kleckner       WhichEngine = EngineKind::JIT;
45841fa2bd1SChris Lattner     else {
4598bcc6445SChris Lattner       if (ErrorStr)
460fc8a2d5aSReid Kleckner         *ErrorStr = "Cannot create an interpreter with a memory manager.";
46141fa2bd1SChris Lattner       return 0;
462fc8a2d5aSReid Kleckner     }
4634bd3bd5bSBrian Gaeke   }
4644bd3bd5bSBrian Gaeke 
465fc8a2d5aSReid Kleckner   // Unless the interpreter was explicitly selected or the JIT is not linked,
466fc8a2d5aSReid Kleckner   // try making a JIT.
46741fa2bd1SChris Lattner   if (WhichEngine & EngineKind::JIT) {
4688418fdcdSDylan Noblesmith     if (TargetMachine *TM =
4698418fdcdSDylan Noblesmith         EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr)) {
4708418fdcdSDylan Noblesmith       TM->setCodeModel(CMModel);
4718418fdcdSDylan Noblesmith 
47270ff8b05SDaniel Dunbar       if (UseMCJIT && ExecutionEngine::MCJITCtor) {
47370ff8b05SDaniel Dunbar         ExecutionEngine *EE =
47470ff8b05SDaniel Dunbar           ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
4758418fdcdSDylan Noblesmith                                      AllocateGVsWithCode, TM);
47670ff8b05SDaniel Dunbar         if (EE) return EE;
47770ff8b05SDaniel Dunbar       } else if (ExecutionEngine::JITCtor) {
47841fa2bd1SChris Lattner         ExecutionEngine *EE =
479091217beSJeffrey Yasskin           ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
4808418fdcdSDylan Noblesmith                                    AllocateGVsWithCode, TM);
48141fa2bd1SChris Lattner         if (EE) return EE;
48241fa2bd1SChris Lattner       }
483fc8a2d5aSReid Kleckner     }
4848418fdcdSDylan Noblesmith   }
485fc8a2d5aSReid Kleckner 
486fc8a2d5aSReid Kleckner   // If we can't make a JIT and we didn't request one specifically, try making
487fc8a2d5aSReid Kleckner   // an interpreter instead.
48841fa2bd1SChris Lattner   if (WhichEngine & EngineKind::Interpreter) {
48941fa2bd1SChris Lattner     if (ExecutionEngine::InterpCtor)
490091217beSJeffrey Yasskin       return ExecutionEngine::InterpCtor(M, ErrorStr);
4918bcc6445SChris Lattner     if (ErrorStr)
49241fa2bd1SChris Lattner       *ErrorStr = "Interpreter has not been linked in.";
49341fa2bd1SChris Lattner     return 0;
494fc8a2d5aSReid Kleckner   }
495fc8a2d5aSReid Kleckner 
4968bcc6445SChris Lattner   if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
4978bcc6445SChris Lattner     if (ErrorStr)
4988bcc6445SChris Lattner       *ErrorStr = "JIT has not been linked in.";
4998bcc6445SChris Lattner   }
500868e3f09SDaniel Dunbar 
50141fa2bd1SChris Lattner   return 0;
502b5163bb9SChris Lattner }
503b5163bb9SChris Lattner 
504996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
5051678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
506996fe010SChris Lattner     return getPointerToFunction(F);
507996fe010SChris Lattner 
50879876f52SReid Spencer   MutexGuard locked(lock);
509868e3f09SDaniel Dunbar   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
510868e3f09SDaniel Dunbar     return P;
51169e84901SJeff Cohen 
51269e84901SJeff Cohen   // Global variable might have been added since interpreter started.
51369e84901SJeff Cohen   if (GlobalVariable *GVar =
51469e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
51569e84901SJeff Cohen     EmitGlobalVariable(GVar);
51669e84901SJeff Cohen   else
517fbcc663cSTorok Edwin     llvm_unreachable("Global hasn't had an address allocated yet!");
518868e3f09SDaniel Dunbar 
519d0fc8f80SJeffrey Yasskin   return EEState.getGlobalAddressMap(locked)[GV];
520996fe010SChris Lattner }
521996fe010SChris Lattner 
522868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of
523868e3f09SDaniel Dunbar /// ConstantExpr values.
524996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
5256c38f0bbSReid Spencer   // If its undefined, return the garbage.
526bcbdbfb3SJay Foad   if (isa<UndefValue>(C)) {
527bcbdbfb3SJay Foad     GenericValue Result;
528bcbdbfb3SJay Foad     switch (C->getType()->getTypeID()) {
529bcbdbfb3SJay Foad     case Type::IntegerTyID:
530bcbdbfb3SJay Foad     case Type::X86_FP80TyID:
531bcbdbfb3SJay Foad     case Type::FP128TyID:
532bcbdbfb3SJay Foad     case Type::PPC_FP128TyID:
533bcbdbfb3SJay Foad       // Although the value is undefined, we still have to construct an APInt
534bcbdbfb3SJay Foad       // with the correct bit width.
535bcbdbfb3SJay Foad       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
536bcbdbfb3SJay Foad       break;
537bcbdbfb3SJay Foad     default:
538bcbdbfb3SJay Foad       break;
539bcbdbfb3SJay Foad     }
540bcbdbfb3SJay Foad     return Result;
541bcbdbfb3SJay Foad   }
5429de0d14dSChris Lattner 
543868e3f09SDaniel Dunbar   // Otherwise, if the value is a ConstantExpr...
5446c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5454fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
5469de0d14dSChris Lattner     switch (CE->getOpcode()) {
5479de0d14dSChris Lattner     case Instruction::GetElementPtr: {
5486c38f0bbSReid Spencer       // Compute the index
5494fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
550c44bd78aSChris Lattner       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
5519de0d14dSChris Lattner       uint64_t Offset =
5524fd528f2SReid Spencer         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
5539de0d14dSChris Lattner 
55487aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
55587aa65f4SReid Spencer       Result = PTOGV(tmp + Offset);
5569de0d14dSChris Lattner       return Result;
5579de0d14dSChris Lattner     }
5584fd528f2SReid Spencer     case Instruction::Trunc: {
5594fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5604fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5614fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
5624fd528f2SReid Spencer       return GV;
5634fd528f2SReid Spencer     }
5644fd528f2SReid Spencer     case Instruction::ZExt: {
5654fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5664fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5674fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
5684fd528f2SReid Spencer       return GV;
5694fd528f2SReid Spencer     }
5704fd528f2SReid Spencer     case Instruction::SExt: {
5714fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5724fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5734fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
5744fd528f2SReid Spencer       return GV;
5754fd528f2SReid Spencer     }
5764fd528f2SReid Spencer     case Instruction::FPTrunc: {
577a1336cf5SDale Johannesen       // FIXME long double
5784fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5794fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
5804fd528f2SReid Spencer       return GV;
5814fd528f2SReid Spencer     }
5824fd528f2SReid Spencer     case Instruction::FPExt:{
583a1336cf5SDale Johannesen       // FIXME long double
5844fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5854fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
5864fd528f2SReid Spencer       return GV;
5874fd528f2SReid Spencer     }
5884fd528f2SReid Spencer     case Instruction::UIToFP: {
5894fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
590fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
5914fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
592fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
5934fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
594fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
59531920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
596ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
597ca24fd90SDan Gohman                                    false,
5989150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
59954306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
600a1336cf5SDale Johannesen       }
6014fd528f2SReid Spencer       return GV;
6024fd528f2SReid Spencer     }
6034fd528f2SReid Spencer     case Instruction::SIToFP: {
6044fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
605fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6064fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
607fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6084fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
609fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
61031920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
611ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
612ca24fd90SDan Gohman                                    true,
6139150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
61454306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
615a1336cf5SDale Johannesen       }
6164fd528f2SReid Spencer       return GV;
6174fd528f2SReid Spencer     }
6184fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
6194fd528f2SReid Spencer     case Instruction::FPToSI: {
6204fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6214fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
622fdd87907SChris Lattner       if (Op0->getType()->isFloatTy())
6234fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
624fdd87907SChris Lattner       else if (Op0->getType()->isDoubleTy())
6254fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
626fdd87907SChris Lattner       else if (Op0->getType()->isX86_FP80Ty()) {
627a1336cf5SDale Johannesen         APFloat apf = APFloat(GV.IntVal);
628a1336cf5SDale Johannesen         uint64_t v;
6294f0bd68cSDale Johannesen         bool ignored;
630a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
631a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
6324f0bd68cSDale Johannesen                                    APFloat::rmTowardZero, &ignored);
633a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
634a1336cf5SDale Johannesen       }
6354fd528f2SReid Spencer       return GV;
6364fd528f2SReid Spencer     }
6376c38f0bbSReid Spencer     case Instruction::PtrToInt: {
6384fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6394fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
6404fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
6414fd528f2SReid Spencer       return GV;
6424fd528f2SReid Spencer     }
6434fd528f2SReid Spencer     case Instruction::IntToPtr: {
6444fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6454fd528f2SReid Spencer       uint32_t PtrWidth = TD->getPointerSizeInBits();
6464fd528f2SReid Spencer       if (PtrWidth != GV.IntVal.getBitWidth())
6474fd528f2SReid Spencer         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
6484fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
6494fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
6506c38f0bbSReid Spencer       return GV;
6516c38f0bbSReid Spencer     }
6526c38f0bbSReid Spencer     case Instruction::BitCast: {
6534fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6544fd528f2SReid Spencer       const Type* DestTy = CE->getType();
6554fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
656fbcc663cSTorok Edwin         default: llvm_unreachable("Invalid bitcast operand");
6574fd528f2SReid Spencer         case Type::IntegerTyID:
6589dff9becSDuncan Sands           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
659fdd87907SChris Lattner           if (DestTy->isFloatTy())
6604fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
661fdd87907SChris Lattner           else if (DestTy->isDoubleTy())
6624fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
6636c38f0bbSReid Spencer           break;
6644fd528f2SReid Spencer         case Type::FloatTyID:
6659dff9becSDuncan Sands           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
6663447fb01SJay Foad           GV.IntVal = APInt::floatToBits(GV.FloatVal);
6674fd528f2SReid Spencer           break;
6684fd528f2SReid Spencer         case Type::DoubleTyID:
6699dff9becSDuncan Sands           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
6703447fb01SJay Foad           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
6714fd528f2SReid Spencer           break;
6724fd528f2SReid Spencer         case Type::PointerTyID:
67319d0b47bSDuncan Sands           assert(DestTy->isPointerTy() && "Invalid bitcast");
6744fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
6756c38f0bbSReid Spencer       }
6764fd528f2SReid Spencer       return GV;
67768cbcc3eSChris Lattner     }
67868cbcc3eSChris Lattner     case Instruction::Add:
679a5b9645cSDan Gohman     case Instruction::FAdd:
6804fd528f2SReid Spencer     case Instruction::Sub:
681a5b9645cSDan Gohman     case Instruction::FSub:
6824fd528f2SReid Spencer     case Instruction::Mul:
683a5b9645cSDan Gohman     case Instruction::FMul:
6844fd528f2SReid Spencer     case Instruction::UDiv:
6854fd528f2SReid Spencer     case Instruction::SDiv:
6864fd528f2SReid Spencer     case Instruction::URem:
6874fd528f2SReid Spencer     case Instruction::SRem:
6884fd528f2SReid Spencer     case Instruction::And:
6894fd528f2SReid Spencer     case Instruction::Or:
6904fd528f2SReid Spencer     case Instruction::Xor: {
6914fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
6924fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
6934fd528f2SReid Spencer       GenericValue GV;
694c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
695fbcc663cSTorok Edwin       default: llvm_unreachable("Bad add type!");
6967a9c62baSReid Spencer       case Type::IntegerTyID:
6974fd528f2SReid Spencer         switch (CE->getOpcode()) {
698fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid integer opcode");
6994fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
7004fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
7014fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
7024fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
7034fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
7044fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
7054fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
7064fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
7074fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
7084fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
7094fd528f2SReid Spencer         }
710c4e6bb5fSChris Lattner         break;
711c4e6bb5fSChris Lattner       case Type::FloatTyID:
7124fd528f2SReid Spencer         switch (CE->getOpcode()) {
713fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid float opcode");
714a5b9645cSDan Gohman           case Instruction::FAdd:
7154fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
716a5b9645cSDan Gohman           case Instruction::FSub:
7174fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
718a5b9645cSDan Gohman           case Instruction::FMul:
7194fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
7204fd528f2SReid Spencer           case Instruction::FDiv:
7214fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
7224fd528f2SReid Spencer           case Instruction::FRem:
72393cd0f1cSChris Lattner             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
7244fd528f2SReid Spencer         }
725c4e6bb5fSChris Lattner         break;
726c4e6bb5fSChris Lattner       case Type::DoubleTyID:
7274fd528f2SReid Spencer         switch (CE->getOpcode()) {
728fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid double opcode");
729a5b9645cSDan Gohman           case Instruction::FAdd:
7304fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
731a5b9645cSDan Gohman           case Instruction::FSub:
7324fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
733a5b9645cSDan Gohman           case Instruction::FMul:
7344fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
7354fd528f2SReid Spencer           case Instruction::FDiv:
7364fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
7374fd528f2SReid Spencer           case Instruction::FRem:
73893cd0f1cSChris Lattner             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
7394fd528f2SReid Spencer         }
740c4e6bb5fSChris Lattner         break;
741a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
742a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
743a1336cf5SDale Johannesen       case Type::FP128TyID: {
744a1336cf5SDale Johannesen         APFloat apfLHS = APFloat(LHS.IntVal);
745a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
746e4f47434SDaniel Dunbar           default: llvm_unreachable("Invalid long double opcode");
747a5b9645cSDan Gohman           case Instruction::FAdd:
748a1336cf5SDale Johannesen             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
74954306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
750a1336cf5SDale Johannesen             break;
751a5b9645cSDan Gohman           case Instruction::FSub:
752a1336cf5SDale Johannesen             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
75354306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
754a1336cf5SDale Johannesen             break;
755a5b9645cSDan Gohman           case Instruction::FMul:
756a1336cf5SDale Johannesen             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
75754306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
758a1336cf5SDale Johannesen             break;
759a1336cf5SDale Johannesen           case Instruction::FDiv:
760a1336cf5SDale Johannesen             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
76154306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
762a1336cf5SDale Johannesen             break;
763a1336cf5SDale Johannesen           case Instruction::FRem:
764a1336cf5SDale Johannesen             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
76554306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
766a1336cf5SDale Johannesen             break;
767a1336cf5SDale Johannesen           }
768a1336cf5SDale Johannesen         }
769a1336cf5SDale Johannesen         break;
770c4e6bb5fSChris Lattner       }
7714fd528f2SReid Spencer       return GV;
7724fd528f2SReid Spencer     }
7739de0d14dSChris Lattner     default:
77468cbcc3eSChris Lattner       break;
77568cbcc3eSChris Lattner     }
776868e3f09SDaniel Dunbar 
777868e3f09SDaniel Dunbar     SmallString<256> Msg;
778868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
779868e3f09SDaniel Dunbar     OS << "ConstantExpr not handled: " << *CE;
780868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
7819de0d14dSChris Lattner   }
782996fe010SChris Lattner 
783868e3f09SDaniel Dunbar   // Otherwise, we have a simple constant.
7844fd528f2SReid Spencer   GenericValue Result;
7856b727599SChris Lattner   switch (C->getType()->getTypeID()) {
78687aa65f4SReid Spencer   case Type::FloatTyID:
787bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
7887a9c62baSReid Spencer     break;
78987aa65f4SReid Spencer   case Type::DoubleTyID:
790bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
79187aa65f4SReid Spencer     break;
792a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
793a1336cf5SDale Johannesen   case Type::FP128TyID:
794a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
79554306fe4SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
796a1336cf5SDale Johannesen     break;
79787aa65f4SReid Spencer   case Type::IntegerTyID:
79887aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
79987aa65f4SReid Spencer     break;
800996fe010SChris Lattner   case Type::PointerTyID:
8016a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
802996fe010SChris Lattner       Result.PointerVal = 0;
8036a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
8046a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
8056a0fd73bSReid Spencer     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
8066a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
8070c778f70SChris Lattner     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
8080c778f70SChris Lattner       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
8090c778f70SChris Lattner                                                         BA->getBasicBlock())));
810e6492f10SChris Lattner     else
811fbcc663cSTorok Edwin       llvm_unreachable("Unknown constant pointer type!");
812996fe010SChris Lattner     break;
813996fe010SChris Lattner   default:
814868e3f09SDaniel Dunbar     SmallString<256> Msg;
815868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
816868e3f09SDaniel Dunbar     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
817868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
818996fe010SChris Lattner   }
819868e3f09SDaniel Dunbar 
820996fe010SChris Lattner   return Result;
821996fe010SChris Lattner }
822996fe010SChris Lattner 
8231202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
8241202d1b1SDuncan Sands /// with the integer held in IntVal.
8251202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
8261202d1b1SDuncan Sands                              unsigned StoreBytes) {
8271202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
8281202d1b1SDuncan Sands   uint8_t *Src = (uint8_t *)IntVal.getRawData();
8295c65cb46SDuncan Sands 
830868e3f09SDaniel Dunbar   if (sys::isLittleEndianHost()) {
8311202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
8321202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
8335c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
834868e3f09SDaniel Dunbar   } else {
8355c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
8361202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
8371202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
8385c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
8395c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
8405c65cb46SDuncan Sands       // May not be aligned so use memcpy.
8415c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
8425c65cb46SDuncan Sands       Src += sizeof(uint64_t);
8435c65cb46SDuncan Sands     }
8445c65cb46SDuncan Sands 
8455c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
846815f8dd2SReid Spencer   }
8477a9c62baSReid Spencer }
8481202d1b1SDuncan Sands 
84909053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
85009053e62SEvan Cheng                                          GenericValue *Ptr, const Type *Ty) {
8511202d1b1SDuncan Sands   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
8521202d1b1SDuncan Sands 
8531202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
8541202d1b1SDuncan Sands   case Type::IntegerTyID:
8551202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
8561202d1b1SDuncan Sands     break;
857996fe010SChris Lattner   case Type::FloatTyID:
85887aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
85987aa65f4SReid Spencer     break;
86087aa65f4SReid Spencer   case Type::DoubleTyID:
86187aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
862996fe010SChris Lattner     break;
8634d7e4ee7SDale Johannesen   case Type::X86_FP80TyID:
8644d7e4ee7SDale Johannesen     memcpy(Ptr, Val.IntVal.getRawData(), 10);
865a1336cf5SDale Johannesen     break;
8667a9c62baSReid Spencer   case Type::PointerTyID:
8671202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
8681202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
86993da3c82SChandler Carruth       memset(&(Ptr->PointerVal), 0, StoreBytes);
8701202d1b1SDuncan Sands 
87187aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
872996fe010SChris Lattner     break;
873996fe010SChris Lattner   default:
8740967d2dfSDavid Greene     dbgs() << "Cannot store value of type " << *Ty << "!\n";
875996fe010SChris Lattner   }
8761202d1b1SDuncan Sands 
877aa121227SChris Lattner   if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
8781202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
8791202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
880996fe010SChris Lattner }
881996fe010SChris Lattner 
8821202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
8831202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
8841202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
8851202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
8861202d1b1SDuncan Sands   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
8875c65cb46SDuncan Sands 
888aa121227SChris Lattner   if (sys::isLittleEndianHost())
8895c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
8905c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
8915c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
8925c65cb46SDuncan Sands   else {
8935c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
8945c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
8955c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
8965c65cb46SDuncan Sands     // a word.
8975c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
8985c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
8995c65cb46SDuncan Sands       // May not be aligned so use memcpy.
9005c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
9015c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
9025c65cb46SDuncan Sands     }
9035c65cb46SDuncan Sands 
9045c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
9055c65cb46SDuncan Sands   }
9067a9c62baSReid Spencer }
9071202d1b1SDuncan Sands 
9081202d1b1SDuncan Sands /// FIXME: document
9091202d1b1SDuncan Sands ///
9101202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
9111202d1b1SDuncan Sands                                           GenericValue *Ptr,
9121202d1b1SDuncan Sands                                           const Type *Ty) {
9131202d1b1SDuncan Sands   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
9141202d1b1SDuncan Sands 
9151202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
9161202d1b1SDuncan Sands   case Type::IntegerTyID:
9171202d1b1SDuncan Sands     // An APInt with all words initially zero.
9181202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
9191202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
9201202d1b1SDuncan Sands     break;
9217f389e8cSChris Lattner   case Type::FloatTyID:
92287aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
92387aa65f4SReid Spencer     break;
92487aa65f4SReid Spencer   case Type::DoubleTyID:
92587aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
9267f389e8cSChris Lattner     break;
9277a9c62baSReid Spencer   case Type::PointerTyID:
92887aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
9297f389e8cSChris Lattner     break;
930a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
931a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
93226d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
933ff306287SDuncan Sands     uint64_t y[2];
9344d7e4ee7SDale Johannesen     memcpy(y, Ptr, 10);
935ff306287SDuncan Sands     Result.IntVal = APInt(80, 2, y);
936a1336cf5SDale Johannesen     break;
937a1336cf5SDale Johannesen   }
9387f389e8cSChris Lattner   default:
939868e3f09SDaniel Dunbar     SmallString<256> Msg;
940868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
941868e3f09SDaniel Dunbar     OS << "Cannot load value of type " << *Ty << "!";
942868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
9437f389e8cSChris Lattner   }
9447f389e8cSChris Lattner }
9457f389e8cSChris Lattner 
946996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
9470967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
948b086d382SDale Johannesen   DEBUG(Init->dump());
94961753bf8SChris Lattner   if (isa<UndefValue>(Init)) {
95061753bf8SChris Lattner     return;
951d84d35baSReid Spencer   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
95269d62138SRobert Bocchino     unsigned ElementSize =
953af9eaa83SDuncan Sands       getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
95469d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
95569d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
95669d62138SRobert Bocchino     return;
9571dd86b11SChris Lattner   } else if (isa<ConstantAggregateZero>(Init)) {
958af9eaa83SDuncan Sands     memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
9591dd86b11SChris Lattner     return;
96069ddfbfeSDan Gohman   } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
96169ddfbfeSDan Gohman     unsigned ElementSize =
962af9eaa83SDuncan Sands       getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
96369ddfbfeSDan Gohman     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
96469ddfbfeSDan Gohman       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
96569ddfbfeSDan Gohman     return;
96669ddfbfeSDan Gohman   } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
96769ddfbfeSDan Gohman     const StructLayout *SL =
96869ddfbfeSDan Gohman       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
96969ddfbfeSDan Gohman     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
97069ddfbfeSDan Gohman       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
97169ddfbfeSDan Gohman     return;
97261753bf8SChris Lattner   } else if (Init->getType()->isFirstClassType()) {
973996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
974996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
975996fe010SChris Lattner     return;
976996fe010SChris Lattner   }
977996fe010SChris Lattner 
978868e3f09SDaniel Dunbar   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
979fbcc663cSTorok Edwin   llvm_unreachable("Unknown constant type to initialize memory with!");
980996fe010SChris Lattner }
981996fe010SChris Lattner 
982996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
983996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
984996fe010SChris Lattner /// their initializers into the memory.
985996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
986996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
9870621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
9880621caefSChris Lattner   // to figure out how the different modules should link together.
9890621caefSChris Lattner   std::map<std::pair<std::string, const Type*>,
9900621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
9910621caefSChris Lattner 
9920621caefSChris Lattner   if (Modules.size() != 1) {
9930621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
994091217beSJeffrey Yasskin       Module &M = *Modules[m];
9950621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
9960621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
9970621caefSChris Lattner         const GlobalValue *GV = I;
9986de96a1bSRafael Espindola         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
9990621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
10000621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
10010621caefSChris Lattner 
10020621caefSChris Lattner         const GlobalValue *&GVEntry =
10030621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
10040621caefSChris Lattner 
10050621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
10060621caefSChris Lattner         // version.
10070621caefSChris Lattner         if (!GVEntry) {
10080621caefSChris Lattner           GVEntry = GV;
10090621caefSChris Lattner           continue;
10100621caefSChris Lattner         }
10110621caefSChris Lattner 
10120621caefSChris Lattner         // If the existing global is strong, never replace it.
1013d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
1014d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
1015d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
10160621caefSChris Lattner           continue;
10170621caefSChris Lattner 
10180621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1019ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
102012c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
10210621caefSChris Lattner           GVEntry = GV;
10220621caefSChris Lattner       }
10230621caefSChris Lattner     }
10240621caefSChris Lattner   }
10250621caefSChris Lattner 
10260621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
10270621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1028091217beSJeffrey Yasskin     Module &M = *Modules[m];
10298ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
10300621caefSChris Lattner          I != E; ++I) {
10310621caefSChris Lattner       // In the multi-module case, see what this global maps to.
10320621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
10330621caefSChris Lattner         if (const GlobalValue *GVEntry =
10340621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
10350621caefSChris Lattner           // If something else is the canonical global, ignore this one.
10360621caefSChris Lattner           if (GVEntry != &*I) {
10370621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
10380621caefSChris Lattner             continue;
10390621caefSChris Lattner           }
10400621caefSChris Lattner         }
10410621caefSChris Lattner       }
10420621caefSChris Lattner 
10435301e7c6SReid Spencer       if (!I->isDeclaration()) {
10445457ce9aSNicolas Geoffray         addGlobalMapping(I, getMemoryForGV(I));
1045996fe010SChris Lattner       } else {
1046e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
1047e8bbcfc2SBrian Gaeke         // get a pointer to it.
10480621caefSChris Lattner         if (void *SymAddr =
10495899e340SDaniel Dunbar             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1050748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
10519de0d14dSChris Lattner         else {
10522104b8d3SChris Lattner           report_fatal_error("Could not resolve external global address: "
10536c2d233eSTorok Edwin                             +I->getName());
10549de0d14dSChris Lattner         }
1055996fe010SChris Lattner       }
10560621caefSChris Lattner     }
10570621caefSChris Lattner 
10580621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
10590621caefSChris Lattner     // canonical location.
10600621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
10610621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
10620621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
10630621caefSChris Lattner         const GlobalValue *CGV =
10640621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
10650621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
10660621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
1067a67f06b9SNuno Lopes         addGlobalMapping(GV, Ptr);
10680621caefSChris Lattner       }
10690621caefSChris Lattner     }
1070996fe010SChris Lattner 
10717a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
10727a9c62baSReid Spencer     // and initialize their contents.
10738ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
10740621caefSChris Lattner          I != E; ++I) {
10755301e7c6SReid Spencer       if (!I->isDeclaration()) {
10760621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
10770621caefSChris Lattner           if (const GlobalValue *GVEntry =
10780621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
10790621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
10800621caefSChris Lattner               continue;
10810621caefSChris Lattner         }
10826bbe3eceSChris Lattner         EmitGlobalVariable(I);
10836bbe3eceSChris Lattner       }
10840621caefSChris Lattner     }
10850621caefSChris Lattner   }
10860621caefSChris Lattner }
10876bbe3eceSChris Lattner 
10886bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
10896bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
10906bbe3eceSChris Lattner // already in the map.
1091fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1092748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
1093dc631735SChris Lattner 
10946bbe3eceSChris Lattner   if (GA == 0) {
10956bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
10965457ce9aSNicolas Geoffray     GA = getMemoryForGV(GV);
1097748e8579SChris Lattner     addGlobalMapping(GV, GA);
10986bbe3eceSChris Lattner   }
1099fbcc0aa1SChris Lattner 
11005457ce9aSNicolas Geoffray   // Don't initialize if it's thread local, let the client do it.
11015457ce9aSNicolas Geoffray   if (!GV->isThreadLocal())
11026bbe3eceSChris Lattner     InitializeMemory(GV->getInitializer(), GA);
11035457ce9aSNicolas Geoffray 
11045457ce9aSNicolas Geoffray   const Type *ElTy = GV->getType()->getElementType();
1105af9eaa83SDuncan Sands   size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1106df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
11076bbe3eceSChris Lattner   ++NumGlobals;
1108996fe010SChris Lattner }
1109f98e981cSJeffrey Yasskin 
1110d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1111d0fc8f80SJeffrey Yasskin   : EE(EE), GlobalAddressMap(this) {
1112f98e981cSJeffrey Yasskin }
1113f98e981cSJeffrey Yasskin 
1114868e3f09SDaniel Dunbar sys::Mutex *
1115868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1116d0fc8f80SJeffrey Yasskin   return &EES->EE.lock;
1117d0fc8f80SJeffrey Yasskin }
1118868e3f09SDaniel Dunbar 
1119868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1120868e3f09SDaniel Dunbar                                                       const GlobalValue *Old) {
1121d0fc8f80SJeffrey Yasskin   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1122d0fc8f80SJeffrey Yasskin   EES->GlobalAddressReverseMap.erase(OldVal);
1123d0fc8f80SJeffrey Yasskin }
1124d0fc8f80SJeffrey Yasskin 
1125868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1126868e3f09SDaniel Dunbar                                                     const GlobalValue *,
1127868e3f09SDaniel Dunbar                                                     const GlobalValue *) {
1128f98e981cSJeffrey Yasskin   assert(false && "The ExecutionEngine doesn't know how to handle a"
1129f98e981cSJeffrey Yasskin          " RAUW on a value it has a global mapping for.");
1130f98e981cSJeffrey Yasskin }
1131