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 
156bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h"
16868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h"
17390d78b3SChris Lattner #include "llvm/ADT/Statistic.h"
18ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h"
198a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/JITMemoryManager.h"
208a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/ObjectCache.h"
219fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
229fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
239fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
249fb823bbSChandler Carruth #include "llvm/IR/Module.h"
259fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
264220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
2735907d8eSDavid Blaikie #include "llvm/Object/ObjectFile.h"
287c16caa3SReid Spencer #include "llvm/Support/Debug.h"
29ed0881b2SChandler Carruth #include "llvm/Support/DynamicLibrary.h"
306c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h"
31ed0881b2SChandler Carruth #include "llvm/Support/Host.h"
326d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
33ed0881b2SChandler Carruth #include "llvm/Support/TargetRegistry.h"
34ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h"
358418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h"
36579f0713SAnton Korobeynikov #include <cmath>
37579f0713SAnton Korobeynikov #include <cstring>
3829681deeSChris Lattner using namespace llvm;
39996fe010SChris Lattner 
40f58e376dSChandler Carruth #define DEBUG_TYPE "jit"
41f58e376dSChandler Carruth 
42c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
44996fe010SChris Lattner 
45d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
46d12ccbd3SJuergen Ributzka void ObjectCache::anchor() {}
47d12ccbd3SJuergen Ributzka void ObjectBuffer::anchor() {}
48d12ccbd3SJuergen Ributzka void ObjectBufferStream::anchor() {}
49d12ccbd3SJuergen Ributzka 
5031faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)(
5131faefffSJeffrey Yasskin   Module *M,
52fc8a2d5aSReid Kleckner   std::string *ErrorStr,
53fc8a2d5aSReid Kleckner   JITMemoryManager *JMM,
54700d08e1SEric Christopher   bool GVsWithCode,
552617dcceSCraig Topper   TargetMachine *TM) = nullptr;
5670ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
5770ff8b05SDaniel Dunbar   Module *M,
5870ff8b05SDaniel Dunbar   std::string *ErrorStr,
599bc53e84SFilip Pizlo   RTDyldMemoryManager *MCJMM,
6070ff8b05SDaniel Dunbar   bool GVsWithCode,
612617dcceSCraig Topper   TargetMachine *TM) = nullptr;
62091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
632617dcceSCraig Topper                                                 std::string *ErrorStr) =nullptr;
642d52c1b8SChris Lattner 
65091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M)
66f98e981cSJeffrey Yasskin   : EEState(*this),
672617dcceSCraig Topper     LazyFunctionCreator(nullptr) {
684567db45SJeffrey Yasskin   CompilingLazily         = false;
69cdc0060eSEvan Cheng   GVCompilationDisabled   = false;
7084a9055eSEvan Cheng   SymbolSearchingDisabled = false;
71bc876017SLang Hames 
72bc876017SLang Hames   // IR module verification is enabled by default in debug builds, and disabled
73bc876017SLang Hames   // by default in release builds.
74bc876017SLang Hames #ifndef NDEBUG
75bc876017SLang Hames   VerifyModules = true;
76bc876017SLang Hames #else
77bc876017SLang Hames   VerifyModules = false;
78bc876017SLang Hames #endif
79bc876017SLang Hames 
80091217beSJeffrey Yasskin   Modules.push_back(M);
81091217beSJeffrey Yasskin   assert(M && "Module is null?");
82260b0c88SMisha Brukman }
83260b0c88SMisha Brukman 
8492f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
85603682adSReid Spencer   clearAllGlobalMappings();
860621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
870621caefSChris Lattner     delete Modules[i];
8892f8b30dSBrian Gaeke }
8992f8b30dSBrian Gaeke 
90a4044332SJeffrey Yasskin namespace {
91868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the
92868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed.
93a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH {
94a4044332SJeffrey Yasskin   GVMemoryBlock(const GlobalVariable *GV)
95a4044332SJeffrey Yasskin     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96a4044332SJeffrey Yasskin 
97a4044332SJeffrey Yasskin public:
98868e3f09SDaniel Dunbar   /// \brief Returns the address the GlobalVariable should be written into.  The
99868e3f09SDaniel Dunbar   /// GVMemoryBlock object prefixes that.
100cdfe20b9SMicah Villmow   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
101229907cdSChris Lattner     Type *ElTy = GV->getType()->getElementType();
102a4044332SJeffrey Yasskin     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103a4044332SJeffrey Yasskin     void *RawMemory = ::operator new(
104cdfe20b9SMicah Villmow       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
105a4044332SJeffrey Yasskin                                    TD.getPreferredAlignment(GV))
106a4044332SJeffrey Yasskin       + GVSize);
107a4044332SJeffrey Yasskin     new(RawMemory) GVMemoryBlock(GV);
108a4044332SJeffrey Yasskin     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109a4044332SJeffrey Yasskin   }
110a4044332SJeffrey Yasskin 
111b51ff603SCraig Topper   void deleted() override {
112a4044332SJeffrey Yasskin     // We allocated with operator new and with some extra memory hanging off the
113a4044332SJeffrey Yasskin     // end, so don't just delete this.  I'm not sure if this is actually
114a4044332SJeffrey Yasskin     // required.
115a4044332SJeffrey Yasskin     this->~GVMemoryBlock();
116a4044332SJeffrey Yasskin     ::operator delete(this);
117a4044332SJeffrey Yasskin   }
118a4044332SJeffrey Yasskin };
119a4044332SJeffrey Yasskin }  // anonymous namespace
120a4044332SJeffrey Yasskin 
121a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
122cdfe20b9SMicah Villmow   return GVMemoryBlock::Create(GV, *getDataLayout());
1235457ce9aSNicolas Geoffray }
1245457ce9aSNicolas Geoffray 
12535907d8eSDavid Blaikie void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
12635907d8eSDavid Blaikie   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
12735907d8eSDavid Blaikie }
12835907d8eSDavid Blaikie 
129091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) {
130af0dea13SCraig Topper   for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
131324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
132091217beSJeffrey Yasskin     Module *Found = *I;
133091217beSJeffrey Yasskin     if (Found == M) {
134324fe890SDevang Patel       Modules.erase(I);
135091217beSJeffrey Yasskin       clearGlobalMappingsFromModule(M);
136091217beSJeffrey Yasskin       return true;
137324fe890SDevang Patel     }
138324fe890SDevang Patel   }
139091217beSJeffrey Yasskin   return false;
140617001d8SNate Begeman }
141617001d8SNate Begeman 
1420621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
1430621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
144091217beSJeffrey Yasskin     if (Function *F = Modules[i]->getFunction(FnName))
1450621caefSChris Lattner       return F;
1460621caefSChris Lattner   }
1472617dcceSCraig Topper   return nullptr;
1480621caefSChris Lattner }
1490621caefSChris Lattner 
1500621caefSChris Lattner 
151868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
152868e3f09SDaniel Dunbar                                           const GlobalValue *ToUnmap) {
153d0fc8f80SJeffrey Yasskin   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
154307c053fSJeffrey Yasskin   void *OldVal;
155868e3f09SDaniel Dunbar 
156868e3f09SDaniel Dunbar   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
157868e3f09SDaniel Dunbar   // GlobalAddressMap.
158307c053fSJeffrey Yasskin   if (I == GlobalAddressMap.end())
1592617dcceSCraig Topper     OldVal = nullptr;
160307c053fSJeffrey Yasskin   else {
161307c053fSJeffrey Yasskin     OldVal = I->second;
162307c053fSJeffrey Yasskin     GlobalAddressMap.erase(I);
163307c053fSJeffrey Yasskin   }
164307c053fSJeffrey Yasskin 
165307c053fSJeffrey Yasskin   GlobalAddressReverseMap.erase(OldVal);
166307c053fSJeffrey Yasskin   return OldVal;
167307c053fSJeffrey Yasskin }
168307c053fSJeffrey Yasskin 
1696d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
1706d8dd189SChris Lattner   MutexGuard locked(lock);
1716d8dd189SChris Lattner 
1720967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
1739813b0b0SDaniel Dunbar         << "\' to [" << Addr << "]\n";);
174d0fc8f80SJeffrey Yasskin   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
1752617dcceSCraig Topper   assert((!CurVal || !Addr) && "GlobalMapping already established!");
1766d8dd189SChris Lattner   CurVal = Addr;
1776d8dd189SChris Lattner 
178868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
179f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
1806bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
181f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
1822617dcceSCraig Topper     assert((!V || !GV) && "GlobalMapping already established!");
1836d8dd189SChris Lattner     V = GV;
1846d8dd189SChris Lattner   }
1856d8dd189SChris Lattner }
1866d8dd189SChris Lattner 
1876d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1886d8dd189SChris Lattner   MutexGuard locked(lock);
1896d8dd189SChris Lattner 
190f98e981cSJeffrey Yasskin   EEState.getGlobalAddressMap(locked).clear();
191f98e981cSJeffrey Yasskin   EEState.getGlobalAddressReverseMap(locked).clear();
1926d8dd189SChris Lattner }
1936d8dd189SChris Lattner 
1948f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
1958f83fc4dSNate Begeman   MutexGuard locked(lock);
1968f83fc4dSNate Begeman 
197868e3f09SDaniel Dunbar   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
198f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, FI);
1998f83fc4dSNate Begeman   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
200868e3f09SDaniel Dunbar        GI != GE; ++GI)
201f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, GI);
2028f83fc4dSNate Begeman }
2038f83fc4dSNate Begeman 
204ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
2056d8dd189SChris Lattner   MutexGuard locked(lock);
2066d8dd189SChris Lattner 
207d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy &Map =
208f98e981cSJeffrey Yasskin     EEState.getGlobalAddressMap(locked);
209ee181730SChris Lattner 
2106d8dd189SChris Lattner   // Deleting from the mapping?
2112617dcceSCraig Topper   if (!Addr)
212f98e981cSJeffrey Yasskin     return EEState.RemoveMapping(locked, GV);
213ee181730SChris Lattner 
214d0fc8f80SJeffrey Yasskin   void *&CurVal = Map[GV];
215ee181730SChris Lattner   void *OldVal = CurVal;
216ee181730SChris Lattner 
217f98e981cSJeffrey Yasskin   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
218f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
2196d8dd189SChris Lattner   CurVal = Addr;
2206d8dd189SChris Lattner 
221868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
222f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
2236bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
224f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
2252617dcceSCraig Topper     assert((!V || !GV) && "GlobalMapping already established!");
2266d8dd189SChris Lattner     V = GV;
2276d8dd189SChris Lattner   }
228ee181730SChris Lattner   return OldVal;
2296d8dd189SChris Lattner }
2306d8dd189SChris Lattner 
2316d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
2326d8dd189SChris Lattner   MutexGuard locked(lock);
2336d8dd189SChris Lattner 
234d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy::iterator I =
235d0fc8f80SJeffrey Yasskin     EEState.getGlobalAddressMap(locked).find(GV);
2362617dcceSCraig Topper   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
2376d8dd189SChris Lattner }
2386d8dd189SChris Lattner 
239748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
24079876f52SReid Spencer   MutexGuard locked(lock);
24179876f52SReid Spencer 
242748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
243f98e981cSJeffrey Yasskin   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
244d0fc8f80SJeffrey Yasskin     for (ExecutionEngineState::GlobalAddressMapTy::iterator
245f98e981cSJeffrey Yasskin          I = EEState.getGlobalAddressMap(locked).begin(),
246f98e981cSJeffrey Yasskin          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
247e4f47434SDaniel Dunbar       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
248e4f47434SDaniel Dunbar                                                           I->second, I->first));
249748e8579SChris Lattner   }
250748e8579SChris Lattner 
2516bf87df5SJeffrey Yasskin   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
252f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).find(Addr);
2532617dcceSCraig Topper   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
254748e8579SChris Lattner }
2555a0d4829SChris Lattner 
256bfd38abbSJeffrey Yasskin namespace {
257bfd38abbSJeffrey Yasskin class ArgvArray {
258bfd38abbSJeffrey Yasskin   char *Array;
259bfd38abbSJeffrey Yasskin   std::vector<char*> Values;
260bfd38abbSJeffrey Yasskin public:
2612617dcceSCraig Topper   ArgvArray() : Array(nullptr) {}
262bfd38abbSJeffrey Yasskin   ~ArgvArray() { clear(); }
263bfd38abbSJeffrey Yasskin   void clear() {
264bfd38abbSJeffrey Yasskin     delete[] Array;
2652617dcceSCraig Topper     Array = nullptr;
266bfd38abbSJeffrey Yasskin     for (size_t I = 0, E = Values.size(); I != E; ++I) {
267bfd38abbSJeffrey Yasskin       delete[] Values[I];
268bfd38abbSJeffrey Yasskin     }
269bfd38abbSJeffrey Yasskin     Values.clear();
270bfd38abbSJeffrey Yasskin   }
271bfd38abbSJeffrey Yasskin   /// Turn a vector of strings into a nice argv style array of pointers to null
272bfd38abbSJeffrey Yasskin   /// terminated strings.
273bfd38abbSJeffrey Yasskin   void *reset(LLVMContext &C, ExecutionEngine *EE,
274bfd38abbSJeffrey Yasskin               const std::vector<std::string> &InputArgv);
275bfd38abbSJeffrey Yasskin };
276bfd38abbSJeffrey Yasskin }  // anonymous namespace
277bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
2785a0d4829SChris Lattner                        const std::vector<std::string> &InputArgv) {
279bfd38abbSJeffrey Yasskin   clear();  // Free the old contents.
2805da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
281bfd38abbSJeffrey Yasskin   Array = new char[(InputArgv.size()+1)*PtrSize];
2825a0d4829SChris Lattner 
283bfd38abbSJeffrey Yasskin   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
284229907cdSChris Lattner   Type *SBytePtr = Type::getInt8PtrTy(C);
2855a0d4829SChris Lattner 
2865a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
2875a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
2885a0d4829SChris Lattner     char *Dest = new char[Size];
289bfd38abbSJeffrey Yasskin     Values.push_back(Dest);
2900967d2dfSDavid Greene     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
2915a0d4829SChris Lattner 
2925a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
2935a0d4829SChris Lattner     Dest[Size-1] = 0;
2945a0d4829SChris Lattner 
295bfd38abbSJeffrey Yasskin     // Endian safe: Array[i] = (PointerTy)Dest;
296bfd38abbSJeffrey Yasskin     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
2975a0d4829SChris Lattner                            SBytePtr);
2985a0d4829SChris Lattner   }
2995a0d4829SChris Lattner 
3005a0d4829SChris Lattner   // Null terminate it
3012617dcceSCraig Topper   EE->StoreValueToMemory(PTOGV(nullptr),
302bfd38abbSJeffrey Yasskin                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
3035a0d4829SChris Lattner                          SBytePtr);
304bfd38abbSJeffrey Yasskin   return Array;
3055a0d4829SChris Lattner }
3065a0d4829SChris Lattner 
30741fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
30841fa2bd1SChris Lattner                                                        bool isDtors) {
309faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
3101a9a0b7bSEvan Cheng   GlobalVariable *GV = module->getNamedGlobal(Name);
311fe36eaebSChris Lattner 
312fe36eaebSChris Lattner   // If this global has internal linkage, or if it has a use, then it must be
313fe36eaebSChris Lattner   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
3140621caefSChris Lattner   // this is the case, don't execute any of the global ctors, __main will do
3150621caefSChris Lattner   // it.
3166de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
317faae50b6SChris Lattner 
3180cbfcb2bSNick Lewycky   // Should be an array of '{ i32, void ()* }' structs.  The first value is
3190621caefSChris Lattner   // the init priority, which we ignore.
32000245f42SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
3212617dcceSCraig Topper   if (!InitList)
3220f857898SNick Lewycky     return;
323868e3f09SDaniel Dunbar   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
32400245f42SChris Lattner     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
3252617dcceSCraig Topper     if (!CS) continue;
326faae50b6SChris Lattner 
327faae50b6SChris Lattner     Constant *FP = CS->getOperand(1);
328faae50b6SChris Lattner     if (FP->isNullValue())
3290f857898SNick Lewycky       continue;  // Found a sentinal value, ignore.
330faae50b6SChris Lattner 
331868e3f09SDaniel Dunbar     // Strip off constant expression casts.
332faae50b6SChris Lattner     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
3336c38f0bbSReid Spencer       if (CE->isCast())
334faae50b6SChris Lattner         FP = CE->getOperand(0);
335868e3f09SDaniel Dunbar 
336faae50b6SChris Lattner     // Execute the ctor/dtor function!
337868e3f09SDaniel Dunbar     if (Function *F = dyn_cast<Function>(FP))
338faae50b6SChris Lattner       runFunction(F, std::vector<GenericValue>());
339868e3f09SDaniel Dunbar 
340868e3f09SDaniel Dunbar     // FIXME: It is marginally lame that we just do nothing here if we see an
341868e3f09SDaniel Dunbar     // entry we don't recognize. It might not be unreasonable for the verifier
342868e3f09SDaniel Dunbar     // to not even allow this and just assert here.
343faae50b6SChris Lattner   }
344faae50b6SChris Lattner }
3451a9a0b7bSEvan Cheng 
3461a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
3471a9a0b7bSEvan Cheng   // Execute global ctors/dtors for each module in the program.
348868e3f09SDaniel Dunbar   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
349868e3f09SDaniel Dunbar     runStaticConstructorsDestructors(Modules[i], isDtors);
3500621caefSChris Lattner }
351faae50b6SChris Lattner 
352cf3e3017SDan Gohman #ifndef NDEBUG
3531202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
3541202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
3555da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
3561202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
3571202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
3581202d1b1SDuncan Sands       return false;
3591202d1b1SDuncan Sands   return true;
3601202d1b1SDuncan Sands }
361cf3e3017SDan Gohman #endif
3621202d1b1SDuncan Sands 
3635a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
3645a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
3655a0d4829SChris Lattner                                        const char * const * envp) {
3665a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
3675a0d4829SChris Lattner   GenericValue GVArgc;
36887aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
3698c32c111SAnton Korobeynikov 
3708c32c111SAnton Korobeynikov   // Check main() type
371b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
372229907cdSChris Lattner   FunctionType *FTy = Fn->getFunctionType();
373229907cdSChris Lattner   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
374868e3f09SDaniel Dunbar 
375868e3f09SDaniel Dunbar   // Check the argument types.
376868e3f09SDaniel Dunbar   if (NumArgs > 3)
3772104b8d3SChris Lattner     report_fatal_error("Invalid number of arguments of main() supplied");
378868e3f09SDaniel Dunbar   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
379868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for third argument of main() supplied");
380868e3f09SDaniel Dunbar   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
381868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for second argument of main() supplied");
382868e3f09SDaniel Dunbar   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
383868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for first argument of main() supplied");
384868e3f09SDaniel Dunbar   if (!FTy->getReturnType()->isIntegerTy() &&
385868e3f09SDaniel Dunbar       !FTy->getReturnType()->isVoidTy())
386868e3f09SDaniel Dunbar     report_fatal_error("Invalid return type of main() supplied");
3878c32c111SAnton Korobeynikov 
388bfd38abbSJeffrey Yasskin   ArgvArray CArgv;
389bfd38abbSJeffrey Yasskin   ArgvArray CEnv;
390b1cad0b3SChris Lattner   if (NumArgs) {
3915a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
392b1cad0b3SChris Lattner     if (NumArgs > 1) {
39355f1c09eSOwen Anderson       // Arg #1 = argv.
394bfd38abbSJeffrey Yasskin       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
3951202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
396b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
397b1cad0b3SChris Lattner       if (NumArgs > 2) {
3985a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3995a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
4005a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
40155f1c09eSOwen Anderson         // Arg #2 = envp.
402bfd38abbSJeffrey Yasskin         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
403b1cad0b3SChris Lattner       }
404b1cad0b3SChris Lattner     }
405b1cad0b3SChris Lattner   }
406868e3f09SDaniel Dunbar 
40787aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
4085a0d4829SChris Lattner }
4095a0d4829SChris Lattner 
410091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M,
411603682adSReid Spencer                                          bool ForceInterpreter,
4127ff05bf5SEvan Cheng                                          std::string *ErrorStr,
41370415d97SJeffrey Yasskin                                          CodeGenOpt::Level OptLevel,
41470415d97SJeffrey Yasskin                                          bool GVsWithCode) {
415add6f1d2SOwen Anderson   EngineBuilder EB =  EngineBuilder(M)
416fc8a2d5aSReid Kleckner       .setEngineKind(ForceInterpreter
417fc8a2d5aSReid Kleckner                      ? EngineKind::Interpreter
418fc8a2d5aSReid Kleckner                      : EngineKind::JIT)
419fc8a2d5aSReid Kleckner       .setErrorStr(ErrorStr)
420fc8a2d5aSReid Kleckner       .setOptLevel(OptLevel)
421add6f1d2SOwen Anderson       .setAllocateGVsWithCode(GVsWithCode);
422add6f1d2SOwen Anderson 
423add6f1d2SOwen Anderson   return EB.create();
424fc8a2d5aSReid Kleckner }
4254bd3bd5bSBrian Gaeke 
4260bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current
4270bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter.  This takes ownership
4280bd34fbdSDylan Noblesmith /// of the module.
4290bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M,
4300bd34fbdSDylan Noblesmith                                             std::string *ErrorStr,
4310bd34fbdSDylan Noblesmith                                             JITMemoryManager *JMM,
43219a58df9SDylan Noblesmith                                             CodeGenOpt::Level OL,
4330bd34fbdSDylan Noblesmith                                             bool GVsWithCode,
4342129f596SEvan Cheng                                             Reloc::Model RM,
4350bd34fbdSDylan Noblesmith                                             CodeModel::Model CMM) {
4362617dcceSCraig Topper   if (!ExecutionEngine::JITCtor) {
4370bd34fbdSDylan Noblesmith     if (ErrorStr)
4380bd34fbdSDylan Noblesmith       *ErrorStr = "JIT has not been linked in.";
4392617dcceSCraig Topper     return nullptr;
4400bd34fbdSDylan Noblesmith   }
4410bd34fbdSDylan Noblesmith 
4420bd34fbdSDylan Noblesmith   // Use the defaults for extra parameters.  Users can use EngineBuilder to
4430bd34fbdSDylan Noblesmith   // set them.
444add6f1d2SOwen Anderson   EngineBuilder EB(M);
445add6f1d2SOwen Anderson   EB.setEngineKind(EngineKind::JIT);
446add6f1d2SOwen Anderson   EB.setErrorStr(ErrorStr);
447add6f1d2SOwen Anderson   EB.setRelocationModel(RM);
448add6f1d2SOwen Anderson   EB.setCodeModel(CMM);
449add6f1d2SOwen Anderson   EB.setAllocateGVsWithCode(GVsWithCode);
450add6f1d2SOwen Anderson   EB.setOptLevel(OL);
451add6f1d2SOwen Anderson   EB.setJITMemoryManager(JMM);
4520bd34fbdSDylan Noblesmith 
453dff24786SPeter Collingbourne   // TODO: permit custom TargetOptions here
454add6f1d2SOwen Anderson   TargetMachine *TM = EB.selectTarget();
4552617dcceSCraig Topper   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
4560bd34fbdSDylan Noblesmith 
4577f26246aSDylan Noblesmith   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
4580bd34fbdSDylan Noblesmith }
4590bd34fbdSDylan Noblesmith 
460add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
46156440fd8SAhmed Charles   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
46225a3d816SBenjamin Kramer 
463a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
464a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
4652617dcceSCraig Topper   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
4662617dcceSCraig Topper     return nullptr;
467a53414fdSNick Lewycky 
4689bc53e84SFilip Pizlo   assert(!(JMM && MCJMM));
4699bc53e84SFilip Pizlo 
470fc8a2d5aSReid Kleckner   // If the user specified a memory manager but didn't specify which engine to
471fc8a2d5aSReid Kleckner   // create, we assume they only want the JIT, and we fail if they only want
472fc8a2d5aSReid Kleckner   // the interpreter.
4739bc53e84SFilip Pizlo   if (JMM || MCJMM) {
47441fa2bd1SChris Lattner     if (WhichEngine & EngineKind::JIT)
475fc8a2d5aSReid Kleckner       WhichEngine = EngineKind::JIT;
47641fa2bd1SChris Lattner     else {
4778bcc6445SChris Lattner       if (ErrorStr)
478fc8a2d5aSReid Kleckner         *ErrorStr = "Cannot create an interpreter with a memory manager.";
4792617dcceSCraig Topper       return nullptr;
480fc8a2d5aSReid Kleckner     }
4814bd3bd5bSBrian Gaeke   }
4824bd3bd5bSBrian Gaeke 
4839bc53e84SFilip Pizlo   if (MCJMM && ! UseMCJIT) {
4849bc53e84SFilip Pizlo     if (ErrorStr)
4859bc53e84SFilip Pizlo       *ErrorStr =
4869bc53e84SFilip Pizlo         "Cannot create a legacy JIT with a runtime dyld memory "
4879bc53e84SFilip Pizlo         "manager.";
4882617dcceSCraig Topper     return nullptr;
4899bc53e84SFilip Pizlo   }
4909bc53e84SFilip Pizlo 
491fc8a2d5aSReid Kleckner   // Unless the interpreter was explicitly selected or the JIT is not linked,
492fc8a2d5aSReid Kleckner   // try making a JIT.
49325a3d816SBenjamin Kramer   if ((WhichEngine & EngineKind::JIT) && TheTM) {
4947f26246aSDylan Noblesmith     Triple TT(M->getTargetTriple());
4957f26246aSDylan Noblesmith     if (!TM->getTarget().hasJIT()) {
4967f26246aSDylan Noblesmith       errs() << "WARNING: This target JIT is not designed for the host"
4977f26246aSDylan Noblesmith              << " you are running.  If bad things happen, please choose"
4987f26246aSDylan Noblesmith              << " a different -march switch.\n";
4997f26246aSDylan Noblesmith     }
5007f26246aSDylan Noblesmith 
501bc876017SLang Hames     ExecutionEngine *EE = nullptr;
502bc876017SLang Hames     if (UseMCJIT && ExecutionEngine::MCJITCtor)
503bc876017SLang Hames       EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
50496c9d95fSAhmed Charles                                       AllocateGVsWithCode, TheTM.release());
505bc876017SLang Hames     else if (ExecutionEngine::JITCtor)
506bc876017SLang Hames       EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
50796c9d95fSAhmed Charles                                     AllocateGVsWithCode, TheTM.release());
508bc876017SLang Hames 
509bc876017SLang Hames     if (EE) {
510bc876017SLang Hames       EE->setVerifyModules(VerifyModules);
511bc876017SLang Hames       return EE;
51241fa2bd1SChris Lattner     }
513fc8a2d5aSReid Kleckner   }
514fc8a2d5aSReid Kleckner 
515fc8a2d5aSReid Kleckner   // If we can't make a JIT and we didn't request one specifically, try making
516fc8a2d5aSReid Kleckner   // an interpreter instead.
51741fa2bd1SChris Lattner   if (WhichEngine & EngineKind::Interpreter) {
51841fa2bd1SChris Lattner     if (ExecutionEngine::InterpCtor)
519091217beSJeffrey Yasskin       return ExecutionEngine::InterpCtor(M, ErrorStr);
5208bcc6445SChris Lattner     if (ErrorStr)
52141fa2bd1SChris Lattner       *ErrorStr = "Interpreter has not been linked in.";
5222617dcceSCraig Topper     return nullptr;
523fc8a2d5aSReid Kleckner   }
524fc8a2d5aSReid Kleckner 
5252617dcceSCraig Topper   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
5262617dcceSCraig Topper       !ExecutionEngine::MCJITCtor) {
5278bcc6445SChris Lattner     if (ErrorStr)
5288bcc6445SChris Lattner       *ErrorStr = "JIT has not been linked in.";
5298bcc6445SChris Lattner   }
530868e3f09SDaniel Dunbar 
5312617dcceSCraig Topper   return nullptr;
532b5163bb9SChris Lattner }
533b5163bb9SChris Lattner 
534996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
5351678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
536996fe010SChris Lattner     return getPointerToFunction(F);
537996fe010SChris Lattner 
53879876f52SReid Spencer   MutexGuard locked(lock);
539868e3f09SDaniel Dunbar   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
540868e3f09SDaniel Dunbar     return P;
54169e84901SJeff Cohen 
54269e84901SJeff Cohen   // Global variable might have been added since interpreter started.
54369e84901SJeff Cohen   if (GlobalVariable *GVar =
54469e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
54569e84901SJeff Cohen     EmitGlobalVariable(GVar);
54669e84901SJeff Cohen   else
547fbcc663cSTorok Edwin     llvm_unreachable("Global hasn't had an address allocated yet!");
548868e3f09SDaniel Dunbar 
549d0fc8f80SJeffrey Yasskin   return EEState.getGlobalAddressMap(locked)[GV];
550996fe010SChris Lattner }
551996fe010SChris Lattner 
552868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of
553868e3f09SDaniel Dunbar /// ConstantExpr values.
554996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
5556c38f0bbSReid Spencer   // If its undefined, return the garbage.
556bcbdbfb3SJay Foad   if (isa<UndefValue>(C)) {
557bcbdbfb3SJay Foad     GenericValue Result;
558bcbdbfb3SJay Foad     switch (C->getType()->getTypeID()) {
559be79a7acSNadav Rotem     default:
560be79a7acSNadav Rotem       break;
561bcbdbfb3SJay Foad     case Type::IntegerTyID:
562bcbdbfb3SJay Foad     case Type::X86_FP80TyID:
563bcbdbfb3SJay Foad     case Type::FP128TyID:
564bcbdbfb3SJay Foad     case Type::PPC_FP128TyID:
565bcbdbfb3SJay Foad       // Although the value is undefined, we still have to construct an APInt
566bcbdbfb3SJay Foad       // with the correct bit width.
567bcbdbfb3SJay Foad       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
568bcbdbfb3SJay Foad       break;
5698e97f016SElena Demikhovsky     case Type::StructTyID: {
5708e97f016SElena Demikhovsky       // if the whole struct is 'undef' just reserve memory for the value.
5718e97f016SElena Demikhovsky       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
5728e97f016SElena Demikhovsky         unsigned int elemNum = STy->getNumElements();
5738e97f016SElena Demikhovsky         Result.AggregateVal.resize(elemNum);
5748e97f016SElena Demikhovsky         for (unsigned int i = 0; i < elemNum; ++i) {
5758e97f016SElena Demikhovsky           Type *ElemTy = STy->getElementType(i);
5768e97f016SElena Demikhovsky           if (ElemTy->isIntegerTy())
5778e97f016SElena Demikhovsky             Result.AggregateVal[i].IntVal =
5788e97f016SElena Demikhovsky               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
5798e97f016SElena Demikhovsky           else if (ElemTy->isAggregateType()) {
5808e97f016SElena Demikhovsky               const Constant *ElemUndef = UndefValue::get(ElemTy);
5818e97f016SElena Demikhovsky               Result.AggregateVal[i] = getConstantValue(ElemUndef);
5828e97f016SElena Demikhovsky             }
5838e97f016SElena Demikhovsky           }
5848e97f016SElena Demikhovsky         }
5858e97f016SElena Demikhovsky       }
5868e97f016SElena Demikhovsky       break;
587be79a7acSNadav Rotem     case Type::VectorTyID:
588be79a7acSNadav Rotem       // if the whole vector is 'undef' just reserve memory for the value.
589be79a7acSNadav Rotem       const VectorType* VTy = dyn_cast<VectorType>(C->getType());
590be79a7acSNadav Rotem       const Type *ElemTy = VTy->getElementType();
591be79a7acSNadav Rotem       unsigned int elemNum = VTy->getNumElements();
592be79a7acSNadav Rotem       Result.AggregateVal.resize(elemNum);
593be79a7acSNadav Rotem       if (ElemTy->isIntegerTy())
594be79a7acSNadav Rotem         for (unsigned int i = 0; i < elemNum; ++i)
595be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal =
596be79a7acSNadav Rotem             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
597bcbdbfb3SJay Foad       break;
598bcbdbfb3SJay Foad     }
599bcbdbfb3SJay Foad     return Result;
600bcbdbfb3SJay Foad   }
6019de0d14dSChris Lattner 
602868e3f09SDaniel Dunbar   // Otherwise, if the value is a ConstantExpr...
6036c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
6044fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
6059de0d14dSChris Lattner     switch (CE->getOpcode()) {
6069de0d14dSChris Lattner     case Instruction::GetElementPtr: {
6076c38f0bbSReid Spencer       // Compute the index
6084fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
6097c68bebbSRafael Espindola       APInt Offset(DL->getPointerSizeInBits(), 0);
6107c68bebbSRafael Espindola       cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
6119de0d14dSChris Lattner 
61287aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
613b6ad9822SNuno Lopes       Result = PTOGV(tmp + Offset.getSExtValue());
6149de0d14dSChris Lattner       return Result;
6159de0d14dSChris Lattner     }
6164fd528f2SReid Spencer     case Instruction::Trunc: {
6174fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6184fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6194fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
6204fd528f2SReid Spencer       return GV;
6214fd528f2SReid Spencer     }
6224fd528f2SReid Spencer     case Instruction::ZExt: {
6234fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6244fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6254fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
6264fd528f2SReid Spencer       return GV;
6274fd528f2SReid Spencer     }
6284fd528f2SReid Spencer     case Instruction::SExt: {
6294fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6304fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6314fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
6324fd528f2SReid Spencer       return GV;
6334fd528f2SReid Spencer     }
6344fd528f2SReid Spencer     case Instruction::FPTrunc: {
635a1336cf5SDale Johannesen       // FIXME long double
6364fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6374fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
6384fd528f2SReid Spencer       return GV;
6394fd528f2SReid Spencer     }
6404fd528f2SReid Spencer     case Instruction::FPExt:{
641a1336cf5SDale Johannesen       // FIXME long double
6424fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6434fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
6444fd528f2SReid Spencer       return GV;
6454fd528f2SReid Spencer     }
6464fd528f2SReid Spencer     case Instruction::UIToFP: {
6474fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
648fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6494fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
650fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6514fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
652fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
65331920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
654ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
655ca24fd90SDan Gohman                                    false,
6569150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
65754306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
658a1336cf5SDale Johannesen       }
6594fd528f2SReid Spencer       return GV;
6604fd528f2SReid Spencer     }
6614fd528f2SReid Spencer     case Instruction::SIToFP: {
6624fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
663fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6644fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
665fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6664fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
667fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
66831920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
669ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
670ca24fd90SDan Gohman                                    true,
6719150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
67254306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
673a1336cf5SDale Johannesen       }
6744fd528f2SReid Spencer       return GV;
6754fd528f2SReid Spencer     }
6764fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
6774fd528f2SReid Spencer     case Instruction::FPToSI: {
6784fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6794fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
680fdd87907SChris Lattner       if (Op0->getType()->isFloatTy())
6814fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
682fdd87907SChris Lattner       else if (Op0->getType()->isDoubleTy())
6834fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
684fdd87907SChris Lattner       else if (Op0->getType()->isX86_FP80Ty()) {
68529178a34STim Northover         APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
686a1336cf5SDale Johannesen         uint64_t v;
6874f0bd68cSDale Johannesen         bool ignored;
688a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
689a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
6904f0bd68cSDale Johannesen                                    APFloat::rmTowardZero, &ignored);
691a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
692a1336cf5SDale Johannesen       }
6934fd528f2SReid Spencer       return GV;
6944fd528f2SReid Spencer     }
6956c38f0bbSReid Spencer     case Instruction::PtrToInt: {
6964fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6977c68bebbSRafael Espindola       uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
698fc1f2cd3SEli Friedman       assert(PtrWidth <= 64 && "Bad pointer width");
6994fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
7007c68bebbSRafael Espindola       uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
701fc1f2cd3SEli Friedman       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
7024fd528f2SReid Spencer       return GV;
7034fd528f2SReid Spencer     }
7044fd528f2SReid Spencer     case Instruction::IntToPtr: {
7054fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
7067c68bebbSRafael Espindola       uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
7074fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
7084fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
7094fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
7106c38f0bbSReid Spencer       return GV;
7116c38f0bbSReid Spencer     }
7126c38f0bbSReid Spencer     case Instruction::BitCast: {
7134fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
714229907cdSChris Lattner       Type* DestTy = CE->getType();
7154fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
716fbcc663cSTorok Edwin         default: llvm_unreachable("Invalid bitcast operand");
7174fd528f2SReid Spencer         case Type::IntegerTyID:
7189dff9becSDuncan Sands           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
719fdd87907SChris Lattner           if (DestTy->isFloatTy())
7204fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
721fdd87907SChris Lattner           else if (DestTy->isDoubleTy())
7224fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
7236c38f0bbSReid Spencer           break;
7244fd528f2SReid Spencer         case Type::FloatTyID:
7259dff9becSDuncan Sands           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
7263447fb01SJay Foad           GV.IntVal = APInt::floatToBits(GV.FloatVal);
7274fd528f2SReid Spencer           break;
7284fd528f2SReid Spencer         case Type::DoubleTyID:
7299dff9becSDuncan Sands           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
7303447fb01SJay Foad           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
7314fd528f2SReid Spencer           break;
7324fd528f2SReid Spencer         case Type::PointerTyID:
73319d0b47bSDuncan Sands           assert(DestTy->isPointerTy() && "Invalid bitcast");
7344fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
7356c38f0bbSReid Spencer       }
7364fd528f2SReid Spencer       return GV;
73768cbcc3eSChris Lattner     }
73868cbcc3eSChris Lattner     case Instruction::Add:
739a5b9645cSDan Gohman     case Instruction::FAdd:
7404fd528f2SReid Spencer     case Instruction::Sub:
741a5b9645cSDan Gohman     case Instruction::FSub:
7424fd528f2SReid Spencer     case Instruction::Mul:
743a5b9645cSDan Gohman     case Instruction::FMul:
7444fd528f2SReid Spencer     case Instruction::UDiv:
7454fd528f2SReid Spencer     case Instruction::SDiv:
7464fd528f2SReid Spencer     case Instruction::URem:
7474fd528f2SReid Spencer     case Instruction::SRem:
7484fd528f2SReid Spencer     case Instruction::And:
7494fd528f2SReid Spencer     case Instruction::Or:
7504fd528f2SReid Spencer     case Instruction::Xor: {
7514fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
7524fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
7534fd528f2SReid Spencer       GenericValue GV;
754c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
755fbcc663cSTorok Edwin       default: llvm_unreachable("Bad add type!");
7567a9c62baSReid Spencer       case Type::IntegerTyID:
7574fd528f2SReid Spencer         switch (CE->getOpcode()) {
758fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid integer opcode");
7594fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
7604fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
7614fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
7624fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
7634fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
7644fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
7654fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
7664fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
7674fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
7684fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
7694fd528f2SReid Spencer         }
770c4e6bb5fSChris Lattner         break;
771c4e6bb5fSChris Lattner       case Type::FloatTyID:
7724fd528f2SReid Spencer         switch (CE->getOpcode()) {
773fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid float opcode");
774a5b9645cSDan Gohman           case Instruction::FAdd:
7754fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
776a5b9645cSDan Gohman           case Instruction::FSub:
7774fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
778a5b9645cSDan Gohman           case Instruction::FMul:
7794fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
7804fd528f2SReid Spencer           case Instruction::FDiv:
7814fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
7824fd528f2SReid Spencer           case Instruction::FRem:
78393cd0f1cSChris Lattner             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
7844fd528f2SReid Spencer         }
785c4e6bb5fSChris Lattner         break;
786c4e6bb5fSChris Lattner       case Type::DoubleTyID:
7874fd528f2SReid Spencer         switch (CE->getOpcode()) {
788fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid double opcode");
789a5b9645cSDan Gohman           case Instruction::FAdd:
7904fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
791a5b9645cSDan Gohman           case Instruction::FSub:
7924fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
793a5b9645cSDan Gohman           case Instruction::FMul:
7944fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
7954fd528f2SReid Spencer           case Instruction::FDiv:
7964fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
7974fd528f2SReid Spencer           case Instruction::FRem:
79893cd0f1cSChris Lattner             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
7994fd528f2SReid Spencer         }
800c4e6bb5fSChris Lattner         break;
801a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
802a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
803a1336cf5SDale Johannesen       case Type::FP128TyID: {
80429178a34STim Northover         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
80529178a34STim Northover         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
806a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
807e4f47434SDaniel Dunbar           default: llvm_unreachable("Invalid long double opcode");
808a5b9645cSDan Gohman           case Instruction::FAdd:
80929178a34STim Northover             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
81054306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
811a1336cf5SDale Johannesen             break;
812a5b9645cSDan Gohman           case Instruction::FSub:
81329178a34STim Northover             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
81429178a34STim Northover                             APFloat::rmNearestTiesToEven);
81554306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
816a1336cf5SDale Johannesen             break;
817a5b9645cSDan Gohman           case Instruction::FMul:
81829178a34STim Northover             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
81929178a34STim Northover                             APFloat::rmNearestTiesToEven);
82054306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
821a1336cf5SDale Johannesen             break;
822a1336cf5SDale Johannesen           case Instruction::FDiv:
82329178a34STim Northover             apfLHS.divide(APFloat(Sem, RHS.IntVal),
82429178a34STim Northover                           APFloat::rmNearestTiesToEven);
82554306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
826a1336cf5SDale Johannesen             break;
827a1336cf5SDale Johannesen           case Instruction::FRem:
82829178a34STim Northover             apfLHS.mod(APFloat(Sem, RHS.IntVal),
82929178a34STim Northover                        APFloat::rmNearestTiesToEven);
83054306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
831a1336cf5SDale Johannesen             break;
832a1336cf5SDale Johannesen           }
833a1336cf5SDale Johannesen         }
834a1336cf5SDale Johannesen         break;
835c4e6bb5fSChris Lattner       }
8364fd528f2SReid Spencer       return GV;
8374fd528f2SReid Spencer     }
8389de0d14dSChris Lattner     default:
83968cbcc3eSChris Lattner       break;
84068cbcc3eSChris Lattner     }
841868e3f09SDaniel Dunbar 
842868e3f09SDaniel Dunbar     SmallString<256> Msg;
843868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
844868e3f09SDaniel Dunbar     OS << "ConstantExpr not handled: " << *CE;
845868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
8469de0d14dSChris Lattner   }
847996fe010SChris Lattner 
848868e3f09SDaniel Dunbar   // Otherwise, we have a simple constant.
8494fd528f2SReid Spencer   GenericValue Result;
8506b727599SChris Lattner   switch (C->getType()->getTypeID()) {
85187aa65f4SReid Spencer   case Type::FloatTyID:
852bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
8537a9c62baSReid Spencer     break;
85487aa65f4SReid Spencer   case Type::DoubleTyID:
855bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
85687aa65f4SReid Spencer     break;
857a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
858a1336cf5SDale Johannesen   case Type::FP128TyID:
859a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
86054306fe4SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
861a1336cf5SDale Johannesen     break;
86287aa65f4SReid Spencer   case Type::IntegerTyID:
86387aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
86487aa65f4SReid Spencer     break;
865996fe010SChris Lattner   case Type::PointerTyID:
8666a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
8672617dcceSCraig Topper       Result.PointerVal = nullptr;
8686a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
8696a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
8706a0fd73bSReid Spencer     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
8716a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
8720c778f70SChris Lattner     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
8730c778f70SChris Lattner       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
8740c778f70SChris Lattner                                                         BA->getBasicBlock())));
875e6492f10SChris Lattner     else
876fbcc663cSTorok Edwin       llvm_unreachable("Unknown constant pointer type!");
877996fe010SChris Lattner     break;
878be79a7acSNadav Rotem   case Type::VectorTyID: {
879be79a7acSNadav Rotem     unsigned elemNum;
880be79a7acSNadav Rotem     Type* ElemTy;
881be79a7acSNadav Rotem     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
882be79a7acSNadav Rotem     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
883be79a7acSNadav Rotem     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
884be79a7acSNadav Rotem 
885be79a7acSNadav Rotem     if (CDV) {
886be79a7acSNadav Rotem         elemNum = CDV->getNumElements();
887be79a7acSNadav Rotem         ElemTy = CDV->getElementType();
888be79a7acSNadav Rotem     } else if (CV || CAZ) {
889be79a7acSNadav Rotem         VectorType* VTy = dyn_cast<VectorType>(C->getType());
890be79a7acSNadav Rotem         elemNum = VTy->getNumElements();
891be79a7acSNadav Rotem         ElemTy = VTy->getElementType();
892be79a7acSNadav Rotem     } else {
893be79a7acSNadav Rotem         llvm_unreachable("Unknown constant vector type!");
894be79a7acSNadav Rotem     }
895be79a7acSNadav Rotem 
896be79a7acSNadav Rotem     Result.AggregateVal.resize(elemNum);
897be79a7acSNadav Rotem     // Check if vector holds floats.
898be79a7acSNadav Rotem     if(ElemTy->isFloatTy()) {
899be79a7acSNadav Rotem       if (CAZ) {
900be79a7acSNadav Rotem         GenericValue floatZero;
901be79a7acSNadav Rotem         floatZero.FloatVal = 0.f;
902be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
903be79a7acSNadav Rotem                   floatZero);
904be79a7acSNadav Rotem         break;
905be79a7acSNadav Rotem       }
906be79a7acSNadav Rotem       if(CV) {
907be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
908be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
909be79a7acSNadav Rotem             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
910be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToFloat();
911be79a7acSNadav Rotem         break;
912be79a7acSNadav Rotem       }
913be79a7acSNadav Rotem       if(CDV)
914be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
915be79a7acSNadav Rotem           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
916be79a7acSNadav Rotem 
917be79a7acSNadav Rotem       break;
918be79a7acSNadav Rotem     }
919be79a7acSNadav Rotem     // Check if vector holds doubles.
920be79a7acSNadav Rotem     if (ElemTy->isDoubleTy()) {
921be79a7acSNadav Rotem       if (CAZ) {
922be79a7acSNadav Rotem         GenericValue doubleZero;
923be79a7acSNadav Rotem         doubleZero.DoubleVal = 0.0;
924be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
925be79a7acSNadav Rotem                   doubleZero);
926be79a7acSNadav Rotem         break;
927be79a7acSNadav Rotem       }
928be79a7acSNadav Rotem       if(CV) {
929be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
930be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
931be79a7acSNadav Rotem             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
932be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToDouble();
933be79a7acSNadav Rotem         break;
934be79a7acSNadav Rotem       }
935be79a7acSNadav Rotem       if(CDV)
936be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
937be79a7acSNadav Rotem           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
938be79a7acSNadav Rotem 
939be79a7acSNadav Rotem       break;
940be79a7acSNadav Rotem     }
941be79a7acSNadav Rotem     // Check if vector holds integers.
942be79a7acSNadav Rotem     if (ElemTy->isIntegerTy()) {
943be79a7acSNadav Rotem       if (CAZ) {
944be79a7acSNadav Rotem         GenericValue intZero;
945be79a7acSNadav Rotem         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
946be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
947be79a7acSNadav Rotem                   intZero);
948be79a7acSNadav Rotem         break;
949be79a7acSNadav Rotem       }
950be79a7acSNadav Rotem       if(CV) {
951be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
952be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
953be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
954be79a7acSNadav Rotem                                             CV->getOperand(i))->getValue();
955be79a7acSNadav Rotem           else {
956be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal =
957be79a7acSNadav Rotem               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
958be79a7acSNadav Rotem           }
959be79a7acSNadav Rotem         break;
960be79a7acSNadav Rotem       }
961be79a7acSNadav Rotem       if(CDV)
962be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
963be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal = APInt(
964be79a7acSNadav Rotem             CDV->getElementType()->getPrimitiveSizeInBits(),
965be79a7acSNadav Rotem             CDV->getElementAsInteger(i));
966be79a7acSNadav Rotem 
967be79a7acSNadav Rotem       break;
968be79a7acSNadav Rotem     }
969be79a7acSNadav Rotem     llvm_unreachable("Unknown constant pointer type!");
970be79a7acSNadav Rotem   }
971be79a7acSNadav Rotem   break;
972be79a7acSNadav Rotem 
973996fe010SChris Lattner   default:
974868e3f09SDaniel Dunbar     SmallString<256> Msg;
975868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
976868e3f09SDaniel Dunbar     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
977868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
978996fe010SChris Lattner   }
979868e3f09SDaniel Dunbar 
980996fe010SChris Lattner   return Result;
981996fe010SChris Lattner }
982996fe010SChris Lattner 
9831202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
9841202d1b1SDuncan Sands /// with the integer held in IntVal.
9851202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
9861202d1b1SDuncan Sands                              unsigned StoreBytes) {
9871202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
988ad06cee2SRoman Divacky   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
9895c65cb46SDuncan Sands 
99041cb64f4SRafael Espindola   if (sys::IsLittleEndianHost) {
9911202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
9921202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
9935c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
994868e3f09SDaniel Dunbar   } else {
9955c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
9961202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
9971202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
9985c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
9995c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
10005c65cb46SDuncan Sands       // May not be aligned so use memcpy.
10015c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
10025c65cb46SDuncan Sands       Src += sizeof(uint64_t);
10035c65cb46SDuncan Sands     }
10045c65cb46SDuncan Sands 
10055c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1006815f8dd2SReid Spencer   }
10077a9c62baSReid Spencer }
10081202d1b1SDuncan Sands 
100909053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1010229907cdSChris Lattner                                          GenericValue *Ptr, Type *Ty) {
1011cdfe20b9SMicah Villmow   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
10121202d1b1SDuncan Sands 
10131202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
1014be79a7acSNadav Rotem   default:
1015be79a7acSNadav Rotem     dbgs() << "Cannot store value of type " << *Ty << "!\n";
1016be79a7acSNadav Rotem     break;
10171202d1b1SDuncan Sands   case Type::IntegerTyID:
10181202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
10191202d1b1SDuncan Sands     break;
1020996fe010SChris Lattner   case Type::FloatTyID:
102187aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
102287aa65f4SReid Spencer     break;
102387aa65f4SReid Spencer   case Type::DoubleTyID:
102487aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
1025996fe010SChris Lattner     break;
10264d7e4ee7SDale Johannesen   case Type::X86_FP80TyID:
10274d7e4ee7SDale Johannesen     memcpy(Ptr, Val.IntVal.getRawData(), 10);
1028a1336cf5SDale Johannesen     break;
10297a9c62baSReid Spencer   case Type::PointerTyID:
10301202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
10311202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
103293da3c82SChandler Carruth       memset(&(Ptr->PointerVal), 0, StoreBytes);
10331202d1b1SDuncan Sands 
103487aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
1035996fe010SChris Lattner     break;
1036be79a7acSNadav Rotem   case Type::VectorTyID:
1037be79a7acSNadav Rotem     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1038be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1039be79a7acSNadav Rotem         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1040be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1041be79a7acSNadav Rotem         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1042be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1043be79a7acSNadav Rotem         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1044be79a7acSNadav Rotem         StoreIntToMemory(Val.AggregateVal[i].IntVal,
1045be79a7acSNadav Rotem           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1046be79a7acSNadav Rotem       }
1047be79a7acSNadav Rotem     }
1048be79a7acSNadav Rotem     break;
1049996fe010SChris Lattner   }
10501202d1b1SDuncan Sands 
105141cb64f4SRafael Espindola   if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
10521202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
10531202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1054996fe010SChris Lattner }
1055996fe010SChris Lattner 
10561202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
10571202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
10581202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
10591202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
106082b63578SDavid Greene   uint8_t *Dst = reinterpret_cast<uint8_t *>(
106182b63578SDavid Greene                    const_cast<uint64_t *>(IntVal.getRawData()));
10625c65cb46SDuncan Sands 
106341cb64f4SRafael Espindola   if (sys::IsLittleEndianHost)
10645c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
10655c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
10665c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
10675c65cb46SDuncan Sands   else {
10685c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
10695c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
10705c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
10715c65cb46SDuncan Sands     // a word.
10725c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
10735c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
10745c65cb46SDuncan Sands       // May not be aligned so use memcpy.
10755c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
10765c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
10775c65cb46SDuncan Sands     }
10785c65cb46SDuncan Sands 
10795c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
10805c65cb46SDuncan Sands   }
10817a9c62baSReid Spencer }
10821202d1b1SDuncan Sands 
10831202d1b1SDuncan Sands /// FIXME: document
10841202d1b1SDuncan Sands ///
10851202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
10861202d1b1SDuncan Sands                                           GenericValue *Ptr,
1087229907cdSChris Lattner                                           Type *Ty) {
1088cdfe20b9SMicah Villmow   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
10891202d1b1SDuncan Sands 
10901202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
10911202d1b1SDuncan Sands   case Type::IntegerTyID:
10921202d1b1SDuncan Sands     // An APInt with all words initially zero.
10931202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
10941202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
10951202d1b1SDuncan Sands     break;
10967f389e8cSChris Lattner   case Type::FloatTyID:
109787aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
109887aa65f4SReid Spencer     break;
109987aa65f4SReid Spencer   case Type::DoubleTyID:
110087aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
11017f389e8cSChris Lattner     break;
11027a9c62baSReid Spencer   case Type::PointerTyID:
110387aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
11047f389e8cSChris Lattner     break;
1105a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
1106a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
110726d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
1108ff306287SDuncan Sands     uint64_t y[2];
11094d7e4ee7SDale Johannesen     memcpy(y, Ptr, 10);
11107a162881SJeffrey Yasskin     Result.IntVal = APInt(80, y);
1111a1336cf5SDale Johannesen     break;
1112a1336cf5SDale Johannesen   }
1113be79a7acSNadav Rotem   case Type::VectorTyID: {
1114be79a7acSNadav Rotem     const VectorType *VT = cast<VectorType>(Ty);
1115be79a7acSNadav Rotem     const Type *ElemT = VT->getElementType();
1116be79a7acSNadav Rotem     const unsigned numElems = VT->getNumElements();
1117be79a7acSNadav Rotem     if (ElemT->isFloatTy()) {
1118be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1119be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1120be79a7acSNadav Rotem         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1121be79a7acSNadav Rotem     }
1122be79a7acSNadav Rotem     if (ElemT->isDoubleTy()) {
1123be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1124be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1125be79a7acSNadav Rotem         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1126be79a7acSNadav Rotem     }
1127be79a7acSNadav Rotem     if (ElemT->isIntegerTy()) {
1128be79a7acSNadav Rotem       GenericValue intZero;
1129be79a7acSNadav Rotem       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1130be79a7acSNadav Rotem       intZero.IntVal = APInt(elemBitWidth, 0);
1131be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems, intZero);
1132be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1133be79a7acSNadav Rotem         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1134be79a7acSNadav Rotem           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1135be79a7acSNadav Rotem     }
1136be79a7acSNadav Rotem   break;
1137be79a7acSNadav Rotem   }
11387f389e8cSChris Lattner   default:
1139868e3f09SDaniel Dunbar     SmallString<256> Msg;
1140868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
1141868e3f09SDaniel Dunbar     OS << "Cannot load value of type " << *Ty << "!";
1142868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
11437f389e8cSChris Lattner   }
11447f389e8cSChris Lattner }
11457f389e8cSChris Lattner 
1146996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
11470967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1148b086d382SDale Johannesen   DEBUG(Init->dump());
114900245f42SChris Lattner   if (isa<UndefValue>(Init))
115061753bf8SChris Lattner     return;
115100245f42SChris Lattner 
115200245f42SChris Lattner   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
115369d62138SRobert Bocchino     unsigned ElementSize =
1154cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
115569d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
115669d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
115769d62138SRobert Bocchino     return;
115800245f42SChris Lattner   }
115900245f42SChris Lattner 
116000245f42SChris Lattner   if (isa<ConstantAggregateZero>(Init)) {
1161cdfe20b9SMicah Villmow     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
11621dd86b11SChris Lattner     return;
116300245f42SChris Lattner   }
116400245f42SChris Lattner 
116500245f42SChris Lattner   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
116669ddfbfeSDan Gohman     unsigned ElementSize =
1167cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
116869ddfbfeSDan Gohman     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
116969ddfbfeSDan Gohman       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
117069ddfbfeSDan Gohman     return;
117100245f42SChris Lattner   }
117200245f42SChris Lattner 
117300245f42SChris Lattner   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
117469ddfbfeSDan Gohman     const StructLayout *SL =
1175cdfe20b9SMicah Villmow       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
117669ddfbfeSDan Gohman     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
117769ddfbfeSDan Gohman       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
117869ddfbfeSDan Gohman     return;
117900245f42SChris Lattner   }
118000245f42SChris Lattner 
118100245f42SChris Lattner   if (const ConstantDataSequential *CDS =
118200245f42SChris Lattner                dyn_cast<ConstantDataSequential>(Init)) {
118300245f42SChris Lattner     // CDS is already laid out in host memory order.
118400245f42SChris Lattner     StringRef Data = CDS->getRawDataValues();
118500245f42SChris Lattner     memcpy(Addr, Data.data(), Data.size());
118600245f42SChris Lattner     return;
118700245f42SChris Lattner   }
118800245f42SChris Lattner 
118900245f42SChris Lattner   if (Init->getType()->isFirstClassType()) {
1190996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
1191996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1192996fe010SChris Lattner     return;
1193996fe010SChris Lattner   }
1194996fe010SChris Lattner 
1195868e3f09SDaniel Dunbar   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1196fbcc663cSTorok Edwin   llvm_unreachable("Unknown constant type to initialize memory with!");
1197996fe010SChris Lattner }
1198996fe010SChris Lattner 
1199996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
1200996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
1201996fe010SChris Lattner /// their initializers into the memory.
1202996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
1203996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
12040621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
12050621caefSChris Lattner   // to figure out how the different modules should link together.
1206229907cdSChris Lattner   std::map<std::pair<std::string, Type*>,
12070621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
12080621caefSChris Lattner 
12090621caefSChris Lattner   if (Modules.size() != 1) {
12100621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1211091217beSJeffrey Yasskin       Module &M = *Modules[m];
1212*49bb65a4SRafael Espindola       for (const auto &GV : M.globals()) {
1213*49bb65a4SRafael Espindola         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1214*49bb65a4SRafael Espindola             GV.hasAppendingLinkage() || !GV.hasName())
12150621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
12160621caefSChris Lattner 
12170621caefSChris Lattner         const GlobalValue *&GVEntry =
1218*49bb65a4SRafael Espindola           LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
12190621caefSChris Lattner 
12200621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
12210621caefSChris Lattner         // version.
12220621caefSChris Lattner         if (!GVEntry) {
1223*49bb65a4SRafael Espindola           GVEntry = &GV;
12240621caefSChris Lattner           continue;
12250621caefSChris Lattner         }
12260621caefSChris Lattner 
12270621caefSChris Lattner         // If the existing global is strong, never replace it.
12287157bb76SNico Rieck         if (GVEntry->hasExternalLinkage())
12290621caefSChris Lattner           continue;
12300621caefSChris Lattner 
12310621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1232ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
1233*49bb65a4SRafael Espindola         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1234*49bb65a4SRafael Espindola           GVEntry = &GV;
12350621caefSChris Lattner       }
12360621caefSChris Lattner     }
12370621caefSChris Lattner   }
12380621caefSChris Lattner 
12390621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
12400621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1241091217beSJeffrey Yasskin     Module &M = *Modules[m];
1242*49bb65a4SRafael Espindola     for (const auto &GV : M.globals()) {
12430621caefSChris Lattner       // In the multi-module case, see what this global maps to.
12440621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
12450621caefSChris Lattner         if (const GlobalValue *GVEntry =
1246*49bb65a4SRafael Espindola               LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
12470621caefSChris Lattner           // If something else is the canonical global, ignore this one.
1248*49bb65a4SRafael Espindola           if (GVEntry != &GV) {
1249*49bb65a4SRafael Espindola             NonCanonicalGlobals.push_back(&GV);
12500621caefSChris Lattner             continue;
12510621caefSChris Lattner           }
12520621caefSChris Lattner         }
12530621caefSChris Lattner       }
12540621caefSChris Lattner 
1255*49bb65a4SRafael Espindola       if (!GV.isDeclaration()) {
1256*49bb65a4SRafael Espindola         addGlobalMapping(&GV, getMemoryForGV(&GV));
1257996fe010SChris Lattner       } else {
1258e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
1259e8bbcfc2SBrian Gaeke         // get a pointer to it.
12600621caefSChris Lattner         if (void *SymAddr =
1261*49bb65a4SRafael Espindola             sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1262*49bb65a4SRafael Espindola           addGlobalMapping(&GV, SymAddr);
12639de0d14dSChris Lattner         else {
12642104b8d3SChris Lattner           report_fatal_error("Could not resolve external global address: "
1265*49bb65a4SRafael Espindola                             +GV.getName());
12669de0d14dSChris Lattner         }
1267996fe010SChris Lattner       }
12680621caefSChris Lattner     }
12690621caefSChris Lattner 
12700621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
12710621caefSChris Lattner     // canonical location.
12720621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
12730621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
12740621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
12750621caefSChris Lattner         const GlobalValue *CGV =
12760621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
12770621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
12780621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
1279a67f06b9SNuno Lopes         addGlobalMapping(GV, Ptr);
12800621caefSChris Lattner       }
12810621caefSChris Lattner     }
1282996fe010SChris Lattner 
12837a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
12847a9c62baSReid Spencer     // and initialize their contents.
1285*49bb65a4SRafael Espindola     for (const auto &GV : M.globals()) {
1286*49bb65a4SRafael Espindola       if (!GV.isDeclaration()) {
12870621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
12880621caefSChris Lattner           if (const GlobalValue *GVEntry =
1289*49bb65a4SRafael Espindola                 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1290*49bb65a4SRafael Espindola             if (GVEntry != &GV)  // Not the canonical variable.
12910621caefSChris Lattner               continue;
12920621caefSChris Lattner         }
1293*49bb65a4SRafael Espindola         EmitGlobalVariable(&GV);
12946bbe3eceSChris Lattner       }
12950621caefSChris Lattner     }
12960621caefSChris Lattner   }
12970621caefSChris Lattner }
12986bbe3eceSChris Lattner 
12996bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
13006bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
13016bbe3eceSChris Lattner // already in the map.
1302fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1303748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
1304dc631735SChris Lattner 
13052617dcceSCraig Topper   if (!GA) {
13066bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
13075457ce9aSNicolas Geoffray     GA = getMemoryForGV(GV);
13083b442379SAndrew Kaylor 
13093b442379SAndrew Kaylor     // If we failed to allocate memory for this global, return.
13102617dcceSCraig Topper     if (!GA) return;
13113b442379SAndrew Kaylor 
1312748e8579SChris Lattner     addGlobalMapping(GV, GA);
13136bbe3eceSChris Lattner   }
1314fbcc0aa1SChris Lattner 
13155457ce9aSNicolas Geoffray   // Don't initialize if it's thread local, let the client do it.
13165457ce9aSNicolas Geoffray   if (!GV->isThreadLocal())
13176bbe3eceSChris Lattner     InitializeMemory(GV->getInitializer(), GA);
13185457ce9aSNicolas Geoffray 
1319229907cdSChris Lattner   Type *ElTy = GV->getType()->getElementType();
1320cdfe20b9SMicah Villmow   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1321df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
13226bbe3eceSChris Lattner   ++NumGlobals;
1323996fe010SChris Lattner }
1324f98e981cSJeffrey Yasskin 
1325d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1326d0fc8f80SJeffrey Yasskin   : EE(EE), GlobalAddressMap(this) {
1327f98e981cSJeffrey Yasskin }
1328f98e981cSJeffrey Yasskin 
1329868e3f09SDaniel Dunbar sys::Mutex *
1330868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1331d0fc8f80SJeffrey Yasskin   return &EES->EE.lock;
1332d0fc8f80SJeffrey Yasskin }
1333868e3f09SDaniel Dunbar 
1334868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1335868e3f09SDaniel Dunbar                                                       const GlobalValue *Old) {
1336d0fc8f80SJeffrey Yasskin   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1337d0fc8f80SJeffrey Yasskin   EES->GlobalAddressReverseMap.erase(OldVal);
1338d0fc8f80SJeffrey Yasskin }
1339d0fc8f80SJeffrey Yasskin 
1340868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1341868e3f09SDaniel Dunbar                                                     const GlobalValue *,
1342868e3f09SDaniel Dunbar                                                     const GlobalValue *) {
1343a2886c21SCraig Topper   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1344f98e981cSJeffrey Yasskin                    " RAUW on a value it has a global mapping for.");
1345f98e981cSJeffrey Yasskin }
1346