blob: 6d767be492b3137e3f03e118a68918c52c26babd [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattneree937c82003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattner996fe012002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman260b0c82003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattner996fe012002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerad481312003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000029#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/Host.h"
Reid Spencer70e37272004-11-29 14:11:29 +000031#include "llvm/Target/TargetData.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000032#include <cmath>
33#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000034using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000035
Chris Lattnerc346ecd2006-12-19 22:43:32 +000036STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000038
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +000039ExecutionEngine *(*ExecutionEngine::JITCtor)(
40 Module *M,
41 std::string *ErrorStr,
42 JITMemoryManager *JMM,
43 CodeGenOpt::Level OptLevel,
44 bool GVsWithCode,
45 CodeModel::Model CMM,
46 StringRef MArch,
47 StringRef MCPU,
48 const SmallVectorImpl<std::string>& MAttrs) = 0;
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000049ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 Module *M,
51 std::string *ErrorStr,
52 JITMemoryManager *JMM,
53 CodeGenOpt::Level OptLevel,
54 bool GVsWithCode,
55 CodeModel::Model CMM,
56 StringRef MArch,
57 StringRef MCPU,
58 const SmallVectorImpl<std::string>& MAttrs) = 0;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Klecknerfc8a2d52009-07-18 00:42:18 +000060 std::string *ErrorStr) = 0;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000061
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000062ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +000063 : EEState(*this),
Duncan Sandsabc79012010-10-21 08:57:29 +000064 LazyFunctionCreator(0),
Daniel Dunbar868e3f02010-11-13 02:48:57 +000065 ExceptionTableRegister(0),
Duncan Sandsabc79012010-10-21 08:57:29 +000066 ExceptionTableDeregister(0) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000067 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000068 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000069 SymbolSearchingDisabled = false;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000070 Modules.push_back(M);
71 assert(M && "Module is null?");
Misha Brukman260b0c82003-10-16 21:18:05 +000072}
73
Brian Gaeke92f8b302003-09-04 22:57:27 +000074ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000075 clearAllGlobalMappings();
Chris Lattner0621cae2006-08-16 01:24:12 +000076 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
77 delete Modules[i];
Brian Gaeke92f8b302003-09-04 22:57:27 +000078}
79
Duncan Sandsabc79012010-10-21 08:57:29 +000080void ExecutionEngine::DeregisterAllTables() {
81 if (ExceptionTableDeregister) {
Eric Christopherf045b7a2011-03-04 23:37:39 +000082 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
83 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
84 for (; it != ite; ++it)
85 ExceptionTableDeregister(it->second);
Duncan Sandsabc79012010-10-21 08:57:29 +000086 AllExceptionTables.clear();
87 }
88}
89
Jeffrey Yasskina4044332010-03-27 04:53:56 +000090namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000091/// \brief Helper class which uses a value handler to automatically deletes the
92/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000093class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96
97public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000098 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000100 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
101 const Type *ElTy = GV->getType()->getElementType();
102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
104 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
105 TD.getPreferredAlignment(GV))
106 + GVSize);
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109 }
110
111 virtual void deleted() {
112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
114 // required.
115 this->~GVMemoryBlock();
116 ::operator delete(this);
117 }
118};
119} // anonymous namespace
120
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000121char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000122 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000123}
124
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000125bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000126 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel324fe892007-10-15 19:56:32 +0000127 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000128 Module *Found = *I;
129 if (Found == M) {
Devang Patel324fe892007-10-15 19:56:32 +0000130 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000131 clearGlobalMappingsFromModule(M);
132 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000133 }
134 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000135 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000136}
137
Chris Lattner0621cae2006-08-16 01:24:12 +0000138Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
139 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000140 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +0000141 return F;
142 }
143 return 0;
144}
145
146
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000147void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
148 const GlobalValue *ToUnmap) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000149 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000150 void *OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000151
152 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
153 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000154 if (I == GlobalAddressMap.end())
155 OldVal = 0;
156 else {
157 OldVal = I->second;
158 GlobalAddressMap.erase(I);
159 }
160
161 GlobalAddressReverseMap.erase(OldVal);
162 return OldVal;
163}
164
Chris Lattner6d8dd182006-05-08 22:00:52 +0000165void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
166 MutexGuard locked(lock);
Evan Cheng5cc53c32008-09-18 07:54:21 +0000167
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000168 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000169 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000170 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000171 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
172 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000173
174 // If we are using the reverse mapping, add it too.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000175 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000176 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000177 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000178 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
179 V = GV;
180 }
181}
182
Chris Lattner6d8dd182006-05-08 22:00:52 +0000183void ExecutionEngine::clearAllGlobalMappings() {
184 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000185
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000186 EEState.getGlobalAddressMap(locked).clear();
187 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000188}
189
Nate Begeman8f83fc42008-05-21 16:34:48 +0000190void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
191 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000192
193 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000194 EEState.RemoveMapping(locked, FI);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000195 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
196 GI != GE; ++GI)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000197 EEState.RemoveMapping(locked, GI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000198}
199
Chris Lattneree181732008-04-04 04:47:41 +0000200void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattner6d8dd182006-05-08 22:00:52 +0000201 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000202
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000203 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000204 EEState.getGlobalAddressMap(locked);
Chris Lattneree181732008-04-04 04:47:41 +0000205
Chris Lattner6d8dd182006-05-08 22:00:52 +0000206 // Deleting from the mapping?
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000207 if (Addr == 0)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000208 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000209
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000210 void *&CurVal = Map[GV];
Chris Lattneree181732008-04-04 04:47:41 +0000211 void *OldVal = CurVal;
212
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000213 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
214 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000215 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000216
217 // If we are using the reverse mapping, add it too.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000218 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000219 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000221 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
222 V = GV;
223 }
Chris Lattneree181732008-04-04 04:47:41 +0000224 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000225}
226
Chris Lattner6d8dd182006-05-08 22:00:52 +0000227void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
228 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000229
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000230 ExecutionEngineState::GlobalAddressMapTy::iterator I =
231 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000232 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000233}
234
Chris Lattner748e8572003-12-31 20:21:04 +0000235const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spencer79876f52005-07-12 15:51:55 +0000236 MutexGuard locked(lock);
237
Chris Lattner748e8572003-12-31 20:21:04 +0000238 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000239 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000240 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000241 I = EEState.getGlobalAddressMap(locked).begin(),
242 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbare4f47432010-11-13 00:55:42 +0000243 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
244 I->second, I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000245 }
246
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000247 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000248 EEState.getGlobalAddressReverseMap(locked).find(Addr);
249 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner748e8572003-12-31 20:21:04 +0000250}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000251
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000252namespace {
253class ArgvArray {
254 char *Array;
255 std::vector<char*> Values;
256public:
257 ArgvArray() : Array(NULL) {}
258 ~ArgvArray() { clear(); }
259 void clear() {
260 delete[] Array;
261 Array = NULL;
262 for (size_t I = 0, E = Values.size(); I != E; ++I) {
263 delete[] Values[I];
264 }
265 Values.clear();
266 }
267 /// Turn a vector of strings into a nice argv style array of pointers to null
268 /// terminated strings.
269 void *reset(LLVMContext &C, ExecutionEngine *EE,
270 const std::vector<std::string> &InputArgv);
271};
272} // anonymous namespace
273void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
274 const std::vector<std::string> &InputArgv) {
275 clear(); // Free the old contents.
Owen Anderson20a631f2006-05-03 01:29:57 +0000276 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000277 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner5a0d4822003-12-26 06:50:30 +0000278
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000279 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sands9ed7b162009-10-06 15:40:36 +0000280 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000281
282 for (unsigned i = 0; i != InputArgv.size(); ++i) {
283 unsigned Size = InputArgv[i].size()+1;
284 char *Dest = new char[Size];
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000285 Values.push_back(Dest);
David Greene0967d2d2010-01-05 01:27:39 +0000286 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000287
Chris Lattner5a0d4822003-12-26 06:50:30 +0000288 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
289 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000290
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000291 // Endian safe: Array[i] = (PointerTy)Dest;
292 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000293 SBytePtr);
294 }
295
296 // Null terminate it
297 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000298 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000299 SBytePtr);
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000300 return Array;
Chris Lattner5a0d4822003-12-26 06:50:30 +0000301}
302
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000303void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
304 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000305 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000306 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000307
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000308 // If this global has internal linkage, or if it has a use, then it must be
309 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
310 // this is the case, don't execute any of the global ctors, __main will do
311 // it.
312 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
313
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000314 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000315 // the init priority, which we ignore.
Nick Lewycky0f857892011-04-11 22:11:20 +0000316 if (isa<ConstantAggregateZero>(GV->getInitializer()))
317 return;
Nick Lewycky466d0c12011-04-08 07:30:21 +0000318 ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000319 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Nick Lewycky0f857892011-04-11 22:11:20 +0000320 if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
321 continue;
Nick Lewycky466d0c12011-04-08 07:30:21 +0000322 ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000323
324 Constant *FP = CS->getOperand(1);
325 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000326 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000327
328 // Strip off constant expression casts.
329 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
330 if (CE->isCast())
331 FP = CE->getOperand(0);
332
333 // Execute the ctor/dtor function!
334 if (Function *F = dyn_cast<Function>(FP))
335 runFunction(F, std::vector<GenericValue>());
336
337 // FIXME: It is marginally lame that we just do nothing here if we see an
338 // entry we don't recognize. It might not be unreasonable for the verifier
339 // to not even allow this and just assert here.
340 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000341}
342
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000343void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
344 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000345 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
346 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000347}
348
Dan Gohmancf3e3012008-08-26 01:38:29 +0000349#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000350/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
351static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
352 unsigned PtrSize = EE->getTargetData()->getPointerSize();
353 for (unsigned i = 0; i < PtrSize; ++i)
354 if (*(i + (uint8_t*)Loc))
355 return false;
356 return true;
357}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000358#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000359
Chris Lattner5a0d4822003-12-26 06:50:30 +0000360int ExecutionEngine::runFunctionAsMain(Function *Fn,
361 const std::vector<std::string> &argv,
362 const char * const * envp) {
363 std::vector<GenericValue> GVArgs;
364 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000365 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000366
367 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000368 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000369 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000370 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000371
372 // Check the argument types.
373 if (NumArgs > 3)
374 report_fatal_error("Invalid number of arguments of main() supplied");
375 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
376 report_fatal_error("Invalid type for third argument of main() supplied");
377 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
378 report_fatal_error("Invalid type for second argument of main() supplied");
379 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
380 report_fatal_error("Invalid type for first argument of main() supplied");
381 if (!FTy->getReturnType()->isIntegerTy() &&
382 !FTy->getReturnType()->isVoidTy())
383 report_fatal_error("Invalid return type of main() supplied");
384
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000385 ArgvArray CArgv;
386 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000387 if (NumArgs) {
388 GVArgs.push_back(GVArgc); // Arg #0 = argc.
389 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000390 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000391 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000392 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000393 "argv[0] was null after CreateArgv");
394 if (NumArgs > 2) {
395 std::vector<std::string> EnvVars;
396 for (unsigned i = 0; envp[i]; ++i)
397 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000398 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000399 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000400 }
401 }
402 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000403
Reid Spencer87aa65f2007-03-06 03:04:04 +0000404 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000405}
406
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000407ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencer603682a2007-03-03 18:19:18 +0000408 bool ForceInterpreter,
Evan Cheng7ff05bf2008-08-08 08:11:34 +0000409 std::string *ErrorStr,
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000410 CodeGenOpt::Level OptLevel,
411 bool GVsWithCode) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000412 return EngineBuilder(M)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000413 .setEngineKind(ForceInterpreter
414 ? EngineKind::Interpreter
415 : EngineKind::JIT)
416 .setErrorStr(ErrorStr)
417 .setOptLevel(OptLevel)
418 .setAllocateGVsWithCode(GVsWithCode)
419 .create();
420}
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000421
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000422ExecutionEngine *EngineBuilder::create() {
Nick Lewyckya53414f2008-03-08 02:49:45 +0000423 // Make sure we can resolve symbols in the program as well. The zero arg
424 // to the function tells DynamicLibrary to load the program, not a library.
425 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
426 return 0;
427
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000428 // If the user specified a memory manager but didn't specify which engine to
429 // create, we assume they only want the JIT, and we fail if they only want
430 // the interpreter.
431 if (JMM) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000432 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000433 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000434 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000435 if (ErrorStr)
436 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000437 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000438 }
439 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000440
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000441 // Unless the interpreter was explicitly selected or the JIT is not linked,
442 // try making a JIT.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000443 if (WhichEngine & EngineKind::JIT) {
Daniel Dunbar70ff8b02010-11-17 16:06:37 +0000444 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
445 ExecutionEngine *EE =
446 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
447 AllocateGVsWithCode, CMModel,
448 MArch, MCPU, MAttrs);
449 if (EE) return EE;
450 } else if (ExecutionEngine::JITCtor) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000451 ExecutionEngine *EE =
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000452 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000453 AllocateGVsWithCode, CMModel,
454 MArch, MCPU, MAttrs);
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000455 if (EE) return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000456 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000457 }
458
459 // If we can't make a JIT and we didn't request one specifically, try making
460 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000461 if (WhichEngine & EngineKind::Interpreter) {
462 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000463 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000464 if (ErrorStr)
465 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000466 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000467 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000468
469 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
470 if (ErrorStr)
471 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000472 }
473
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000474 return 0;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000475}
476
Chris Lattner996fe012002-12-24 00:01:05 +0000477void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000478 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000479 return getPointerToFunction(F);
480
Reid Spencer79876f52005-07-12 15:51:55 +0000481 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000482 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
483 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000484
485 // Global variable might have been added since interpreter started.
486 if (GlobalVariable *GVar =
487 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
488 EmitGlobalVariable(GVar);
489 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000490 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000491
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000492 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000493}
494
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000495/// \brief Converts a Constant* into a GenericValue, including handling of
496/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000497GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000498 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000499 if (isa<UndefValue>(C)) {
500 GenericValue Result;
501 switch (C->getType()->getTypeID()) {
502 case Type::IntegerTyID:
503 case Type::X86_FP80TyID:
504 case Type::FP128TyID:
505 case Type::PPC_FP128TyID:
506 // Although the value is undefined, we still have to construct an APInt
507 // with the correct bit width.
508 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
509 break;
510 default:
511 break;
512 }
513 return Result;
514 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000515
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000516 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000517 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000518 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000519 switch (CE->getOpcode()) {
520 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000521 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000522 GenericValue Result = getConstantValue(Op0);
Chris Lattnerc44bd782007-02-10 20:35:22 +0000523 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattner9de0d142003-04-23 19:01:49 +0000524 uint64_t Offset =
Reid Spencer4fd528f2007-03-06 22:23:15 +0000525 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukman835702a2005-04-21 22:36:52 +0000526
Reid Spencer87aa65f2007-03-06 03:04:04 +0000527 char* tmp = (char*) Result.PointerVal;
528 Result = PTOGV(tmp + Offset);
Chris Lattner9de0d142003-04-23 19:01:49 +0000529 return Result;
530 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000531 case Instruction::Trunc: {
532 GenericValue GV = getConstantValue(Op0);
533 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
534 GV.IntVal = GV.IntVal.trunc(BitWidth);
535 return GV;
536 }
537 case Instruction::ZExt: {
538 GenericValue GV = getConstantValue(Op0);
539 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
540 GV.IntVal = GV.IntVal.zext(BitWidth);
541 return GV;
542 }
543 case Instruction::SExt: {
544 GenericValue GV = getConstantValue(Op0);
545 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
546 GV.IntVal = GV.IntVal.sext(BitWidth);
547 return GV;
548 }
549 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000550 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000551 GenericValue GV = getConstantValue(Op0);
552 GV.FloatVal = float(GV.DoubleVal);
553 return GV;
554 }
555 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000556 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000557 GenericValue GV = getConstantValue(Op0);
558 GV.DoubleVal = double(GV.FloatVal);
559 return GV;
560 }
561 case Instruction::UIToFP: {
562 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000563 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000564 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000565 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000566 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000567 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000568 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000569 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000570 false,
571 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000572 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000573 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000574 return GV;
575 }
576 case Instruction::SIToFP: {
577 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000578 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000579 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000580 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000581 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000582 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000583 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000584 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000585 true,
586 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000587 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000588 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000589 return GV;
590 }
591 case Instruction::FPToUI: // double->APInt conversion handles sign
592 case Instruction::FPToSI: {
593 GenericValue GV = getConstantValue(Op0);
594 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000595 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000596 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000597 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000598 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000599 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000600 APFloat apf = APFloat(GV.IntVal);
601 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000602 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000603 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000604 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000605 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000606 GV.IntVal = v; // endian?
607 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000608 return GV;
609 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000610 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000611 GenericValue GV = getConstantValue(Op0);
612 uint32_t PtrWidth = TD->getPointerSizeInBits();
613 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
614 return GV;
615 }
616 case Instruction::IntToPtr: {
617 GenericValue GV = getConstantValue(Op0);
618 uint32_t PtrWidth = TD->getPointerSizeInBits();
619 if (PtrWidth != GV.IntVal.getBitWidth())
620 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
621 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
622 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000623 return GV;
624 }
625 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000626 GenericValue GV = getConstantValue(Op0);
627 const Type* DestTy = CE->getType();
628 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000629 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000630 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000631 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000632 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000633 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000634 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000635 GV.DoubleVal = GV.IntVal.bitsToDouble();
636 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000637 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000638 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000639 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000640 break;
641 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000642 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000643 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000644 break;
645 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000646 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000647 break; // getConstantValue(Op0) above already converted it
648 }
649 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000650 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000651 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000652 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000653 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000654 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000655 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000656 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000657 case Instruction::UDiv:
658 case Instruction::SDiv:
659 case Instruction::URem:
660 case Instruction::SRem:
661 case Instruction::And:
662 case Instruction::Or:
663 case Instruction::Xor: {
664 GenericValue LHS = getConstantValue(Op0);
665 GenericValue RHS = getConstantValue(CE->getOperand(1));
666 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000667 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000668 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000669 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000670 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000671 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000672 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
673 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
674 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
675 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
676 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
677 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
678 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
679 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
680 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
681 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
682 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000683 break;
684 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000685 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000686 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000687 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000688 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000689 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000690 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000691 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000692 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000693 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000694 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000695 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000696 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000697 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000698 break;
699 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000700 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000701 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000702 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000703 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000704 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000705 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000706 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000707 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000708 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000709 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000710 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000711 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000712 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000713 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000714 case Type::X86_FP80TyID:
715 case Type::PPC_FP128TyID:
716 case Type::FP128TyID: {
717 APFloat apfLHS = APFloat(LHS.IntVal);
718 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000719 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000720 case Instruction::FAdd:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000721 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000722 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000723 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000724 case Instruction::FSub:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000725 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000726 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000727 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000728 case Instruction::FMul:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000729 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000730 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000731 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000732 case Instruction::FDiv:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000733 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000734 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000735 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000736 case Instruction::FRem:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000737 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000738 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000739 break;
740 }
741 }
742 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000743 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000744 return GV;
745 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000746 default:
747 break;
748 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000749
750 SmallString<256> Msg;
751 raw_svector_ostream OS(Msg);
752 OS << "ConstantExpr not handled: " << *CE;
753 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000754 }
Misha Brukman835702a2005-04-21 22:36:52 +0000755
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000756 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000757 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000758 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000759 case Type::FloatTyID:
760 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000761 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000762 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000763 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000764 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000765 case Type::X86_FP80TyID:
766 case Type::FP128TyID:
767 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000768 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000769 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000770 case Type::IntegerTyID:
771 Result.IntVal = cast<ConstantInt>(C)->getValue();
772 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000773 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000774 if (isa<ConstantPointerNull>(C))
Chris Lattner996fe012002-12-24 00:01:05 +0000775 Result.PointerVal = 0;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000776 else if (const Function *F = dyn_cast<Function>(C))
777 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000778 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000779 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000780 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
781 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
782 BA->getBasicBlock())));
Reid Spencer6a0fd732004-07-18 00:41:27 +0000783 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000784 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000785 break;
786 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000787 SmallString<256> Msg;
788 raw_svector_ostream OS(Msg);
789 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
790 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000791 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000792
Chris Lattner996fe012002-12-24 00:01:05 +0000793 return Result;
794}
795
Duncan Sands1202d1b2007-12-14 19:38:31 +0000796/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
797/// with the integer held in IntVal.
798static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
799 unsigned StoreBytes) {
800 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
801 uint8_t *Src = (uint8_t *)IntVal.getRawData();
802
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000803 if (sys::isLittleEndianHost()) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000804 // Little-endian host - the source is ordered from LSB to MSB. Order the
805 // destination from LSB to MSB: Do a straight copy.
806 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000807 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000808 // Big-endian host - the source is an array of 64 bit words ordered from
809 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
810 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
811 while (StoreBytes > sizeof(uint64_t)) {
812 StoreBytes -= sizeof(uint64_t);
813 // May not be aligned so use memcpy.
814 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
815 Src += sizeof(uint64_t);
816 }
817
818 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
819 }
820}
821
Evan Cheng09053e62008-11-04 06:10:31 +0000822void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
823 GenericValue *Ptr, const Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000824 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
825
Reid Spencer87aa65f2007-03-06 03:04:04 +0000826 switch (Ty->getTypeID()) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000827 case Type::IntegerTyID:
828 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000829 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000830 case Type::FloatTyID:
831 *((float*)Ptr) = Val.FloatVal;
832 break;
833 case Type::DoubleTyID:
834 *((double*)Ptr) = Val.DoubleVal;
835 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000836 case Type::X86_FP80TyID:
837 memcpy(Ptr, Val.IntVal.getRawData(), 10);
838 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000839 case Type::PointerTyID:
840 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
841 if (StoreBytes != sizeof(PointerTy))
842 memset(Ptr, 0, StoreBytes);
843
Reid Spencer87aa65f2007-03-06 03:04:04 +0000844 *((PointerTy*)Ptr) = Val.PointerVal;
845 break;
846 default:
David Greene0967d2d2010-01-05 01:27:39 +0000847 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattner996fe012002-12-24 00:01:05 +0000848 }
Duncan Sands1202d1b2007-12-14 19:38:31 +0000849
Chris Lattneraa121222009-01-22 19:53:00 +0000850 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000851 // Host and target are different endian - reverse the stored bytes.
852 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
853}
854
855/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
856/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
857static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
858 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
859 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
860
Chris Lattneraa121222009-01-22 19:53:00 +0000861 if (sys::isLittleEndianHost())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000862 // Little-endian host - the destination must be ordered from LSB to MSB.
863 // The source is ordered from LSB to MSB: Do a straight copy.
864 memcpy(Dst, Src, LoadBytes);
865 else {
866 // Big-endian - the destination is an array of 64 bit words ordered from
867 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
868 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
869 // a word.
870 while (LoadBytes > sizeof(uint64_t)) {
871 LoadBytes -= sizeof(uint64_t);
872 // May not be aligned so use memcpy.
873 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
874 Dst += sizeof(uint64_t);
875 }
876
877 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
878 }
Chris Lattner996fe012002-12-24 00:01:05 +0000879}
880
Misha Brukman857c21b2003-10-10 17:45:12 +0000881/// FIXME: document
882///
Duncan Sands1202d1b2007-12-14 19:38:31 +0000883void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +0000884 GenericValue *Ptr,
885 const Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000886 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +0000887
Duncan Sands1202d1b2007-12-14 19:38:31 +0000888 switch (Ty->getTypeID()) {
889 case Type::IntegerTyID:
890 // An APInt with all words initially zero.
891 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
892 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
893 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000894 case Type::FloatTyID:
895 Result.FloatVal = *((float*)Ptr);
896 break;
897 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +0000898 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000899 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000900 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +0000901 Result.PointerVal = *((PointerTy*)Ptr);
902 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000903 case Type::X86_FP80TyID: {
904 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +0000905 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000906 uint64_t y[2];
907 memcpy(y, Ptr, 10);
Duncan Sandsff306282007-11-28 10:36:19 +0000908 Result.IntVal = APInt(80, 2, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000909 break;
910 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000911 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000912 SmallString<256> Msg;
913 raw_svector_ostream OS(Msg);
914 OS << "Cannot load value of type " << *Ty << "!";
915 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +0000916 }
Chris Lattner7f389e82003-05-08 16:52:16 +0000917}
918
Chris Lattner996fe012002-12-24 00:01:05 +0000919void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +0000920 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +0000921 DEBUG(Init->dump());
Chris Lattner61753bf2004-10-16 18:19:26 +0000922 if (isa<UndefValue>(Init)) {
923 return;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000924 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +0000925 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000926 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +0000927 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
928 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
929 return;
Chris Lattner1dd86b12008-02-15 00:57:28 +0000930 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000931 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +0000932 return;
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000933 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
934 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000935 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000936 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
937 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
938 return;
939 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
940 const StructLayout *SL =
941 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
942 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
943 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
944 return;
Chris Lattner61753bf2004-10-16 18:19:26 +0000945 } else if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +0000946 GenericValue Val = getConstantValue(Init);
947 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
948 return;
949 }
950
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000951 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +0000952 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +0000953}
954
Chris Lattner996fe012002-12-24 00:01:05 +0000955/// EmitGlobals - Emit all of the global variables to memory, storing their
956/// addresses into GlobalAddress. This must make sure to copy the contents of
957/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +0000958void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +0000959 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +0000960 // to hold them. If there is more than one module, do a prepass over globals
961 // to figure out how the different modules should link together.
Chris Lattner0621cae2006-08-16 01:24:12 +0000962 std::map<std::pair<std::string, const Type*>,
963 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +0000964
Chris Lattner0621cae2006-08-16 01:24:12 +0000965 if (Modules.size() != 1) {
966 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000967 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +0000968 for (Module::const_global_iterator I = M.global_begin(),
969 E = M.global_end(); I != E; ++I) {
970 const GlobalValue *GV = I;
Rafael Espindola6de96a12009-01-15 20:18:42 +0000971 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattner0621cae2006-08-16 01:24:12 +0000972 GV->hasAppendingLinkage() || !GV->hasName())
973 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000974
975 const GlobalValue *&GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +0000976 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
977
978 // If this is the first time we've seen this global, it is the canonical
979 // version.
980 if (!GVEntry) {
981 GVEntry = GV;
982 continue;
983 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000984
Chris Lattner0621cae2006-08-16 01:24:12 +0000985 // If the existing global is strong, never replace it.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000986 if (GVEntry->hasExternalLinkage() ||
987 GVEntry->hasDLLImportLinkage() ||
988 GVEntry->hasDLLExportLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000989 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000990
Chris Lattner0621cae2006-08-16 01:24:12 +0000991 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +0000992 // symbol. FIXME is this right for common?
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000993 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000994 GVEntry = GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000995 }
Chris Lattner996fe012002-12-24 00:01:05 +0000996 }
Chris Lattner0621cae2006-08-16 01:24:12 +0000997 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000998
Chris Lattner0621cae2006-08-16 01:24:12 +0000999 std::vector<const GlobalValue*> NonCanonicalGlobals;
1000 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001001 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +00001002 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1003 I != E; ++I) {
1004 // In the multi-module case, see what this global maps to.
1005 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001006 if (const GlobalValue *GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +00001007 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1008 // If something else is the canonical global, ignore this one.
1009 if (GVEntry != &*I) {
1010 NonCanonicalGlobals.push_back(I);
1011 continue;
1012 }
1013 }
1014 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001015
Reid Spencer5301e7c2007-01-30 20:08:39 +00001016 if (!I->isDeclaration()) {
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001017 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattner0621cae2006-08-16 01:24:12 +00001018 } else {
1019 // External variable reference. Try to use the dynamic loader to
1020 // get a pointer to it.
1021 if (void *SymAddr =
Daniel Dunbar5899e342009-07-21 08:54:24 +00001022 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattner0621cae2006-08-16 01:24:12 +00001023 addGlobalMapping(I, SymAddr);
1024 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001025 report_fatal_error("Could not resolve external global address: "
Torok Edwin6c2d2332009-07-07 17:32:34 +00001026 +I->getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001027 }
1028 }
1029 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001030
Chris Lattner0621cae2006-08-16 01:24:12 +00001031 // If there are multiple modules, map the non-canonical globals to their
1032 // canonical location.
1033 if (!NonCanonicalGlobals.empty()) {
1034 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1035 const GlobalValue *GV = NonCanonicalGlobals[i];
1036 const GlobalValue *CGV =
1037 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1038 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1039 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001040 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001041 }
1042 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001043
1044 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001045 // and initialize their contents.
Chris Lattner0621cae2006-08-16 01:24:12 +00001046 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1047 I != E; ++I) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001048 if (!I->isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001049 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001050 if (const GlobalValue *GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +00001051 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1052 if (GVEntry != &*I) // Not the canonical variable.
1053 continue;
1054 }
1055 EmitGlobalVariable(I);
1056 }
1057 }
1058 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001059}
1060
1061// EmitGlobalVariable - This method emits the specified global variable to the
1062// address specified in GlobalAddresses, or allocates new memory if it's not
1063// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001064void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001065 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001066
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001067 if (GA == 0) {
1068 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001069 GA = getMemoryForGV(GV);
Chris Lattner748e8572003-12-31 20:21:04 +00001070 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001071 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001072
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001073 // Don't initialize if it's thread local, let the client do it.
1074 if (!GV->isThreadLocal())
1075 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001076
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001077 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001078 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001079 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001080 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001081}
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001082
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001083ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1084 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001085}
1086
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001087sys::Mutex *
1088ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001089 return &EES->EE.lock;
1090}
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001091
1092void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1093 const GlobalValue *Old) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001094 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1095 EES->GlobalAddressReverseMap.erase(OldVal);
1096}
1097
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001098void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1099 const GlobalValue *,
1100 const GlobalValue *) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001101 assert(false && "The ExecutionEngine doesn't know how to handle a"
1102 " RAUW on a value it has a global mapping for.");
1103}