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"
17868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h"
18390d78b3SChris Lattner #include "llvm/ADT/Statistic.h"
19ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h"
208a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/JITMemoryManager.h"
218a8cd2baSChandler Carruth #include "llvm/ExecutionEngine/ObjectCache.h"
229fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
239fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
249fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
259fb823bbSChandler Carruth #include "llvm/IR/Module.h"
269fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
274220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.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 
40c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
41c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
42996fe010SChris Lattner 
43d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
44d12ccbd3SJuergen Ributzka void ObjectCache::anchor() {}
45d12ccbd3SJuergen Ributzka void ObjectBuffer::anchor() {}
46d12ccbd3SJuergen Ributzka void ObjectBufferStream::anchor() {}
47d12ccbd3SJuergen Ributzka 
4831faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)(
4931faefffSJeffrey Yasskin   Module *M,
50fc8a2d5aSReid Kleckner   std::string *ErrorStr,
51fc8a2d5aSReid Kleckner   JITMemoryManager *JMM,
52700d08e1SEric Christopher   bool GVsWithCode,
532617dcceSCraig Topper   TargetMachine *TM) = nullptr;
5470ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
5570ff8b05SDaniel Dunbar   Module *M,
5670ff8b05SDaniel Dunbar   std::string *ErrorStr,
579bc53e84SFilip Pizlo   RTDyldMemoryManager *MCJMM,
5870ff8b05SDaniel Dunbar   bool GVsWithCode,
592617dcceSCraig Topper   TargetMachine *TM) = nullptr;
60091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
612617dcceSCraig Topper                                                 std::string *ErrorStr) =nullptr;
622d52c1b8SChris Lattner 
63091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M)
64f98e981cSJeffrey Yasskin   : EEState(*this),
652617dcceSCraig Topper     LazyFunctionCreator(nullptr) {
664567db45SJeffrey Yasskin   CompilingLazily         = false;
67cdc0060eSEvan Cheng   GVCompilationDisabled   = false;
6884a9055eSEvan Cheng   SymbolSearchingDisabled = false;
69*bc876017SLang Hames 
70*bc876017SLang Hames   // IR module verification is enabled by default in debug builds, and disabled
71*bc876017SLang Hames   // by default in release builds.
72*bc876017SLang Hames #ifndef NDEBUG
73*bc876017SLang Hames   VerifyModules = true;
74*bc876017SLang Hames #else
75*bc876017SLang Hames   VerifyModules = false;
76*bc876017SLang Hames #endif
77*bc876017SLang Hames 
78091217beSJeffrey Yasskin   Modules.push_back(M);
79091217beSJeffrey Yasskin   assert(M && "Module is null?");
80260b0c88SMisha Brukman }
81260b0c88SMisha Brukman 
8292f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
83603682adSReid Spencer   clearAllGlobalMappings();
840621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
850621caefSChris Lattner     delete Modules[i];
8692f8b30dSBrian Gaeke }
8792f8b30dSBrian Gaeke 
88a4044332SJeffrey Yasskin namespace {
89868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the
90868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed.
91a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH {
92a4044332SJeffrey Yasskin   GVMemoryBlock(const GlobalVariable *GV)
93a4044332SJeffrey Yasskin     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
94a4044332SJeffrey Yasskin 
95a4044332SJeffrey Yasskin public:
96868e3f09SDaniel Dunbar   /// \brief Returns the address the GlobalVariable should be written into.  The
97868e3f09SDaniel Dunbar   /// GVMemoryBlock object prefixes that.
98cdfe20b9SMicah Villmow   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
99229907cdSChris Lattner     Type *ElTy = GV->getType()->getElementType();
100a4044332SJeffrey Yasskin     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
101a4044332SJeffrey Yasskin     void *RawMemory = ::operator new(
102cdfe20b9SMicah Villmow       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
103a4044332SJeffrey Yasskin                                    TD.getPreferredAlignment(GV))
104a4044332SJeffrey Yasskin       + GVSize);
105a4044332SJeffrey Yasskin     new(RawMemory) GVMemoryBlock(GV);
106a4044332SJeffrey Yasskin     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
107a4044332SJeffrey Yasskin   }
108a4044332SJeffrey Yasskin 
109b51ff603SCraig Topper   void deleted() override {
110a4044332SJeffrey Yasskin     // We allocated with operator new and with some extra memory hanging off the
111a4044332SJeffrey Yasskin     // end, so don't just delete this.  I'm not sure if this is actually
112a4044332SJeffrey Yasskin     // required.
113a4044332SJeffrey Yasskin     this->~GVMemoryBlock();
114a4044332SJeffrey Yasskin     ::operator delete(this);
115a4044332SJeffrey Yasskin   }
116a4044332SJeffrey Yasskin };
117a4044332SJeffrey Yasskin }  // anonymous namespace
118a4044332SJeffrey Yasskin 
119a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
120cdfe20b9SMicah Villmow   return GVMemoryBlock::Create(GV, *getDataLayout());
1215457ce9aSNicolas Geoffray }
1225457ce9aSNicolas Geoffray 
123091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) {
124af0dea13SCraig Topper   for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
125324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
126091217beSJeffrey Yasskin     Module *Found = *I;
127091217beSJeffrey Yasskin     if (Found == M) {
128324fe890SDevang Patel       Modules.erase(I);
129091217beSJeffrey Yasskin       clearGlobalMappingsFromModule(M);
130091217beSJeffrey Yasskin       return true;
131324fe890SDevang Patel     }
132324fe890SDevang Patel   }
133091217beSJeffrey Yasskin   return false;
134617001d8SNate Begeman }
135617001d8SNate Begeman 
1360621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
1370621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
138091217beSJeffrey Yasskin     if (Function *F = Modules[i]->getFunction(FnName))
1390621caefSChris Lattner       return F;
1400621caefSChris Lattner   }
1412617dcceSCraig Topper   return nullptr;
1420621caefSChris Lattner }
1430621caefSChris Lattner 
1440621caefSChris Lattner 
145868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
146868e3f09SDaniel Dunbar                                           const GlobalValue *ToUnmap) {
147d0fc8f80SJeffrey Yasskin   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
148307c053fSJeffrey Yasskin   void *OldVal;
149868e3f09SDaniel Dunbar 
150868e3f09SDaniel Dunbar   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
151868e3f09SDaniel Dunbar   // GlobalAddressMap.
152307c053fSJeffrey Yasskin   if (I == GlobalAddressMap.end())
1532617dcceSCraig Topper     OldVal = nullptr;
154307c053fSJeffrey Yasskin   else {
155307c053fSJeffrey Yasskin     OldVal = I->second;
156307c053fSJeffrey Yasskin     GlobalAddressMap.erase(I);
157307c053fSJeffrey Yasskin   }
158307c053fSJeffrey Yasskin 
159307c053fSJeffrey Yasskin   GlobalAddressReverseMap.erase(OldVal);
160307c053fSJeffrey Yasskin   return OldVal;
161307c053fSJeffrey Yasskin }
162307c053fSJeffrey Yasskin 
1636d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
1646d8dd189SChris Lattner   MutexGuard locked(lock);
1656d8dd189SChris Lattner 
1660967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
1679813b0b0SDaniel Dunbar         << "\' to [" << Addr << "]\n";);
168d0fc8f80SJeffrey Yasskin   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
1692617dcceSCraig Topper   assert((!CurVal || !Addr) && "GlobalMapping already established!");
1706d8dd189SChris Lattner   CurVal = Addr;
1716d8dd189SChris Lattner 
172868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
173f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
1746bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
175f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
1762617dcceSCraig Topper     assert((!V || !GV) && "GlobalMapping already established!");
1776d8dd189SChris Lattner     V = GV;
1786d8dd189SChris Lattner   }
1796d8dd189SChris Lattner }
1806d8dd189SChris Lattner 
1816d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1826d8dd189SChris Lattner   MutexGuard locked(lock);
1836d8dd189SChris Lattner 
184f98e981cSJeffrey Yasskin   EEState.getGlobalAddressMap(locked).clear();
185f98e981cSJeffrey Yasskin   EEState.getGlobalAddressReverseMap(locked).clear();
1866d8dd189SChris Lattner }
1876d8dd189SChris Lattner 
1888f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
1898f83fc4dSNate Begeman   MutexGuard locked(lock);
1908f83fc4dSNate Begeman 
191868e3f09SDaniel Dunbar   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
192f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, FI);
1938f83fc4dSNate Begeman   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
194868e3f09SDaniel Dunbar        GI != GE; ++GI)
195f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, GI);
1968f83fc4dSNate Begeman }
1978f83fc4dSNate Begeman 
198ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1996d8dd189SChris Lattner   MutexGuard locked(lock);
2006d8dd189SChris Lattner 
201d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy &Map =
202f98e981cSJeffrey Yasskin     EEState.getGlobalAddressMap(locked);
203ee181730SChris Lattner 
2046d8dd189SChris Lattner   // Deleting from the mapping?
2052617dcceSCraig Topper   if (!Addr)
206f98e981cSJeffrey Yasskin     return EEState.RemoveMapping(locked, GV);
207ee181730SChris Lattner 
208d0fc8f80SJeffrey Yasskin   void *&CurVal = Map[GV];
209ee181730SChris Lattner   void *OldVal = CurVal;
210ee181730SChris Lattner 
211f98e981cSJeffrey Yasskin   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
212f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
2136d8dd189SChris Lattner   CurVal = Addr;
2146d8dd189SChris Lattner 
215868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
216f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
2176bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
218f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
2192617dcceSCraig Topper     assert((!V || !GV) && "GlobalMapping already established!");
2206d8dd189SChris Lattner     V = GV;
2216d8dd189SChris Lattner   }
222ee181730SChris Lattner   return OldVal;
2236d8dd189SChris Lattner }
2246d8dd189SChris Lattner 
2256d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
2266d8dd189SChris Lattner   MutexGuard locked(lock);
2276d8dd189SChris Lattner 
228d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy::iterator I =
229d0fc8f80SJeffrey Yasskin     EEState.getGlobalAddressMap(locked).find(GV);
2302617dcceSCraig Topper   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
2316d8dd189SChris Lattner }
2326d8dd189SChris Lattner 
233748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
23479876f52SReid Spencer   MutexGuard locked(lock);
23579876f52SReid Spencer 
236748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
237f98e981cSJeffrey Yasskin   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
238d0fc8f80SJeffrey Yasskin     for (ExecutionEngineState::GlobalAddressMapTy::iterator
239f98e981cSJeffrey Yasskin          I = EEState.getGlobalAddressMap(locked).begin(),
240f98e981cSJeffrey Yasskin          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
241e4f47434SDaniel Dunbar       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
242e4f47434SDaniel Dunbar                                                           I->second, I->first));
243748e8579SChris Lattner   }
244748e8579SChris Lattner 
2456bf87df5SJeffrey Yasskin   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
246f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).find(Addr);
2472617dcceSCraig Topper   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
248748e8579SChris Lattner }
2495a0d4829SChris Lattner 
250bfd38abbSJeffrey Yasskin namespace {
251bfd38abbSJeffrey Yasskin class ArgvArray {
252bfd38abbSJeffrey Yasskin   char *Array;
253bfd38abbSJeffrey Yasskin   std::vector<char*> Values;
254bfd38abbSJeffrey Yasskin public:
2552617dcceSCraig Topper   ArgvArray() : Array(nullptr) {}
256bfd38abbSJeffrey Yasskin   ~ArgvArray() { clear(); }
257bfd38abbSJeffrey Yasskin   void clear() {
258bfd38abbSJeffrey Yasskin     delete[] Array;
2592617dcceSCraig Topper     Array = nullptr;
260bfd38abbSJeffrey Yasskin     for (size_t I = 0, E = Values.size(); I != E; ++I) {
261bfd38abbSJeffrey Yasskin       delete[] Values[I];
262bfd38abbSJeffrey Yasskin     }
263bfd38abbSJeffrey Yasskin     Values.clear();
264bfd38abbSJeffrey Yasskin   }
265bfd38abbSJeffrey Yasskin   /// Turn a vector of strings into a nice argv style array of pointers to null
266bfd38abbSJeffrey Yasskin   /// terminated strings.
267bfd38abbSJeffrey Yasskin   void *reset(LLVMContext &C, ExecutionEngine *EE,
268bfd38abbSJeffrey Yasskin               const std::vector<std::string> &InputArgv);
269bfd38abbSJeffrey Yasskin };
270bfd38abbSJeffrey Yasskin }  // anonymous namespace
271bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
2725a0d4829SChris Lattner                        const std::vector<std::string> &InputArgv) {
273bfd38abbSJeffrey Yasskin   clear();  // Free the old contents.
2745da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
275bfd38abbSJeffrey Yasskin   Array = new char[(InputArgv.size()+1)*PtrSize];
2765a0d4829SChris Lattner 
277bfd38abbSJeffrey Yasskin   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
278229907cdSChris Lattner   Type *SBytePtr = Type::getInt8PtrTy(C);
2795a0d4829SChris Lattner 
2805a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
2815a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
2825a0d4829SChris Lattner     char *Dest = new char[Size];
283bfd38abbSJeffrey Yasskin     Values.push_back(Dest);
2840967d2dfSDavid Greene     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
2855a0d4829SChris Lattner 
2865a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
2875a0d4829SChris Lattner     Dest[Size-1] = 0;
2885a0d4829SChris Lattner 
289bfd38abbSJeffrey Yasskin     // Endian safe: Array[i] = (PointerTy)Dest;
290bfd38abbSJeffrey Yasskin     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
2915a0d4829SChris Lattner                            SBytePtr);
2925a0d4829SChris Lattner   }
2935a0d4829SChris Lattner 
2945a0d4829SChris Lattner   // Null terminate it
2952617dcceSCraig Topper   EE->StoreValueToMemory(PTOGV(nullptr),
296bfd38abbSJeffrey Yasskin                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
2975a0d4829SChris Lattner                          SBytePtr);
298bfd38abbSJeffrey Yasskin   return Array;
2995a0d4829SChris Lattner }
3005a0d4829SChris Lattner 
30141fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
30241fa2bd1SChris Lattner                                                        bool isDtors) {
303faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
3041a9a0b7bSEvan Cheng   GlobalVariable *GV = module->getNamedGlobal(Name);
305fe36eaebSChris Lattner 
306fe36eaebSChris Lattner   // If this global has internal linkage, or if it has a use, then it must be
307fe36eaebSChris Lattner   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
3080621caefSChris Lattner   // this is the case, don't execute any of the global ctors, __main will do
3090621caefSChris Lattner   // it.
3106de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
311faae50b6SChris Lattner 
3120cbfcb2bSNick Lewycky   // Should be an array of '{ i32, void ()* }' structs.  The first value is
3130621caefSChris Lattner   // the init priority, which we ignore.
31400245f42SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
3152617dcceSCraig Topper   if (!InitList)
3160f857898SNick Lewycky     return;
317868e3f09SDaniel Dunbar   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
31800245f42SChris Lattner     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
3192617dcceSCraig Topper     if (!CS) continue;
320faae50b6SChris Lattner 
321faae50b6SChris Lattner     Constant *FP = CS->getOperand(1);
322faae50b6SChris Lattner     if (FP->isNullValue())
3230f857898SNick Lewycky       continue;  // Found a sentinal value, ignore.
324faae50b6SChris Lattner 
325868e3f09SDaniel Dunbar     // Strip off constant expression casts.
326faae50b6SChris Lattner     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
3276c38f0bbSReid Spencer       if (CE->isCast())
328faae50b6SChris Lattner         FP = CE->getOperand(0);
329868e3f09SDaniel Dunbar 
330faae50b6SChris Lattner     // Execute the ctor/dtor function!
331868e3f09SDaniel Dunbar     if (Function *F = dyn_cast<Function>(FP))
332faae50b6SChris Lattner       runFunction(F, std::vector<GenericValue>());
333868e3f09SDaniel Dunbar 
334868e3f09SDaniel Dunbar     // FIXME: It is marginally lame that we just do nothing here if we see an
335868e3f09SDaniel Dunbar     // entry we don't recognize. It might not be unreasonable for the verifier
336868e3f09SDaniel Dunbar     // to not even allow this and just assert here.
337faae50b6SChris Lattner   }
338faae50b6SChris Lattner }
3391a9a0b7bSEvan Cheng 
3401a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
3411a9a0b7bSEvan Cheng   // Execute global ctors/dtors for each module in the program.
342868e3f09SDaniel Dunbar   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
343868e3f09SDaniel Dunbar     runStaticConstructorsDestructors(Modules[i], isDtors);
3440621caefSChris Lattner }
345faae50b6SChris Lattner 
346cf3e3017SDan Gohman #ifndef NDEBUG
3471202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
3481202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
3495da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
3501202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
3511202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
3521202d1b1SDuncan Sands       return false;
3531202d1b1SDuncan Sands   return true;
3541202d1b1SDuncan Sands }
355cf3e3017SDan Gohman #endif
3561202d1b1SDuncan Sands 
3575a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
3585a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
3595a0d4829SChris Lattner                                        const char * const * envp) {
3605a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
3615a0d4829SChris Lattner   GenericValue GVArgc;
36287aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
3638c32c111SAnton Korobeynikov 
3648c32c111SAnton Korobeynikov   // Check main() type
365b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
366229907cdSChris Lattner   FunctionType *FTy = Fn->getFunctionType();
367229907cdSChris Lattner   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
368868e3f09SDaniel Dunbar 
369868e3f09SDaniel Dunbar   // Check the argument types.
370868e3f09SDaniel Dunbar   if (NumArgs > 3)
3712104b8d3SChris Lattner     report_fatal_error("Invalid number of arguments of main() supplied");
372868e3f09SDaniel Dunbar   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
373868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for third argument of main() supplied");
374868e3f09SDaniel Dunbar   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
375868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for second argument of main() supplied");
376868e3f09SDaniel Dunbar   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
377868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for first argument of main() supplied");
378868e3f09SDaniel Dunbar   if (!FTy->getReturnType()->isIntegerTy() &&
379868e3f09SDaniel Dunbar       !FTy->getReturnType()->isVoidTy())
380868e3f09SDaniel Dunbar     report_fatal_error("Invalid return type of main() supplied");
3818c32c111SAnton Korobeynikov 
382bfd38abbSJeffrey Yasskin   ArgvArray CArgv;
383bfd38abbSJeffrey Yasskin   ArgvArray CEnv;
384b1cad0b3SChris Lattner   if (NumArgs) {
3855a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
386b1cad0b3SChris Lattner     if (NumArgs > 1) {
38755f1c09eSOwen Anderson       // Arg #1 = argv.
388bfd38abbSJeffrey Yasskin       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
3891202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
390b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
391b1cad0b3SChris Lattner       if (NumArgs > 2) {
3925a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3935a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3945a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
39555f1c09eSOwen Anderson         // Arg #2 = envp.
396bfd38abbSJeffrey Yasskin         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
397b1cad0b3SChris Lattner       }
398b1cad0b3SChris Lattner     }
399b1cad0b3SChris Lattner   }
400868e3f09SDaniel Dunbar 
40187aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
4025a0d4829SChris Lattner }
4035a0d4829SChris Lattner 
404091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M,
405603682adSReid Spencer                                          bool ForceInterpreter,
4067ff05bf5SEvan Cheng                                          std::string *ErrorStr,
40770415d97SJeffrey Yasskin                                          CodeGenOpt::Level OptLevel,
40870415d97SJeffrey Yasskin                                          bool GVsWithCode) {
409add6f1d2SOwen Anderson   EngineBuilder EB =  EngineBuilder(M)
410fc8a2d5aSReid Kleckner       .setEngineKind(ForceInterpreter
411fc8a2d5aSReid Kleckner                      ? EngineKind::Interpreter
412fc8a2d5aSReid Kleckner                      : EngineKind::JIT)
413fc8a2d5aSReid Kleckner       .setErrorStr(ErrorStr)
414fc8a2d5aSReid Kleckner       .setOptLevel(OptLevel)
415add6f1d2SOwen Anderson       .setAllocateGVsWithCode(GVsWithCode);
416add6f1d2SOwen Anderson 
417add6f1d2SOwen Anderson   return EB.create();
418fc8a2d5aSReid Kleckner }
4194bd3bd5bSBrian Gaeke 
4200bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current
4210bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter.  This takes ownership
4220bd34fbdSDylan Noblesmith /// of the module.
4230bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M,
4240bd34fbdSDylan Noblesmith                                             std::string *ErrorStr,
4250bd34fbdSDylan Noblesmith                                             JITMemoryManager *JMM,
42619a58df9SDylan Noblesmith                                             CodeGenOpt::Level OL,
4270bd34fbdSDylan Noblesmith                                             bool GVsWithCode,
4282129f596SEvan Cheng                                             Reloc::Model RM,
4290bd34fbdSDylan Noblesmith                                             CodeModel::Model CMM) {
4302617dcceSCraig Topper   if (!ExecutionEngine::JITCtor) {
4310bd34fbdSDylan Noblesmith     if (ErrorStr)
4320bd34fbdSDylan Noblesmith       *ErrorStr = "JIT has not been linked in.";
4332617dcceSCraig Topper     return nullptr;
4340bd34fbdSDylan Noblesmith   }
4350bd34fbdSDylan Noblesmith 
4360bd34fbdSDylan Noblesmith   // Use the defaults for extra parameters.  Users can use EngineBuilder to
4370bd34fbdSDylan Noblesmith   // set them.
438add6f1d2SOwen Anderson   EngineBuilder EB(M);
439add6f1d2SOwen Anderson   EB.setEngineKind(EngineKind::JIT);
440add6f1d2SOwen Anderson   EB.setErrorStr(ErrorStr);
441add6f1d2SOwen Anderson   EB.setRelocationModel(RM);
442add6f1d2SOwen Anderson   EB.setCodeModel(CMM);
443add6f1d2SOwen Anderson   EB.setAllocateGVsWithCode(GVsWithCode);
444add6f1d2SOwen Anderson   EB.setOptLevel(OL);
445add6f1d2SOwen Anderson   EB.setJITMemoryManager(JMM);
4460bd34fbdSDylan Noblesmith 
447dff24786SPeter Collingbourne   // TODO: permit custom TargetOptions here
448add6f1d2SOwen Anderson   TargetMachine *TM = EB.selectTarget();
4492617dcceSCraig Topper   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
4500bd34fbdSDylan Noblesmith 
4517f26246aSDylan Noblesmith   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
4520bd34fbdSDylan Noblesmith }
4530bd34fbdSDylan Noblesmith 
454add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
45556440fd8SAhmed Charles   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
45625a3d816SBenjamin Kramer 
457a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
458a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
4592617dcceSCraig Topper   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
4602617dcceSCraig Topper     return nullptr;
461a53414fdSNick Lewycky 
4629bc53e84SFilip Pizlo   assert(!(JMM && MCJMM));
4639bc53e84SFilip Pizlo 
464fc8a2d5aSReid Kleckner   // If the user specified a memory manager but didn't specify which engine to
465fc8a2d5aSReid Kleckner   // create, we assume they only want the JIT, and we fail if they only want
466fc8a2d5aSReid Kleckner   // the interpreter.
4679bc53e84SFilip Pizlo   if (JMM || MCJMM) {
46841fa2bd1SChris Lattner     if (WhichEngine & EngineKind::JIT)
469fc8a2d5aSReid Kleckner       WhichEngine = EngineKind::JIT;
47041fa2bd1SChris Lattner     else {
4718bcc6445SChris Lattner       if (ErrorStr)
472fc8a2d5aSReid Kleckner         *ErrorStr = "Cannot create an interpreter with a memory manager.";
4732617dcceSCraig Topper       return nullptr;
474fc8a2d5aSReid Kleckner     }
4754bd3bd5bSBrian Gaeke   }
4764bd3bd5bSBrian Gaeke 
4779bc53e84SFilip Pizlo   if (MCJMM && ! UseMCJIT) {
4789bc53e84SFilip Pizlo     if (ErrorStr)
4799bc53e84SFilip Pizlo       *ErrorStr =
4809bc53e84SFilip Pizlo         "Cannot create a legacy JIT with a runtime dyld memory "
4819bc53e84SFilip Pizlo         "manager.";
4822617dcceSCraig Topper     return nullptr;
4839bc53e84SFilip Pizlo   }
4849bc53e84SFilip Pizlo 
485fc8a2d5aSReid Kleckner   // Unless the interpreter was explicitly selected or the JIT is not linked,
486fc8a2d5aSReid Kleckner   // try making a JIT.
48725a3d816SBenjamin Kramer   if ((WhichEngine & EngineKind::JIT) && TheTM) {
4887f26246aSDylan Noblesmith     Triple TT(M->getTargetTriple());
4897f26246aSDylan Noblesmith     if (!TM->getTarget().hasJIT()) {
4907f26246aSDylan Noblesmith       errs() << "WARNING: This target JIT is not designed for the host"
4917f26246aSDylan Noblesmith              << " you are running.  If bad things happen, please choose"
4927f26246aSDylan Noblesmith              << " a different -march switch.\n";
4937f26246aSDylan Noblesmith     }
4947f26246aSDylan Noblesmith 
495*bc876017SLang Hames     ExecutionEngine *EE = nullptr;
496*bc876017SLang Hames     if (UseMCJIT && ExecutionEngine::MCJITCtor)
497*bc876017SLang Hames       EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
49896c9d95fSAhmed Charles                                       AllocateGVsWithCode, TheTM.release());
499*bc876017SLang Hames     else if (ExecutionEngine::JITCtor)
500*bc876017SLang Hames       EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
50196c9d95fSAhmed Charles                                     AllocateGVsWithCode, TheTM.release());
502*bc876017SLang Hames 
503*bc876017SLang Hames     if (EE) {
504*bc876017SLang Hames       EE->setVerifyModules(VerifyModules);
505*bc876017SLang Hames       return EE;
50641fa2bd1SChris Lattner     }
507fc8a2d5aSReid Kleckner   }
508fc8a2d5aSReid Kleckner 
509fc8a2d5aSReid Kleckner   // If we can't make a JIT and we didn't request one specifically, try making
510fc8a2d5aSReid Kleckner   // an interpreter instead.
51141fa2bd1SChris Lattner   if (WhichEngine & EngineKind::Interpreter) {
51241fa2bd1SChris Lattner     if (ExecutionEngine::InterpCtor)
513091217beSJeffrey Yasskin       return ExecutionEngine::InterpCtor(M, ErrorStr);
5148bcc6445SChris Lattner     if (ErrorStr)
51541fa2bd1SChris Lattner       *ErrorStr = "Interpreter has not been linked in.";
5162617dcceSCraig Topper     return nullptr;
517fc8a2d5aSReid Kleckner   }
518fc8a2d5aSReid Kleckner 
5192617dcceSCraig Topper   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
5202617dcceSCraig Topper       !ExecutionEngine::MCJITCtor) {
5218bcc6445SChris Lattner     if (ErrorStr)
5228bcc6445SChris Lattner       *ErrorStr = "JIT has not been linked in.";
5238bcc6445SChris Lattner   }
524868e3f09SDaniel Dunbar 
5252617dcceSCraig Topper   return nullptr;
526b5163bb9SChris Lattner }
527b5163bb9SChris Lattner 
528996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
5291678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
530996fe010SChris Lattner     return getPointerToFunction(F);
531996fe010SChris Lattner 
53279876f52SReid Spencer   MutexGuard locked(lock);
533868e3f09SDaniel Dunbar   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
534868e3f09SDaniel Dunbar     return P;
53569e84901SJeff Cohen 
53669e84901SJeff Cohen   // Global variable might have been added since interpreter started.
53769e84901SJeff Cohen   if (GlobalVariable *GVar =
53869e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
53969e84901SJeff Cohen     EmitGlobalVariable(GVar);
54069e84901SJeff Cohen   else
541fbcc663cSTorok Edwin     llvm_unreachable("Global hasn't had an address allocated yet!");
542868e3f09SDaniel Dunbar 
543d0fc8f80SJeffrey Yasskin   return EEState.getGlobalAddressMap(locked)[GV];
544996fe010SChris Lattner }
545996fe010SChris Lattner 
546868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of
547868e3f09SDaniel Dunbar /// ConstantExpr values.
548996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
5496c38f0bbSReid Spencer   // If its undefined, return the garbage.
550bcbdbfb3SJay Foad   if (isa<UndefValue>(C)) {
551bcbdbfb3SJay Foad     GenericValue Result;
552bcbdbfb3SJay Foad     switch (C->getType()->getTypeID()) {
553be79a7acSNadav Rotem     default:
554be79a7acSNadav Rotem       break;
555bcbdbfb3SJay Foad     case Type::IntegerTyID:
556bcbdbfb3SJay Foad     case Type::X86_FP80TyID:
557bcbdbfb3SJay Foad     case Type::FP128TyID:
558bcbdbfb3SJay Foad     case Type::PPC_FP128TyID:
559bcbdbfb3SJay Foad       // Although the value is undefined, we still have to construct an APInt
560bcbdbfb3SJay Foad       // with the correct bit width.
561bcbdbfb3SJay Foad       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
562bcbdbfb3SJay Foad       break;
5638e97f016SElena Demikhovsky     case Type::StructTyID: {
5648e97f016SElena Demikhovsky       // if the whole struct is 'undef' just reserve memory for the value.
5658e97f016SElena Demikhovsky       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
5668e97f016SElena Demikhovsky         unsigned int elemNum = STy->getNumElements();
5678e97f016SElena Demikhovsky         Result.AggregateVal.resize(elemNum);
5688e97f016SElena Demikhovsky         for (unsigned int i = 0; i < elemNum; ++i) {
5698e97f016SElena Demikhovsky           Type *ElemTy = STy->getElementType(i);
5708e97f016SElena Demikhovsky           if (ElemTy->isIntegerTy())
5718e97f016SElena Demikhovsky             Result.AggregateVal[i].IntVal =
5728e97f016SElena Demikhovsky               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
5738e97f016SElena Demikhovsky           else if (ElemTy->isAggregateType()) {
5748e97f016SElena Demikhovsky               const Constant *ElemUndef = UndefValue::get(ElemTy);
5758e97f016SElena Demikhovsky               Result.AggregateVal[i] = getConstantValue(ElemUndef);
5768e97f016SElena Demikhovsky             }
5778e97f016SElena Demikhovsky           }
5788e97f016SElena Demikhovsky         }
5798e97f016SElena Demikhovsky       }
5808e97f016SElena Demikhovsky       break;
581be79a7acSNadav Rotem     case Type::VectorTyID:
582be79a7acSNadav Rotem       // if the whole vector is 'undef' just reserve memory for the value.
583be79a7acSNadav Rotem       const VectorType* VTy = dyn_cast<VectorType>(C->getType());
584be79a7acSNadav Rotem       const Type *ElemTy = VTy->getElementType();
585be79a7acSNadav Rotem       unsigned int elemNum = VTy->getNumElements();
586be79a7acSNadav Rotem       Result.AggregateVal.resize(elemNum);
587be79a7acSNadav Rotem       if (ElemTy->isIntegerTy())
588be79a7acSNadav Rotem         for (unsigned int i = 0; i < elemNum; ++i)
589be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal =
590be79a7acSNadav Rotem             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
591bcbdbfb3SJay Foad       break;
592bcbdbfb3SJay Foad     }
593bcbdbfb3SJay Foad     return Result;
594bcbdbfb3SJay Foad   }
5959de0d14dSChris Lattner 
596868e3f09SDaniel Dunbar   // Otherwise, if the value is a ConstantExpr...
5976c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5984fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
5999de0d14dSChris Lattner     switch (CE->getOpcode()) {
6009de0d14dSChris Lattner     case Instruction::GetElementPtr: {
6016c38f0bbSReid Spencer       // Compute the index
6024fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
6037c68bebbSRafael Espindola       APInt Offset(DL->getPointerSizeInBits(), 0);
6047c68bebbSRafael Espindola       cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
6059de0d14dSChris Lattner 
60687aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
607b6ad9822SNuno Lopes       Result = PTOGV(tmp + Offset.getSExtValue());
6089de0d14dSChris Lattner       return Result;
6099de0d14dSChris Lattner     }
6104fd528f2SReid Spencer     case Instruction::Trunc: {
6114fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6124fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6134fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
6144fd528f2SReid Spencer       return GV;
6154fd528f2SReid Spencer     }
6164fd528f2SReid Spencer     case Instruction::ZExt: {
6174fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6184fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6194fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
6204fd528f2SReid Spencer       return GV;
6214fd528f2SReid Spencer     }
6224fd528f2SReid Spencer     case Instruction::SExt: {
6234fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6244fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6254fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
6264fd528f2SReid Spencer       return GV;
6274fd528f2SReid Spencer     }
6284fd528f2SReid Spencer     case Instruction::FPTrunc: {
629a1336cf5SDale Johannesen       // FIXME long double
6304fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6314fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
6324fd528f2SReid Spencer       return GV;
6334fd528f2SReid Spencer     }
6344fd528f2SReid Spencer     case Instruction::FPExt:{
635a1336cf5SDale Johannesen       // FIXME long double
6364fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6374fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
6384fd528f2SReid Spencer       return GV;
6394fd528f2SReid Spencer     }
6404fd528f2SReid Spencer     case Instruction::UIToFP: {
6414fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
642fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6434fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
644fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6454fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
646fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
64731920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
648ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
649ca24fd90SDan Gohman                                    false,
6509150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
65154306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
652a1336cf5SDale Johannesen       }
6534fd528f2SReid Spencer       return GV;
6544fd528f2SReid Spencer     }
6554fd528f2SReid Spencer     case Instruction::SIToFP: {
6564fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
657fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6584fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
659fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6604fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
661fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
66231920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
663ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
664ca24fd90SDan Gohman                                    true,
6659150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
66654306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
667a1336cf5SDale Johannesen       }
6684fd528f2SReid Spencer       return GV;
6694fd528f2SReid Spencer     }
6704fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
6714fd528f2SReid Spencer     case Instruction::FPToSI: {
6724fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6734fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
674fdd87907SChris Lattner       if (Op0->getType()->isFloatTy())
6754fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
676fdd87907SChris Lattner       else if (Op0->getType()->isDoubleTy())
6774fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
678fdd87907SChris Lattner       else if (Op0->getType()->isX86_FP80Ty()) {
67929178a34STim Northover         APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
680a1336cf5SDale Johannesen         uint64_t v;
6814f0bd68cSDale Johannesen         bool ignored;
682a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
683a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
6844f0bd68cSDale Johannesen                                    APFloat::rmTowardZero, &ignored);
685a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
686a1336cf5SDale Johannesen       }
6874fd528f2SReid Spencer       return GV;
6884fd528f2SReid Spencer     }
6896c38f0bbSReid Spencer     case Instruction::PtrToInt: {
6904fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6917c68bebbSRafael Espindola       uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
692fc1f2cd3SEli Friedman       assert(PtrWidth <= 64 && "Bad pointer width");
6934fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
6947c68bebbSRafael Espindola       uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
695fc1f2cd3SEli Friedman       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
6964fd528f2SReid Spencer       return GV;
6974fd528f2SReid Spencer     }
6984fd528f2SReid Spencer     case Instruction::IntToPtr: {
6994fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
7007c68bebbSRafael Espindola       uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
7014fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
7024fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
7034fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
7046c38f0bbSReid Spencer       return GV;
7056c38f0bbSReid Spencer     }
7066c38f0bbSReid Spencer     case Instruction::BitCast: {
7074fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
708229907cdSChris Lattner       Type* DestTy = CE->getType();
7094fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
710fbcc663cSTorok Edwin         default: llvm_unreachable("Invalid bitcast operand");
7114fd528f2SReid Spencer         case Type::IntegerTyID:
7129dff9becSDuncan Sands           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
713fdd87907SChris Lattner           if (DestTy->isFloatTy())
7144fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
715fdd87907SChris Lattner           else if (DestTy->isDoubleTy())
7164fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
7176c38f0bbSReid Spencer           break;
7184fd528f2SReid Spencer         case Type::FloatTyID:
7199dff9becSDuncan Sands           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
7203447fb01SJay Foad           GV.IntVal = APInt::floatToBits(GV.FloatVal);
7214fd528f2SReid Spencer           break;
7224fd528f2SReid Spencer         case Type::DoubleTyID:
7239dff9becSDuncan Sands           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
7243447fb01SJay Foad           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
7254fd528f2SReid Spencer           break;
7264fd528f2SReid Spencer         case Type::PointerTyID:
72719d0b47bSDuncan Sands           assert(DestTy->isPointerTy() && "Invalid bitcast");
7284fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
7296c38f0bbSReid Spencer       }
7304fd528f2SReid Spencer       return GV;
73168cbcc3eSChris Lattner     }
73268cbcc3eSChris Lattner     case Instruction::Add:
733a5b9645cSDan Gohman     case Instruction::FAdd:
7344fd528f2SReid Spencer     case Instruction::Sub:
735a5b9645cSDan Gohman     case Instruction::FSub:
7364fd528f2SReid Spencer     case Instruction::Mul:
737a5b9645cSDan Gohman     case Instruction::FMul:
7384fd528f2SReid Spencer     case Instruction::UDiv:
7394fd528f2SReid Spencer     case Instruction::SDiv:
7404fd528f2SReid Spencer     case Instruction::URem:
7414fd528f2SReid Spencer     case Instruction::SRem:
7424fd528f2SReid Spencer     case Instruction::And:
7434fd528f2SReid Spencer     case Instruction::Or:
7444fd528f2SReid Spencer     case Instruction::Xor: {
7454fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
7464fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
7474fd528f2SReid Spencer       GenericValue GV;
748c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
749fbcc663cSTorok Edwin       default: llvm_unreachable("Bad add type!");
7507a9c62baSReid Spencer       case Type::IntegerTyID:
7514fd528f2SReid Spencer         switch (CE->getOpcode()) {
752fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid integer opcode");
7534fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
7544fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
7554fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
7564fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
7574fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
7584fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
7594fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
7604fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
7614fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
7624fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
7634fd528f2SReid Spencer         }
764c4e6bb5fSChris Lattner         break;
765c4e6bb5fSChris Lattner       case Type::FloatTyID:
7664fd528f2SReid Spencer         switch (CE->getOpcode()) {
767fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid float opcode");
768a5b9645cSDan Gohman           case Instruction::FAdd:
7694fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
770a5b9645cSDan Gohman           case Instruction::FSub:
7714fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
772a5b9645cSDan Gohman           case Instruction::FMul:
7734fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
7744fd528f2SReid Spencer           case Instruction::FDiv:
7754fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
7764fd528f2SReid Spencer           case Instruction::FRem:
77793cd0f1cSChris Lattner             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
7784fd528f2SReid Spencer         }
779c4e6bb5fSChris Lattner         break;
780c4e6bb5fSChris Lattner       case Type::DoubleTyID:
7814fd528f2SReid Spencer         switch (CE->getOpcode()) {
782fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid double opcode");
783a5b9645cSDan Gohman           case Instruction::FAdd:
7844fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
785a5b9645cSDan Gohman           case Instruction::FSub:
7864fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
787a5b9645cSDan Gohman           case Instruction::FMul:
7884fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
7894fd528f2SReid Spencer           case Instruction::FDiv:
7904fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
7914fd528f2SReid Spencer           case Instruction::FRem:
79293cd0f1cSChris Lattner             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
7934fd528f2SReid Spencer         }
794c4e6bb5fSChris Lattner         break;
795a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
796a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
797a1336cf5SDale Johannesen       case Type::FP128TyID: {
79829178a34STim Northover         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
79929178a34STim Northover         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
800a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
801e4f47434SDaniel Dunbar           default: llvm_unreachable("Invalid long double opcode");
802a5b9645cSDan Gohman           case Instruction::FAdd:
80329178a34STim Northover             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
80454306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
805a1336cf5SDale Johannesen             break;
806a5b9645cSDan Gohman           case Instruction::FSub:
80729178a34STim Northover             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
80829178a34STim Northover                             APFloat::rmNearestTiesToEven);
80954306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
810a1336cf5SDale Johannesen             break;
811a5b9645cSDan Gohman           case Instruction::FMul:
81229178a34STim Northover             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
81329178a34STim Northover                             APFloat::rmNearestTiesToEven);
81454306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
815a1336cf5SDale Johannesen             break;
816a1336cf5SDale Johannesen           case Instruction::FDiv:
81729178a34STim Northover             apfLHS.divide(APFloat(Sem, RHS.IntVal),
81829178a34STim Northover                           APFloat::rmNearestTiesToEven);
81954306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
820a1336cf5SDale Johannesen             break;
821a1336cf5SDale Johannesen           case Instruction::FRem:
82229178a34STim Northover             apfLHS.mod(APFloat(Sem, RHS.IntVal),
82329178a34STim Northover                        APFloat::rmNearestTiesToEven);
82454306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
825a1336cf5SDale Johannesen             break;
826a1336cf5SDale Johannesen           }
827a1336cf5SDale Johannesen         }
828a1336cf5SDale Johannesen         break;
829c4e6bb5fSChris Lattner       }
8304fd528f2SReid Spencer       return GV;
8314fd528f2SReid Spencer     }
8329de0d14dSChris Lattner     default:
83368cbcc3eSChris Lattner       break;
83468cbcc3eSChris Lattner     }
835868e3f09SDaniel Dunbar 
836868e3f09SDaniel Dunbar     SmallString<256> Msg;
837868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
838868e3f09SDaniel Dunbar     OS << "ConstantExpr not handled: " << *CE;
839868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
8409de0d14dSChris Lattner   }
841996fe010SChris Lattner 
842868e3f09SDaniel Dunbar   // Otherwise, we have a simple constant.
8434fd528f2SReid Spencer   GenericValue Result;
8446b727599SChris Lattner   switch (C->getType()->getTypeID()) {
84587aa65f4SReid Spencer   case Type::FloatTyID:
846bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
8477a9c62baSReid Spencer     break;
84887aa65f4SReid Spencer   case Type::DoubleTyID:
849bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
85087aa65f4SReid Spencer     break;
851a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
852a1336cf5SDale Johannesen   case Type::FP128TyID:
853a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
85454306fe4SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
855a1336cf5SDale Johannesen     break;
85687aa65f4SReid Spencer   case Type::IntegerTyID:
85787aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
85887aa65f4SReid Spencer     break;
859996fe010SChris Lattner   case Type::PointerTyID:
8606a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
8612617dcceSCraig Topper       Result.PointerVal = nullptr;
8626a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
8636a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
8646a0fd73bSReid Spencer     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
8656a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
8660c778f70SChris Lattner     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
8670c778f70SChris Lattner       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
8680c778f70SChris Lattner                                                         BA->getBasicBlock())));
869e6492f10SChris Lattner     else
870fbcc663cSTorok Edwin       llvm_unreachable("Unknown constant pointer type!");
871996fe010SChris Lattner     break;
872be79a7acSNadav Rotem   case Type::VectorTyID: {
873be79a7acSNadav Rotem     unsigned elemNum;
874be79a7acSNadav Rotem     Type* ElemTy;
875be79a7acSNadav Rotem     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
876be79a7acSNadav Rotem     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
877be79a7acSNadav Rotem     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
878be79a7acSNadav Rotem 
879be79a7acSNadav Rotem     if (CDV) {
880be79a7acSNadav Rotem         elemNum = CDV->getNumElements();
881be79a7acSNadav Rotem         ElemTy = CDV->getElementType();
882be79a7acSNadav Rotem     } else if (CV || CAZ) {
883be79a7acSNadav Rotem         VectorType* VTy = dyn_cast<VectorType>(C->getType());
884be79a7acSNadav Rotem         elemNum = VTy->getNumElements();
885be79a7acSNadav Rotem         ElemTy = VTy->getElementType();
886be79a7acSNadav Rotem     } else {
887be79a7acSNadav Rotem         llvm_unreachable("Unknown constant vector type!");
888be79a7acSNadav Rotem     }
889be79a7acSNadav Rotem 
890be79a7acSNadav Rotem     Result.AggregateVal.resize(elemNum);
891be79a7acSNadav Rotem     // Check if vector holds floats.
892be79a7acSNadav Rotem     if(ElemTy->isFloatTy()) {
893be79a7acSNadav Rotem       if (CAZ) {
894be79a7acSNadav Rotem         GenericValue floatZero;
895be79a7acSNadav Rotem         floatZero.FloatVal = 0.f;
896be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
897be79a7acSNadav Rotem                   floatZero);
898be79a7acSNadav Rotem         break;
899be79a7acSNadav Rotem       }
900be79a7acSNadav Rotem       if(CV) {
901be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
902be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
903be79a7acSNadav Rotem             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
904be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToFloat();
905be79a7acSNadav Rotem         break;
906be79a7acSNadav Rotem       }
907be79a7acSNadav Rotem       if(CDV)
908be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
909be79a7acSNadav Rotem           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
910be79a7acSNadav Rotem 
911be79a7acSNadav Rotem       break;
912be79a7acSNadav Rotem     }
913be79a7acSNadav Rotem     // Check if vector holds doubles.
914be79a7acSNadav Rotem     if (ElemTy->isDoubleTy()) {
915be79a7acSNadav Rotem       if (CAZ) {
916be79a7acSNadav Rotem         GenericValue doubleZero;
917be79a7acSNadav Rotem         doubleZero.DoubleVal = 0.0;
918be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
919be79a7acSNadav Rotem                   doubleZero);
920be79a7acSNadav Rotem         break;
921be79a7acSNadav Rotem       }
922be79a7acSNadav Rotem       if(CV) {
923be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
924be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
925be79a7acSNadav Rotem             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
926be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToDouble();
927be79a7acSNadav Rotem         break;
928be79a7acSNadav Rotem       }
929be79a7acSNadav Rotem       if(CDV)
930be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
931be79a7acSNadav Rotem           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
932be79a7acSNadav Rotem 
933be79a7acSNadav Rotem       break;
934be79a7acSNadav Rotem     }
935be79a7acSNadav Rotem     // Check if vector holds integers.
936be79a7acSNadav Rotem     if (ElemTy->isIntegerTy()) {
937be79a7acSNadav Rotem       if (CAZ) {
938be79a7acSNadav Rotem         GenericValue intZero;
939be79a7acSNadav Rotem         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
940be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
941be79a7acSNadav Rotem                   intZero);
942be79a7acSNadav Rotem         break;
943be79a7acSNadav Rotem       }
944be79a7acSNadav Rotem       if(CV) {
945be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
946be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
947be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
948be79a7acSNadav Rotem                                             CV->getOperand(i))->getValue();
949be79a7acSNadav Rotem           else {
950be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal =
951be79a7acSNadav Rotem               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
952be79a7acSNadav Rotem           }
953be79a7acSNadav Rotem         break;
954be79a7acSNadav Rotem       }
955be79a7acSNadav Rotem       if(CDV)
956be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
957be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal = APInt(
958be79a7acSNadav Rotem             CDV->getElementType()->getPrimitiveSizeInBits(),
959be79a7acSNadav Rotem             CDV->getElementAsInteger(i));
960be79a7acSNadav Rotem 
961be79a7acSNadav Rotem       break;
962be79a7acSNadav Rotem     }
963be79a7acSNadav Rotem     llvm_unreachable("Unknown constant pointer type!");
964be79a7acSNadav Rotem   }
965be79a7acSNadav Rotem   break;
966be79a7acSNadav Rotem 
967996fe010SChris Lattner   default:
968868e3f09SDaniel Dunbar     SmallString<256> Msg;
969868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
970868e3f09SDaniel Dunbar     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
971868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
972996fe010SChris Lattner   }
973868e3f09SDaniel Dunbar 
974996fe010SChris Lattner   return Result;
975996fe010SChris Lattner }
976996fe010SChris Lattner 
9771202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
9781202d1b1SDuncan Sands /// with the integer held in IntVal.
9791202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
9801202d1b1SDuncan Sands                              unsigned StoreBytes) {
9811202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
982ad06cee2SRoman Divacky   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
9835c65cb46SDuncan Sands 
98441cb64f4SRafael Espindola   if (sys::IsLittleEndianHost) {
9851202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
9861202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
9875c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
988868e3f09SDaniel Dunbar   } else {
9895c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
9901202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
9911202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
9925c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
9935c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
9945c65cb46SDuncan Sands       // May not be aligned so use memcpy.
9955c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
9965c65cb46SDuncan Sands       Src += sizeof(uint64_t);
9975c65cb46SDuncan Sands     }
9985c65cb46SDuncan Sands 
9995c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1000815f8dd2SReid Spencer   }
10017a9c62baSReid Spencer }
10021202d1b1SDuncan Sands 
100309053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1004229907cdSChris Lattner                                          GenericValue *Ptr, Type *Ty) {
1005cdfe20b9SMicah Villmow   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
10061202d1b1SDuncan Sands 
10071202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
1008be79a7acSNadav Rotem   default:
1009be79a7acSNadav Rotem     dbgs() << "Cannot store value of type " << *Ty << "!\n";
1010be79a7acSNadav Rotem     break;
10111202d1b1SDuncan Sands   case Type::IntegerTyID:
10121202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
10131202d1b1SDuncan Sands     break;
1014996fe010SChris Lattner   case Type::FloatTyID:
101587aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
101687aa65f4SReid Spencer     break;
101787aa65f4SReid Spencer   case Type::DoubleTyID:
101887aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
1019996fe010SChris Lattner     break;
10204d7e4ee7SDale Johannesen   case Type::X86_FP80TyID:
10214d7e4ee7SDale Johannesen     memcpy(Ptr, Val.IntVal.getRawData(), 10);
1022a1336cf5SDale Johannesen     break;
10237a9c62baSReid Spencer   case Type::PointerTyID:
10241202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
10251202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
102693da3c82SChandler Carruth       memset(&(Ptr->PointerVal), 0, StoreBytes);
10271202d1b1SDuncan Sands 
102887aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
1029996fe010SChris Lattner     break;
1030be79a7acSNadav Rotem   case Type::VectorTyID:
1031be79a7acSNadav Rotem     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1032be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1033be79a7acSNadav Rotem         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1034be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1035be79a7acSNadav Rotem         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1036be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1037be79a7acSNadav Rotem         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1038be79a7acSNadav Rotem         StoreIntToMemory(Val.AggregateVal[i].IntVal,
1039be79a7acSNadav Rotem           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1040be79a7acSNadav Rotem       }
1041be79a7acSNadav Rotem     }
1042be79a7acSNadav Rotem     break;
1043996fe010SChris Lattner   }
10441202d1b1SDuncan Sands 
104541cb64f4SRafael Espindola   if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
10461202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
10471202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1048996fe010SChris Lattner }
1049996fe010SChris Lattner 
10501202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
10511202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
10521202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
10531202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
105482b63578SDavid Greene   uint8_t *Dst = reinterpret_cast<uint8_t *>(
105582b63578SDavid Greene                    const_cast<uint64_t *>(IntVal.getRawData()));
10565c65cb46SDuncan Sands 
105741cb64f4SRafael Espindola   if (sys::IsLittleEndianHost)
10585c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
10595c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
10605c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
10615c65cb46SDuncan Sands   else {
10625c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
10635c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
10645c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
10655c65cb46SDuncan Sands     // a word.
10665c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
10675c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
10685c65cb46SDuncan Sands       // May not be aligned so use memcpy.
10695c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
10705c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
10715c65cb46SDuncan Sands     }
10725c65cb46SDuncan Sands 
10735c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
10745c65cb46SDuncan Sands   }
10757a9c62baSReid Spencer }
10761202d1b1SDuncan Sands 
10771202d1b1SDuncan Sands /// FIXME: document
10781202d1b1SDuncan Sands ///
10791202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
10801202d1b1SDuncan Sands                                           GenericValue *Ptr,
1081229907cdSChris Lattner                                           Type *Ty) {
1082cdfe20b9SMicah Villmow   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
10831202d1b1SDuncan Sands 
10841202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
10851202d1b1SDuncan Sands   case Type::IntegerTyID:
10861202d1b1SDuncan Sands     // An APInt with all words initially zero.
10871202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
10881202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
10891202d1b1SDuncan Sands     break;
10907f389e8cSChris Lattner   case Type::FloatTyID:
109187aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
109287aa65f4SReid Spencer     break;
109387aa65f4SReid Spencer   case Type::DoubleTyID:
109487aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
10957f389e8cSChris Lattner     break;
10967a9c62baSReid Spencer   case Type::PointerTyID:
109787aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
10987f389e8cSChris Lattner     break;
1099a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
1100a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
110126d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
1102ff306287SDuncan Sands     uint64_t y[2];
11034d7e4ee7SDale Johannesen     memcpy(y, Ptr, 10);
11047a162881SJeffrey Yasskin     Result.IntVal = APInt(80, y);
1105a1336cf5SDale Johannesen     break;
1106a1336cf5SDale Johannesen   }
1107be79a7acSNadav Rotem   case Type::VectorTyID: {
1108be79a7acSNadav Rotem     const VectorType *VT = cast<VectorType>(Ty);
1109be79a7acSNadav Rotem     const Type *ElemT = VT->getElementType();
1110be79a7acSNadav Rotem     const unsigned numElems = VT->getNumElements();
1111be79a7acSNadav Rotem     if (ElemT->isFloatTy()) {
1112be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1113be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1114be79a7acSNadav Rotem         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1115be79a7acSNadav Rotem     }
1116be79a7acSNadav Rotem     if (ElemT->isDoubleTy()) {
1117be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1118be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1119be79a7acSNadav Rotem         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1120be79a7acSNadav Rotem     }
1121be79a7acSNadav Rotem     if (ElemT->isIntegerTy()) {
1122be79a7acSNadav Rotem       GenericValue intZero;
1123be79a7acSNadav Rotem       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1124be79a7acSNadav Rotem       intZero.IntVal = APInt(elemBitWidth, 0);
1125be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems, intZero);
1126be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1127be79a7acSNadav Rotem         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1128be79a7acSNadav Rotem           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1129be79a7acSNadav Rotem     }
1130be79a7acSNadav Rotem   break;
1131be79a7acSNadav Rotem   }
11327f389e8cSChris Lattner   default:
1133868e3f09SDaniel Dunbar     SmallString<256> Msg;
1134868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
1135868e3f09SDaniel Dunbar     OS << "Cannot load value of type " << *Ty << "!";
1136868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
11377f389e8cSChris Lattner   }
11387f389e8cSChris Lattner }
11397f389e8cSChris Lattner 
1140996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
11410967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1142b086d382SDale Johannesen   DEBUG(Init->dump());
114300245f42SChris Lattner   if (isa<UndefValue>(Init))
114461753bf8SChris Lattner     return;
114500245f42SChris Lattner 
114600245f42SChris Lattner   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
114769d62138SRobert Bocchino     unsigned ElementSize =
1148cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
114969d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
115069d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
115169d62138SRobert Bocchino     return;
115200245f42SChris Lattner   }
115300245f42SChris Lattner 
115400245f42SChris Lattner   if (isa<ConstantAggregateZero>(Init)) {
1155cdfe20b9SMicah Villmow     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
11561dd86b11SChris Lattner     return;
115700245f42SChris Lattner   }
115800245f42SChris Lattner 
115900245f42SChris Lattner   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
116069ddfbfeSDan Gohman     unsigned ElementSize =
1161cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
116269ddfbfeSDan Gohman     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
116369ddfbfeSDan Gohman       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
116469ddfbfeSDan Gohman     return;
116500245f42SChris Lattner   }
116600245f42SChris Lattner 
116700245f42SChris Lattner   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
116869ddfbfeSDan Gohman     const StructLayout *SL =
1169cdfe20b9SMicah Villmow       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
117069ddfbfeSDan Gohman     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
117169ddfbfeSDan Gohman       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
117269ddfbfeSDan Gohman     return;
117300245f42SChris Lattner   }
117400245f42SChris Lattner 
117500245f42SChris Lattner   if (const ConstantDataSequential *CDS =
117600245f42SChris Lattner                dyn_cast<ConstantDataSequential>(Init)) {
117700245f42SChris Lattner     // CDS is already laid out in host memory order.
117800245f42SChris Lattner     StringRef Data = CDS->getRawDataValues();
117900245f42SChris Lattner     memcpy(Addr, Data.data(), Data.size());
118000245f42SChris Lattner     return;
118100245f42SChris Lattner   }
118200245f42SChris Lattner 
118300245f42SChris Lattner   if (Init->getType()->isFirstClassType()) {
1184996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
1185996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1186996fe010SChris Lattner     return;
1187996fe010SChris Lattner   }
1188996fe010SChris Lattner 
1189868e3f09SDaniel Dunbar   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1190fbcc663cSTorok Edwin   llvm_unreachable("Unknown constant type to initialize memory with!");
1191996fe010SChris Lattner }
1192996fe010SChris Lattner 
1193996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
1194996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
1195996fe010SChris Lattner /// their initializers into the memory.
1196996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
1197996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
11980621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
11990621caefSChris Lattner   // to figure out how the different modules should link together.
1200229907cdSChris Lattner   std::map<std::pair<std::string, Type*>,
12010621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
12020621caefSChris Lattner 
12030621caefSChris Lattner   if (Modules.size() != 1) {
12040621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1205091217beSJeffrey Yasskin       Module &M = *Modules[m];
12060621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
12070621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
12080621caefSChris Lattner         const GlobalValue *GV = I;
12096de96a1bSRafael Espindola         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
12100621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
12110621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
12120621caefSChris Lattner 
12130621caefSChris Lattner         const GlobalValue *&GVEntry =
12140621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
12150621caefSChris Lattner 
12160621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
12170621caefSChris Lattner         // version.
12180621caefSChris Lattner         if (!GVEntry) {
12190621caefSChris Lattner           GVEntry = GV;
12200621caefSChris Lattner           continue;
12210621caefSChris Lattner         }
12220621caefSChris Lattner 
12230621caefSChris Lattner         // If the existing global is strong, never replace it.
12247157bb76SNico Rieck         if (GVEntry->hasExternalLinkage())
12250621caefSChris Lattner           continue;
12260621caefSChris Lattner 
12270621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1228ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
122912c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
12300621caefSChris Lattner           GVEntry = GV;
12310621caefSChris Lattner       }
12320621caefSChris Lattner     }
12330621caefSChris Lattner   }
12340621caefSChris Lattner 
12350621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
12360621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1237091217beSJeffrey Yasskin     Module &M = *Modules[m];
12388ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
12390621caefSChris Lattner          I != E; ++I) {
12400621caefSChris Lattner       // In the multi-module case, see what this global maps to.
12410621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
12420621caefSChris Lattner         if (const GlobalValue *GVEntry =
12430621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
12440621caefSChris Lattner           // If something else is the canonical global, ignore this one.
12450621caefSChris Lattner           if (GVEntry != &*I) {
12460621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
12470621caefSChris Lattner             continue;
12480621caefSChris Lattner           }
12490621caefSChris Lattner         }
12500621caefSChris Lattner       }
12510621caefSChris Lattner 
12525301e7c6SReid Spencer       if (!I->isDeclaration()) {
12535457ce9aSNicolas Geoffray         addGlobalMapping(I, getMemoryForGV(I));
1254996fe010SChris Lattner       } else {
1255e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
1256e8bbcfc2SBrian Gaeke         // get a pointer to it.
12570621caefSChris Lattner         if (void *SymAddr =
12585899e340SDaniel Dunbar             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1259748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
12609de0d14dSChris Lattner         else {
12612104b8d3SChris Lattner           report_fatal_error("Could not resolve external global address: "
12626c2d233eSTorok Edwin                             +I->getName());
12639de0d14dSChris Lattner         }
1264996fe010SChris Lattner       }
12650621caefSChris Lattner     }
12660621caefSChris Lattner 
12670621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
12680621caefSChris Lattner     // canonical location.
12690621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
12700621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
12710621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
12720621caefSChris Lattner         const GlobalValue *CGV =
12730621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
12740621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
12750621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
1276a67f06b9SNuno Lopes         addGlobalMapping(GV, Ptr);
12770621caefSChris Lattner       }
12780621caefSChris Lattner     }
1279996fe010SChris Lattner 
12807a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
12817a9c62baSReid Spencer     // and initialize their contents.
12828ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
12830621caefSChris Lattner          I != E; ++I) {
12845301e7c6SReid Spencer       if (!I->isDeclaration()) {
12850621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
12860621caefSChris Lattner           if (const GlobalValue *GVEntry =
12870621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
12880621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
12890621caefSChris Lattner               continue;
12900621caefSChris Lattner         }
12916bbe3eceSChris Lattner         EmitGlobalVariable(I);
12926bbe3eceSChris Lattner       }
12930621caefSChris Lattner     }
12940621caefSChris Lattner   }
12950621caefSChris Lattner }
12966bbe3eceSChris Lattner 
12976bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
12986bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
12996bbe3eceSChris Lattner // already in the map.
1300fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1301748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
1302dc631735SChris Lattner 
13032617dcceSCraig Topper   if (!GA) {
13046bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
13055457ce9aSNicolas Geoffray     GA = getMemoryForGV(GV);
13063b442379SAndrew Kaylor 
13073b442379SAndrew Kaylor     // If we failed to allocate memory for this global, return.
13082617dcceSCraig Topper     if (!GA) return;
13093b442379SAndrew Kaylor 
1310748e8579SChris Lattner     addGlobalMapping(GV, GA);
13116bbe3eceSChris Lattner   }
1312fbcc0aa1SChris Lattner 
13135457ce9aSNicolas Geoffray   // Don't initialize if it's thread local, let the client do it.
13145457ce9aSNicolas Geoffray   if (!GV->isThreadLocal())
13156bbe3eceSChris Lattner     InitializeMemory(GV->getInitializer(), GA);
13165457ce9aSNicolas Geoffray 
1317229907cdSChris Lattner   Type *ElTy = GV->getType()->getElementType();
1318cdfe20b9SMicah Villmow   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1319df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
13206bbe3eceSChris Lattner   ++NumGlobals;
1321996fe010SChris Lattner }
1322f98e981cSJeffrey Yasskin 
1323d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1324d0fc8f80SJeffrey Yasskin   : EE(EE), GlobalAddressMap(this) {
1325f98e981cSJeffrey Yasskin }
1326f98e981cSJeffrey Yasskin 
1327868e3f09SDaniel Dunbar sys::Mutex *
1328868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1329d0fc8f80SJeffrey Yasskin   return &EES->EE.lock;
1330d0fc8f80SJeffrey Yasskin }
1331868e3f09SDaniel Dunbar 
1332868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1333868e3f09SDaniel Dunbar                                                       const GlobalValue *Old) {
1334d0fc8f80SJeffrey Yasskin   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1335d0fc8f80SJeffrey Yasskin   EES->GlobalAddressReverseMap.erase(OldVal);
1336d0fc8f80SJeffrey Yasskin }
1337d0fc8f80SJeffrey Yasskin 
1338868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1339868e3f09SDaniel Dunbar                                                     const GlobalValue *,
1340868e3f09SDaniel Dunbar                                                     const GlobalValue *) {
1341a2886c21SCraig Topper   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1342f98e981cSJeffrey Yasskin                    " RAUW on a value it has a global mapping for.");
1343f98e981cSJeffrey Yasskin }
1344