blob: b9356dcd0a74835223379947cfb45dc7d8b7184d [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"
Dylan Noblesmith7f262462011-12-12 04:20:36 +000031#include "llvm/Support/TargetRegistry.h"
Reid Spencer70e37272004-11-29 14:11:29 +000032#include "llvm/Target/TargetData.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000033#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000034#include <cmath>
35#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000036using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000037
Chris Lattnerc346ecd2006-12-19 22:43:32 +000038STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
39STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000040
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +000041ExecutionEngine *(*ExecutionEngine::JITCtor)(
42 Module *M,
43 std::string *ErrorStr,
44 JITMemoryManager *JMM,
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +000045 bool GVsWithCode,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000046 TargetMachine *TM) = 0;
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000047ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
48 Module *M,
49 std::string *ErrorStr,
50 JITMemoryManager *JMM,
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000051 bool GVsWithCode,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000052 TargetMachine *TM) = 0;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000053ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Klecknerfc8a2d52009-07-18 00:42:18 +000054 std::string *ErrorStr) = 0;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000055
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000056ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +000057 : EEState(*this),
Duncan Sandsabc79012010-10-21 08:57:29 +000058 LazyFunctionCreator(0),
Daniel Dunbar868e3f02010-11-13 02:48:57 +000059 ExceptionTableRegister(0),
Duncan Sandsabc79012010-10-21 08:57:29 +000060 ExceptionTableDeregister(0) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000061 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000062 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000063 SymbolSearchingDisabled = false;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000064 Modules.push_back(M);
65 assert(M && "Module is null?");
Misha Brukman260b0c82003-10-16 21:18:05 +000066}
67
Brian Gaeke92f8b302003-09-04 22:57:27 +000068ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000069 clearAllGlobalMappings();
Chris Lattner0621cae2006-08-16 01:24:12 +000070 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
71 delete Modules[i];
Brian Gaeke92f8b302003-09-04 22:57:27 +000072}
73
Duncan Sandsabc79012010-10-21 08:57:29 +000074void ExecutionEngine::DeregisterAllTables() {
75 if (ExceptionTableDeregister) {
Eric Christopherf045b7a2011-03-04 23:37:39 +000076 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
77 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
78 for (; it != ite; ++it)
79 ExceptionTableDeregister(it->second);
Duncan Sandsabc79012010-10-21 08:57:29 +000080 AllExceptionTables.clear();
81 }
82}
83
Jeffrey Yasskina4044332010-03-27 04:53:56 +000084namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000085/// \brief Helper class which uses a value handler to automatically deletes the
86/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000087class GVMemoryBlock : public CallbackVH {
88 GVMemoryBlock(const GlobalVariable *GV)
89 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
90
91public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000092 /// \brief Returns the address the GlobalVariable should be written into. The
93 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000094 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000095 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +000096 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
97 void *RawMemory = ::operator new(
98 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
99 TD.getPreferredAlignment(GV))
100 + GVSize);
101 new(RawMemory) GVMemoryBlock(GV);
102 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
103 }
104
105 virtual void deleted() {
106 // We allocated with operator new and with some extra memory hanging off the
107 // end, so don't just delete this. I'm not sure if this is actually
108 // required.
109 this->~GVMemoryBlock();
110 ::operator delete(this);
111 }
112};
113} // anonymous namespace
114
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000115char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000116 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000117}
118
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000119bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000120 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel324fe892007-10-15 19:56:32 +0000121 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000122 Module *Found = *I;
123 if (Found == M) {
Devang Patel324fe892007-10-15 19:56:32 +0000124 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000125 clearGlobalMappingsFromModule(M);
126 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000127 }
128 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000129 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000130}
131
Chris Lattner0621cae2006-08-16 01:24:12 +0000132Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
133 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000134 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +0000135 return F;
136 }
137 return 0;
138}
139
140
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000141void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
142 const GlobalValue *ToUnmap) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000143 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000144 void *OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000145
146 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
147 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000148 if (I == GlobalAddressMap.end())
149 OldVal = 0;
150 else {
151 OldVal = I->second;
152 GlobalAddressMap.erase(I);
153 }
154
155 GlobalAddressReverseMap.erase(OldVal);
156 return OldVal;
157}
158
Chris Lattner6d8dd182006-05-08 22:00:52 +0000159void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
160 MutexGuard locked(lock);
Evan Cheng5cc53c32008-09-18 07:54:21 +0000161
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000162 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000163 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000164 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000165 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
166 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000167
168 // If we are using the reverse mapping, add it too.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000169 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000170 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000171 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000172 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
173 V = GV;
174 }
175}
176
Chris Lattner6d8dd182006-05-08 22:00:52 +0000177void ExecutionEngine::clearAllGlobalMappings() {
178 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000179
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000180 EEState.getGlobalAddressMap(locked).clear();
181 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000182}
183
Nate Begeman8f83fc42008-05-21 16:34:48 +0000184void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
185 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000186
187 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000188 EEState.RemoveMapping(locked, FI);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000189 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
190 GI != GE; ++GI)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000191 EEState.RemoveMapping(locked, GI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000192}
193
Chris Lattneree181732008-04-04 04:47:41 +0000194void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattner6d8dd182006-05-08 22:00:52 +0000195 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000196
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000197 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000198 EEState.getGlobalAddressMap(locked);
Chris Lattneree181732008-04-04 04:47:41 +0000199
Chris Lattner6d8dd182006-05-08 22:00:52 +0000200 // Deleting from the mapping?
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000201 if (Addr == 0)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000202 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000203
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000204 void *&CurVal = Map[GV];
Chris Lattneree181732008-04-04 04:47:41 +0000205 void *OldVal = CurVal;
206
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000207 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
208 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000209 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000210
211 // If we are using the reverse mapping, add it too.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000212 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000213 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000214 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000215 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
216 V = GV;
217 }
Chris Lattneree181732008-04-04 04:47:41 +0000218 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000219}
220
Chris Lattner6d8dd182006-05-08 22:00:52 +0000221void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
222 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000223
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000224 ExecutionEngineState::GlobalAddressMapTy::iterator I =
225 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000226 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000227}
228
Chris Lattner748e8572003-12-31 20:21:04 +0000229const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spencer79876f52005-07-12 15:51:55 +0000230 MutexGuard locked(lock);
231
Chris Lattner748e8572003-12-31 20:21:04 +0000232 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000233 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000234 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000235 I = EEState.getGlobalAddressMap(locked).begin(),
236 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbare4f47432010-11-13 00:55:42 +0000237 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
238 I->second, I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000239 }
240
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000241 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000242 EEState.getGlobalAddressReverseMap(locked).find(Addr);
243 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner748e8572003-12-31 20:21:04 +0000244}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000245
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000246namespace {
247class ArgvArray {
248 char *Array;
249 std::vector<char*> Values;
250public:
251 ArgvArray() : Array(NULL) {}
252 ~ArgvArray() { clear(); }
253 void clear() {
254 delete[] Array;
255 Array = NULL;
256 for (size_t I = 0, E = Values.size(); I != E; ++I) {
257 delete[] Values[I];
258 }
259 Values.clear();
260 }
261 /// Turn a vector of strings into a nice argv style array of pointers to null
262 /// terminated strings.
263 void *reset(LLVMContext &C, ExecutionEngine *EE,
264 const std::vector<std::string> &InputArgv);
265};
266} // anonymous namespace
267void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
268 const std::vector<std::string> &InputArgv) {
269 clear(); // Free the old contents.
Owen Anderson20a631f2006-05-03 01:29:57 +0000270 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000271 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner5a0d4822003-12-26 06:50:30 +0000272
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000273 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000274 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000275
276 for (unsigned i = 0; i != InputArgv.size(); ++i) {
277 unsigned Size = InputArgv[i].size()+1;
278 char *Dest = new char[Size];
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000279 Values.push_back(Dest);
David Greene0967d2d2010-01-05 01:27:39 +0000280 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000281
Chris Lattner5a0d4822003-12-26 06:50:30 +0000282 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
283 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000284
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000285 // Endian safe: Array[i] = (PointerTy)Dest;
286 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000287 SBytePtr);
288 }
289
290 // Null terminate it
291 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000292 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000293 SBytePtr);
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000294 return Array;
Chris Lattner5a0d4822003-12-26 06:50:30 +0000295}
296
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000297void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
298 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000299 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000300 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000301
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000302 // If this global has internal linkage, or if it has a use, then it must be
303 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
304 // this is the case, don't execute any of the global ctors, __main will do
305 // it.
306 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
307
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000308 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000309 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000310 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
311 if (InitList == 0)
Nick Lewycky0f857892011-04-11 22:11:20 +0000312 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000313 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000314 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
315 if (CS == 0) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000316
317 Constant *FP = CS->getOperand(1);
318 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000319 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000320
321 // Strip off constant expression casts.
322 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
323 if (CE->isCast())
324 FP = CE->getOperand(0);
325
326 // Execute the ctor/dtor function!
327 if (Function *F = dyn_cast<Function>(FP))
328 runFunction(F, std::vector<GenericValue>());
329
330 // FIXME: It is marginally lame that we just do nothing here if we see an
331 // entry we don't recognize. It might not be unreasonable for the verifier
332 // to not even allow this and just assert here.
333 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000334}
335
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000336void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
337 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000338 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
339 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000340}
341
Dan Gohmancf3e3012008-08-26 01:38:29 +0000342#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000343/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
344static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
345 unsigned PtrSize = EE->getTargetData()->getPointerSize();
346 for (unsigned i = 0; i < PtrSize; ++i)
347 if (*(i + (uint8_t*)Loc))
348 return false;
349 return true;
350}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000351#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000352
Chris Lattner5a0d4822003-12-26 06:50:30 +0000353int ExecutionEngine::runFunctionAsMain(Function *Fn,
354 const std::vector<std::string> &argv,
355 const char * const * envp) {
356 std::vector<GenericValue> GVArgs;
357 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000358 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000359
360 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000361 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000362 FunctionType *FTy = Fn->getFunctionType();
363 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000364
365 // Check the argument types.
366 if (NumArgs > 3)
367 report_fatal_error("Invalid number of arguments of main() supplied");
368 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
369 report_fatal_error("Invalid type for third argument of main() supplied");
370 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
371 report_fatal_error("Invalid type for second argument of main() supplied");
372 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
373 report_fatal_error("Invalid type for first argument of main() supplied");
374 if (!FTy->getReturnType()->isIntegerTy() &&
375 !FTy->getReturnType()->isVoidTy())
376 report_fatal_error("Invalid return type of main() supplied");
377
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000378 ArgvArray CArgv;
379 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000380 if (NumArgs) {
381 GVArgs.push_back(GVArgc); // Arg #0 = argc.
382 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000383 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000384 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000385 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000386 "argv[0] was null after CreateArgv");
387 if (NumArgs > 2) {
388 std::vector<std::string> EnvVars;
389 for (unsigned i = 0; envp[i]; ++i)
390 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000391 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000392 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000393 }
394 }
395 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000396
Reid Spencer87aa65f2007-03-06 03:04:04 +0000397 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000398}
399
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000400ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencer603682a2007-03-03 18:19:18 +0000401 bool ForceInterpreter,
Evan Cheng7ff05bf2008-08-08 08:11:34 +0000402 std::string *ErrorStr,
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000403 CodeGenOpt::Level OptLevel,
404 bool GVsWithCode) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000405 return EngineBuilder(M)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000406 .setEngineKind(ForceInterpreter
407 ? EngineKind::Interpreter
408 : EngineKind::JIT)
409 .setErrorStr(ErrorStr)
410 .setOptLevel(OptLevel)
411 .setAllocateGVsWithCode(GVsWithCode)
412 .create();
413}
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000414
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000415/// createJIT - This is the factory method for creating a JIT for the current
416/// machine, it does not fall back to the interpreter. This takes ownership
417/// of the module.
418ExecutionEngine *ExecutionEngine::createJIT(Module *M,
419 std::string *ErrorStr,
420 JITMemoryManager *JMM,
Dylan Noblesmith19a58df2011-12-01 21:49:21 +0000421 CodeGenOpt::Level OL,
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000422 bool GVsWithCode,
Evan Cheng2129f592011-07-19 06:37:02 +0000423 Reloc::Model RM,
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000424 CodeModel::Model CMM) {
425 if (ExecutionEngine::JITCtor == 0) {
426 if (ErrorStr)
427 *ErrorStr = "JIT has not been linked in.";
428 return 0;
429 }
430
431 // Use the defaults for extra parameters. Users can use EngineBuilder to
432 // set them.
433 StringRef MArch = "";
434 StringRef MCPU = "";
435 SmallVector<std::string, 1> MAttrs;
436
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000437 Triple TT(M->getTargetTriple());
Peter Collingbournedff24782011-12-07 23:58:57 +0000438 // TODO: permit custom TargetOptions here
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000439 TargetMachine *TM =
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000440 EngineBuilder::selectTarget(TT, MArch, MCPU, MAttrs, TargetOptions(), RM,
Peter Collingbournedff24782011-12-07 23:58:57 +0000441 CMM, OL, ErrorStr);
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000442 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000443
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000444 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmith0bd34fb2011-05-13 22:02:53 +0000445}
446
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000447ExecutionEngine *EngineBuilder::create() {
Nick Lewyckya53414f2008-03-08 02:49:45 +0000448 // Make sure we can resolve symbols in the program as well. The zero arg
449 // to the function tells DynamicLibrary to load the program, not a library.
450 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
451 return 0;
452
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000453 // If the user specified a memory manager but didn't specify which engine to
454 // create, we assume they only want the JIT, and we fail if they only want
455 // the interpreter.
456 if (JMM) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000457 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000458 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000459 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000460 if (ErrorStr)
461 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000462 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000463 }
464 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000465
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000466 // Unless the interpreter was explicitly selected or the JIT is not linked,
467 // try making a JIT.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000468 if (WhichEngine & EngineKind::JIT) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000469 Triple TT(M->getTargetTriple());
470 if (TargetMachine *TM = EngineBuilder::selectTarget(TT, MArch, MCPU, MAttrs,
Peter Collingbournedff24782011-12-07 23:58:57 +0000471 Options,
Evan Chengefd9b422011-07-20 07:51:56 +0000472 RelocModel, CMModel,
Dylan Noblesmith19a58df2011-12-01 21:49:21 +0000473 OptLevel, ErrorStr)) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000474 if (!TM->getTarget().hasJIT()) {
475 errs() << "WARNING: This target JIT is not designed for the host"
476 << " you are running. If bad things happen, please choose"
477 << " a different -march switch.\n";
478 }
479
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +0000480 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
481 ExecutionEngine *EE =
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000482 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +0000483 AllocateGVsWithCode, TM);
484 if (EE) return EE;
485 } else if (ExecutionEngine::JITCtor) {
486 ExecutionEngine *EE =
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000487 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +0000488 AllocateGVsWithCode, TM);
489 if (EE) return EE;
490 }
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000491 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000492 }
493
494 // If we can't make a JIT and we didn't request one specifically, try making
495 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000496 if (WhichEngine & EngineKind::Interpreter) {
497 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000498 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000499 if (ErrorStr)
500 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000501 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000502 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000503
504 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
505 if (ErrorStr)
506 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000507 }
508
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000509 return 0;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000510}
511
Chris Lattner996fe012002-12-24 00:01:05 +0000512void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000513 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000514 return getPointerToFunction(F);
515
Reid Spencer79876f52005-07-12 15:51:55 +0000516 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000517 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
518 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000519
520 // Global variable might have been added since interpreter started.
521 if (GlobalVariable *GVar =
522 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
523 EmitGlobalVariable(GVar);
524 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000525 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000526
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000527 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000528}
529
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000530/// \brief Converts a Constant* into a GenericValue, including handling of
531/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000532GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000533 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000534 if (isa<UndefValue>(C)) {
535 GenericValue Result;
536 switch (C->getType()->getTypeID()) {
537 case Type::IntegerTyID:
538 case Type::X86_FP80TyID:
539 case Type::FP128TyID:
540 case Type::PPC_FP128TyID:
541 // Although the value is undefined, we still have to construct an APInt
542 // with the correct bit width.
543 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
544 break;
545 default:
546 break;
547 }
548 return Result;
549 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000550
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000551 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000552 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000553 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000554 switch (CE->getOpcode()) {
555 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000556 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000557 GenericValue Result = getConstantValue(Op0);
Chris Lattnerc44bd782007-02-10 20:35:22 +0000558 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Jay Foadbf904772011-07-19 14:01:37 +0000559 uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
Misha Brukman835702a2005-04-21 22:36:52 +0000560
Reid Spencer87aa65f2007-03-06 03:04:04 +0000561 char* tmp = (char*) Result.PointerVal;
562 Result = PTOGV(tmp + Offset);
Chris Lattner9de0d142003-04-23 19:01:49 +0000563 return Result;
564 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000565 case Instruction::Trunc: {
566 GenericValue GV = getConstantValue(Op0);
567 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
568 GV.IntVal = GV.IntVal.trunc(BitWidth);
569 return GV;
570 }
571 case Instruction::ZExt: {
572 GenericValue GV = getConstantValue(Op0);
573 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
574 GV.IntVal = GV.IntVal.zext(BitWidth);
575 return GV;
576 }
577 case Instruction::SExt: {
578 GenericValue GV = getConstantValue(Op0);
579 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
580 GV.IntVal = GV.IntVal.sext(BitWidth);
581 return GV;
582 }
583 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000584 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000585 GenericValue GV = getConstantValue(Op0);
586 GV.FloatVal = float(GV.DoubleVal);
587 return GV;
588 }
589 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000590 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000591 GenericValue GV = getConstantValue(Op0);
592 GV.DoubleVal = double(GV.FloatVal);
593 return GV;
594 }
595 case Instruction::UIToFP: {
596 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000597 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000598 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000599 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000600 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000601 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000602 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000603 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000604 false,
605 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000606 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000607 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000608 return GV;
609 }
610 case Instruction::SIToFP: {
611 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000612 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000613 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000614 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000615 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000616 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000617 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000618 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000619 true,
620 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000621 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000622 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000623 return GV;
624 }
625 case Instruction::FPToUI: // double->APInt conversion handles sign
626 case Instruction::FPToSI: {
627 GenericValue GV = getConstantValue(Op0);
628 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000629 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000630 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000631 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000632 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000633 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000634 APFloat apf = APFloat(GV.IntVal);
635 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000636 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000637 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000638 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000639 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000640 GV.IntVal = v; // endian?
641 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000642 return GV;
643 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000644 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000645 GenericValue GV = getConstantValue(Op0);
646 uint32_t PtrWidth = TD->getPointerSizeInBits();
647 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
648 return GV;
649 }
650 case Instruction::IntToPtr: {
651 GenericValue GV = getConstantValue(Op0);
652 uint32_t PtrWidth = TD->getPointerSizeInBits();
653 if (PtrWidth != GV.IntVal.getBitWidth())
654 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
655 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
656 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000657 return GV;
658 }
659 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000660 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000661 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000662 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000663 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000664 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000665 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000666 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000667 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000668 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000669 GV.DoubleVal = GV.IntVal.bitsToDouble();
670 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000671 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000672 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000673 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000674 break;
675 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000676 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000677 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000678 break;
679 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000680 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000681 break; // getConstantValue(Op0) above already converted it
682 }
683 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000684 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000685 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000686 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000687 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000688 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000689 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000690 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000691 case Instruction::UDiv:
692 case Instruction::SDiv:
693 case Instruction::URem:
694 case Instruction::SRem:
695 case Instruction::And:
696 case Instruction::Or:
697 case Instruction::Xor: {
698 GenericValue LHS = getConstantValue(Op0);
699 GenericValue RHS = getConstantValue(CE->getOperand(1));
700 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000701 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000702 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000703 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000704 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000705 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000706 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
707 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
708 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
709 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
710 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
711 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
712 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
713 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
714 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
715 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
716 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000717 break;
718 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000719 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000720 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000721 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000722 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000723 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000724 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000725 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000726 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000727 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000728 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000729 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000730 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000731 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000732 break;
733 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000734 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000735 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000736 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000737 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000738 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000739 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000740 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000741 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000742 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000743 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000744 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000745 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000746 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000747 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000748 case Type::X86_FP80TyID:
749 case Type::PPC_FP128TyID:
750 case Type::FP128TyID: {
751 APFloat apfLHS = APFloat(LHS.IntVal);
752 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000753 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000754 case Instruction::FAdd:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000755 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000756 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000757 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000758 case Instruction::FSub:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000759 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000760 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000761 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000762 case Instruction::FMul:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000763 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000764 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000765 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000766 case Instruction::FDiv:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000767 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000768 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000769 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000770 case Instruction::FRem:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000771 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000772 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000773 break;
774 }
775 }
776 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000777 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000778 return GV;
779 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000780 default:
781 break;
782 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000783
784 SmallString<256> Msg;
785 raw_svector_ostream OS(Msg);
786 OS << "ConstantExpr not handled: " << *CE;
787 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000788 }
Misha Brukman835702a2005-04-21 22:36:52 +0000789
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000790 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000791 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000792 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000793 case Type::FloatTyID:
794 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000795 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000796 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000797 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000798 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000799 case Type::X86_FP80TyID:
800 case Type::FP128TyID:
801 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000802 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000803 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000804 case Type::IntegerTyID:
805 Result.IntVal = cast<ConstantInt>(C)->getValue();
806 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000807 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000808 if (isa<ConstantPointerNull>(C))
Chris Lattner996fe012002-12-24 00:01:05 +0000809 Result.PointerVal = 0;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000810 else if (const Function *F = dyn_cast<Function>(C))
811 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000812 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000813 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000814 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
815 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
816 BA->getBasicBlock())));
Reid Spencer6a0fd732004-07-18 00:41:27 +0000817 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000818 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000819 break;
820 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000821 SmallString<256> Msg;
822 raw_svector_ostream OS(Msg);
823 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
824 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000825 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000826
Chris Lattner996fe012002-12-24 00:01:05 +0000827 return Result;
828}
829
Duncan Sands1202d1b2007-12-14 19:38:31 +0000830/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
831/// with the integer held in IntVal.
832static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
833 unsigned StoreBytes) {
834 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
835 uint8_t *Src = (uint8_t *)IntVal.getRawData();
836
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000837 if (sys::isLittleEndianHost()) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000838 // Little-endian host - the source is ordered from LSB to MSB. Order the
839 // destination from LSB to MSB: Do a straight copy.
840 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000841 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000842 // Big-endian host - the source is an array of 64 bit words ordered from
843 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
844 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
845 while (StoreBytes > sizeof(uint64_t)) {
846 StoreBytes -= sizeof(uint64_t);
847 // May not be aligned so use memcpy.
848 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
849 Src += sizeof(uint64_t);
850 }
851
852 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
853 }
854}
855
Evan Cheng09053e62008-11-04 06:10:31 +0000856void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +0000857 GenericValue *Ptr, Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000858 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
859
Reid Spencer87aa65f2007-03-06 03:04:04 +0000860 switch (Ty->getTypeID()) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000861 case Type::IntegerTyID:
862 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000863 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000864 case Type::FloatTyID:
865 *((float*)Ptr) = Val.FloatVal;
866 break;
867 case Type::DoubleTyID:
868 *((double*)Ptr) = Val.DoubleVal;
869 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000870 case Type::X86_FP80TyID:
871 memcpy(Ptr, Val.IntVal.getRawData(), 10);
872 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000873 case Type::PointerTyID:
874 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
875 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +0000876 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +0000877
Reid Spencer87aa65f2007-03-06 03:04:04 +0000878 *((PointerTy*)Ptr) = Val.PointerVal;
879 break;
880 default:
David Greene0967d2d2010-01-05 01:27:39 +0000881 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattner996fe012002-12-24 00:01:05 +0000882 }
Duncan Sands1202d1b2007-12-14 19:38:31 +0000883
Chris Lattneraa121222009-01-22 19:53:00 +0000884 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000885 // Host and target are different endian - reverse the stored bytes.
886 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
887}
888
889/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
890/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
891static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
892 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
893 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
894
Chris Lattneraa121222009-01-22 19:53:00 +0000895 if (sys::isLittleEndianHost())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000896 // Little-endian host - the destination must be ordered from LSB to MSB.
897 // The source is ordered from LSB to MSB: Do a straight copy.
898 memcpy(Dst, Src, LoadBytes);
899 else {
900 // Big-endian - the destination is an array of 64 bit words ordered from
901 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
902 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
903 // a word.
904 while (LoadBytes > sizeof(uint64_t)) {
905 LoadBytes -= sizeof(uint64_t);
906 // May not be aligned so use memcpy.
907 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
908 Dst += sizeof(uint64_t);
909 }
910
911 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
912 }
Chris Lattner996fe012002-12-24 00:01:05 +0000913}
914
Misha Brukman857c21b2003-10-10 17:45:12 +0000915/// FIXME: document
916///
Duncan Sands1202d1b2007-12-14 19:38:31 +0000917void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +0000918 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +0000919 Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000920 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +0000921
Duncan Sands1202d1b2007-12-14 19:38:31 +0000922 switch (Ty->getTypeID()) {
923 case Type::IntegerTyID:
924 // An APInt with all words initially zero.
925 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
926 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
927 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000928 case Type::FloatTyID:
929 Result.FloatVal = *((float*)Ptr);
930 break;
931 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +0000932 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000933 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000934 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +0000935 Result.PointerVal = *((PointerTy*)Ptr);
936 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000937 case Type::X86_FP80TyID: {
938 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +0000939 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000940 uint64_t y[2];
941 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +0000942 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000943 break;
944 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000945 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000946 SmallString<256> Msg;
947 raw_svector_ostream OS(Msg);
948 OS << "Cannot load value of type " << *Ty << "!";
949 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +0000950 }
Chris Lattner7f389e82003-05-08 16:52:16 +0000951}
952
Chris Lattner996fe012002-12-24 00:01:05 +0000953void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +0000954 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +0000955 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +0000956 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +0000957 return;
Chris Lattner00245f42012-01-24 13:41:11 +0000958
959 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +0000960 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000961 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +0000962 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
963 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
964 return;
Chris Lattner00245f42012-01-24 13:41:11 +0000965 }
966
967 if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000968 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +0000969 return;
Chris Lattner00245f42012-01-24 13:41:11 +0000970 }
971
972 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000973 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000974 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000975 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
976 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
977 return;
Chris Lattner00245f42012-01-24 13:41:11 +0000978 }
979
980 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000981 const StructLayout *SL =
982 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
983 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
984 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
985 return;
Chris Lattner00245f42012-01-24 13:41:11 +0000986 }
987
988 if (const ConstantDataSequential *CDS =
989 dyn_cast<ConstantDataSequential>(Init)) {
990 // CDS is already laid out in host memory order.
991 StringRef Data = CDS->getRawDataValues();
992 memcpy(Addr, Data.data(), Data.size());
993 return;
994 }
995
996 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +0000997 GenericValue Val = getConstantValue(Init);
998 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
999 return;
1000 }
1001
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001002 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001003 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001004}
1005
Chris Lattner996fe012002-12-24 00:01:05 +00001006/// EmitGlobals - Emit all of the global variables to memory, storing their
1007/// addresses into GlobalAddress. This must make sure to copy the contents of
1008/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001009void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001010 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001011 // to hold them. If there is more than one module, do a prepass over globals
1012 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001013 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001014 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001015
Chris Lattner0621cae2006-08-16 01:24:12 +00001016 if (Modules.size() != 1) {
1017 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001018 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +00001019 for (Module::const_global_iterator I = M.global_begin(),
1020 E = M.global_end(); I != E; ++I) {
1021 const GlobalValue *GV = I;
Rafael Espindola6de96a12009-01-15 20:18:42 +00001022 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattner0621cae2006-08-16 01:24:12 +00001023 GV->hasAppendingLinkage() || !GV->hasName())
1024 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001025
1026 const GlobalValue *&GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +00001027 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1028
1029 // If this is the first time we've seen this global, it is the canonical
1030 // version.
1031 if (!GVEntry) {
1032 GVEntry = GV;
1033 continue;
1034 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001035
Chris Lattner0621cae2006-08-16 01:24:12 +00001036 // If the existing global is strong, never replace it.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +00001037 if (GVEntry->hasExternalLinkage() ||
1038 GVEntry->hasDLLImportLinkage() ||
1039 GVEntry->hasDLLExportLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001040 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001041
Chris Lattner0621cae2006-08-16 01:24:12 +00001042 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001043 // symbol. FIXME is this right for common?
Anton Korobeynikov12c94942006-12-01 00:25:12 +00001044 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001045 GVEntry = GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001046 }
Chris Lattner996fe012002-12-24 00:01:05 +00001047 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001048 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001049
Chris Lattner0621cae2006-08-16 01:24:12 +00001050 std::vector<const GlobalValue*> NonCanonicalGlobals;
1051 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001052 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +00001053 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1054 I != E; ++I) {
1055 // In the multi-module case, see what this global maps to.
1056 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001057 if (const GlobalValue *GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +00001058 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1059 // If something else is the canonical global, ignore this one.
1060 if (GVEntry != &*I) {
1061 NonCanonicalGlobals.push_back(I);
1062 continue;
1063 }
1064 }
1065 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001066
Reid Spencer5301e7c2007-01-30 20:08:39 +00001067 if (!I->isDeclaration()) {
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001068 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattner0621cae2006-08-16 01:24:12 +00001069 } else {
1070 // External variable reference. Try to use the dynamic loader to
1071 // get a pointer to it.
1072 if (void *SymAddr =
Daniel Dunbar5899e342009-07-21 08:54:24 +00001073 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattner0621cae2006-08-16 01:24:12 +00001074 addGlobalMapping(I, SymAddr);
1075 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001076 report_fatal_error("Could not resolve external global address: "
Torok Edwin6c2d2332009-07-07 17:32:34 +00001077 +I->getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001078 }
1079 }
1080 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001081
Chris Lattner0621cae2006-08-16 01:24:12 +00001082 // If there are multiple modules, map the non-canonical globals to their
1083 // canonical location.
1084 if (!NonCanonicalGlobals.empty()) {
1085 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1086 const GlobalValue *GV = NonCanonicalGlobals[i];
1087 const GlobalValue *CGV =
1088 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1089 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1090 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001091 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001092 }
1093 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001094
1095 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001096 // and initialize their contents.
Chris Lattner0621cae2006-08-16 01:24:12 +00001097 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1098 I != E; ++I) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001099 if (!I->isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001100 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001101 if (const GlobalValue *GVEntry =
Chris Lattner0621cae2006-08-16 01:24:12 +00001102 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1103 if (GVEntry != &*I) // Not the canonical variable.
1104 continue;
1105 }
1106 EmitGlobalVariable(I);
1107 }
1108 }
1109 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001110}
1111
1112// EmitGlobalVariable - This method emits the specified global variable to the
1113// address specified in GlobalAddresses, or allocates new memory if it's not
1114// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001115void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001116 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001117
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001118 if (GA == 0) {
1119 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001120 GA = getMemoryForGV(GV);
Chris Lattner748e8572003-12-31 20:21:04 +00001121 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001122 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001123
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001124 // Don't initialize if it's thread local, let the client do it.
1125 if (!GV->isThreadLocal())
1126 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001127
Chris Lattner229907c2011-07-18 04:54:35 +00001128 Type *ElTy = GV->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001129 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001130 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001131 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001132}
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001133
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001134ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1135 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001136}
1137
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001138sys::Mutex *
1139ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001140 return &EES->EE.lock;
1141}
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001142
1143void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1144 const GlobalValue *Old) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001145 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1146 EES->GlobalAddressReverseMap.erase(OldVal);
1147}
1148
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001149void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1150 const GlobalValue *,
1151 const GlobalValue *) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001152 assert(false && "The ExecutionEngine doesn't know how to handle a"
1153 " RAUW on a value it has a global mapping for.");
1154}