blob: 91d68fb1e2578f628f14f4d4dcf05410b1bcbdd0 [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000029#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000030#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000031#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000032#include <cmath>
33#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000034using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner36343732006-12-19 22:43:32 +000036STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000038
Jeffrey Yasskin46882612010-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 Dunbar6d135972010-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 Yasskinf0356fe2010-01-27 20:34:15 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000060 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000061
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000062ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000063 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000064 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000065 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000066 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000067 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000068 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000069 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000070 Modules.push_back(M);
71 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000072}
73
Brian Gaeke8e539482003-09-04 22:57:27 +000074ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000075 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000076 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
77 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000078}
79
Duncan Sandsb35fd442010-10-21 08:57:29 +000080void ExecutionEngine::DeregisterAllTables() {
81 if (ExceptionTableDeregister) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000082 for (std::vector<void*>::iterator it = AllExceptionTables.begin(),
83 ie = AllExceptionTables.end(); it != ie; ++it)
Duncan Sandsb35fd442010-10-21 08:57:29 +000084 ExceptionTableDeregister(*it);
85 AllExceptionTables.clear();
86 }
87}
88
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000089namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000090/// \brief Helper class which uses a value handler to automatically deletes the
91/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000092class GVMemoryBlock : public CallbackVH {
93 GVMemoryBlock(const GlobalVariable *GV)
94 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
95
96public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000097 /// \brief Returns the address the GlobalVariable should be written into. The
98 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000099 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
100 const Type *ElTy = GV->getType()->getElementType();
101 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
102 void *RawMemory = ::operator new(
103 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
104 TD.getPreferredAlignment(GV))
105 + GVSize);
106 new(RawMemory) GVMemoryBlock(GV);
107 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
108 }
109
110 virtual void deleted() {
111 // We allocated with operator new and with some extra memory hanging off the
112 // end, so don't just delete this. I'm not sure if this is actually
113 // required.
114 this->~GVMemoryBlock();
115 ::operator delete(this);
116 }
117};
118} // anonymous namespace
119
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000120char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000121 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000122}
123
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000124bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000125 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000126 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000127 Module *Found = *I;
128 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000129 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000130 clearGlobalMappingsFromModule(M);
131 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000132 }
133 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000134 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000135}
136
Chris Lattnerfe854032006-08-16 01:24:12 +0000137Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
138 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000139 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000140 return F;
141 }
142 return 0;
143}
144
145
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000146void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
147 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000149 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000150
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
152 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000153 if (I == GlobalAddressMap.end())
154 OldVal = 0;
155 else {
156 OldVal = I->second;
157 GlobalAddressMap.erase(I);
158 }
159
160 GlobalAddressReverseMap.erase(OldVal);
161 return OldVal;
162}
163
Chris Lattnere7fd5532006-05-08 22:00:52 +0000164void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
165 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000166
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000167 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000168 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000169 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000170 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
171 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000172
173 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000174 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000175 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000176 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000177 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
178 V = GV;
179 }
180}
181
Chris Lattnere7fd5532006-05-08 22:00:52 +0000182void ExecutionEngine::clearAllGlobalMappings() {
183 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000184
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000185 EEState.getGlobalAddressMap(locked).clear();
186 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187}
188
Nate Begemanf049e072008-05-21 16:34:48 +0000189void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000191
192 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000193 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000194 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
195 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000196 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000197}
198
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000199void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000200 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000201
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000202 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000203 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204
Chris Lattnere7fd5532006-05-08 22:00:52 +0000205 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000206 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000207 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000208
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000209 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000210 void *OldVal = CurVal;
211
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000212 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
213 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000214 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000215
216 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000217 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000218 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000219 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
221 V = GV;
222 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000223 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000224}
225
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
227 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000228
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
230 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000231 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000232}
233
Chris Lattner55d86482003-12-31 20:21:04 +0000234const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000235 MutexGuard locked(lock);
236
Chris Lattner55d86482003-12-31 20:21:04 +0000237 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000238 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000239 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000240 I = EEState.getGlobalAddressMap(locked).begin(),
241 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000242 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
243 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000244 }
245
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000246 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000247 EEState.getGlobalAddressReverseMap(locked).find(Addr);
248 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000249}
Chris Lattner87f03102003-12-26 06:50:30 +0000250
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000251namespace {
252class ArgvArray {
253 char *Array;
254 std::vector<char*> Values;
255public:
256 ArgvArray() : Array(NULL) {}
257 ~ArgvArray() { clear(); }
258 void clear() {
259 delete[] Array;
260 Array = NULL;
261 for (size_t I = 0, E = Values.size(); I != E; ++I) {
262 delete[] Values[I];
263 }
264 Values.clear();
265 }
266 /// Turn a vector of strings into a nice argv style array of pointers to null
267 /// terminated strings.
268 void *reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv);
270};
271} // anonymous namespace
272void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv) {
274 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000275 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000276 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000277
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000278 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000279 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000280
281 for (unsigned i = 0; i != InputArgv.size(); ++i) {
282 unsigned Size = InputArgv[i].size()+1;
283 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000284 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000285 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000286
Chris Lattner87f03102003-12-26 06:50:30 +0000287 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
288 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000289
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000290 // Endian safe: Array[i] = (PointerTy)Dest;
291 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000292 SBytePtr);
293 }
294
295 // Null terminate it
296 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000297 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000298 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000299 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000300}
301
Chris Lattnerfbd39762009-09-23 01:46:04 +0000302void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
303 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000304 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000305 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000306
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000307 // If this global has internal linkage, or if it has a use, then it must be
308 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
309 // this is the case, don't execute any of the global ctors, __main will do
310 // it.
311 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
312
313 // Should be an array of '{ int, void ()* }' structs. The first value is
314 // the init priority, which we ignore.
315 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
316 if (!InitList) return;
317 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
318 ConstantStruct *CS =
319 dyn_cast<ConstantStruct>(InitList->getOperand(i));
320 if (!CS) continue;
321 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
322
323 Constant *FP = CS->getOperand(1);
324 if (FP->isNullValue())
325 break; // Found a null terminator, exit.
326
327 // Strip off constant expression casts.
328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
329 if (CE->isCast())
330 FP = CE->getOperand(0);
331
332 // Execute the ctor/dtor function!
333 if (Function *F = dyn_cast<Function>(FP))
334 runFunction(F, std::vector<GenericValue>());
335
336 // FIXME: It is marginally lame that we just do nothing here if we see an
337 // entry we don't recognize. It might not be unreasonable for the verifier
338 // to not even allow this and just assert here.
339 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000340}
341
Evan Cheng18314dc2008-09-30 15:51:21 +0000342void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
343 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000344 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
345 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000346}
347
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000348#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000349/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
350static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
351 unsigned PtrSize = EE->getTargetData()->getPointerSize();
352 for (unsigned i = 0; i < PtrSize; ++i)
353 if (*(i + (uint8_t*)Loc))
354 return false;
355 return true;
356}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000357#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000358
Chris Lattner87f03102003-12-26 06:50:30 +0000359int ExecutionEngine::runFunctionAsMain(Function *Fn,
360 const std::vector<std::string> &argv,
361 const char * const * envp) {
362 std::vector<GenericValue> GVArgs;
363 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000364 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000365
366 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000367 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000368 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000369 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000370
371 // Check the argument types.
372 if (NumArgs > 3)
373 report_fatal_error("Invalid number of arguments of main() supplied");
374 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
375 report_fatal_error("Invalid type for third argument of main() supplied");
376 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
377 report_fatal_error("Invalid type for second argument of main() supplied");
378 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
379 report_fatal_error("Invalid type for first argument of main() supplied");
380 if (!FTy->getReturnType()->isIntegerTy() &&
381 !FTy->getReturnType()->isVoidTy())
382 report_fatal_error("Invalid return type of main() supplied");
383
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000384 ArgvArray CArgv;
385 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000386 if (NumArgs) {
387 GVArgs.push_back(GVArgc); // Arg #0 = argc.
388 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000389 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000390 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000391 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000392 "argv[0] was null after CreateArgv");
393 if (NumArgs > 2) {
394 std::vector<std::string> EnvVars;
395 for (unsigned i = 0; envp[i]; ++i)
396 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000397 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000398 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000399 }
400 }
401 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000402
Reid Spencer8fb0f192007-03-06 03:04:04 +0000403 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000404}
405
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000406ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000407 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000408 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000409 CodeGenOpt::Level OptLevel,
410 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000411 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000412 .setEngineKind(ForceInterpreter
413 ? EngineKind::Interpreter
414 : EngineKind::JIT)
415 .setErrorStr(ErrorStr)
416 .setOptLevel(OptLevel)
417 .setAllocateGVsWithCode(GVsWithCode)
418 .create();
419}
Brian Gaeke82d82772003-09-03 20:34:19 +0000420
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000421ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000422 // Make sure we can resolve symbols in the program as well. The zero arg
423 // to the function tells DynamicLibrary to load the program, not a library.
424 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
425 return 0;
426
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000427 // If the user specified a memory manager but didn't specify which engine to
428 // create, we assume they only want the JIT, and we fail if they only want
429 // the interpreter.
430 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000431 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000432 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000433 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000434 if (ErrorStr)
435 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000436 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000437 }
438 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000439
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000440 // Unless the interpreter was explicitly selected or the JIT is not linked,
441 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000442 if (WhichEngine & EngineKind::JIT) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000443 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
444 ExecutionEngine *EE =
445 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
446 AllocateGVsWithCode, CMModel,
447 MArch, MCPU, MAttrs);
448 if (EE) return EE;
449 } else if (ExecutionEngine::JITCtor) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000450 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000451 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000452 AllocateGVsWithCode, CMModel,
453 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000454 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000455 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000456 }
457
458 // If we can't make a JIT and we didn't request one specifically, try making
459 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000460 if (WhichEngine & EngineKind::Interpreter) {
461 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000462 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000463 if (ErrorStr)
464 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000465 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000466 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000467
468 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
469 if (ErrorStr)
470 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000471 }
472
Chris Lattnerfbd39762009-09-23 01:46:04 +0000473 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000474}
475
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000476void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000477 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000478 return getPointerToFunction(F);
479
Reid Spenceree448632005-07-12 15:51:55 +0000480 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000481 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
482 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000483
484 // Global variable might have been added since interpreter started.
485 if (GlobalVariable *GVar =
486 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
487 EmitGlobalVariable(GVar);
488 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000489 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000490
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000491 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000492}
493
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000494/// \brief Converts a Constant* into a GenericValue, including handling of
495/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000496GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000497 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000498 if (isa<UndefValue>(C)) {
499 GenericValue Result;
500 switch (C->getType()->getTypeID()) {
501 case Type::IntegerTyID:
502 case Type::X86_FP80TyID:
503 case Type::FP128TyID:
504 case Type::PPC_FP128TyID:
505 // Although the value is undefined, we still have to construct an APInt
506 // with the correct bit width.
507 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
508 break;
509 default:
510 break;
511 }
512 return Result;
513 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000514
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000515 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000516 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000517 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000518 switch (CE->getOpcode()) {
519 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000520 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000521 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000522 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000523 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000524 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000525
Reid Spencer8fb0f192007-03-06 03:04:04 +0000526 char* tmp = (char*) Result.PointerVal;
527 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000528 return Result;
529 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000530 case Instruction::Trunc: {
531 GenericValue GV = getConstantValue(Op0);
532 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
533 GV.IntVal = GV.IntVal.trunc(BitWidth);
534 return GV;
535 }
536 case Instruction::ZExt: {
537 GenericValue GV = getConstantValue(Op0);
538 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
539 GV.IntVal = GV.IntVal.zext(BitWidth);
540 return GV;
541 }
542 case Instruction::SExt: {
543 GenericValue GV = getConstantValue(Op0);
544 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
545 GV.IntVal = GV.IntVal.sext(BitWidth);
546 return GV;
547 }
548 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000549 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000550 GenericValue GV = getConstantValue(Op0);
551 GV.FloatVal = float(GV.DoubleVal);
552 return GV;
553 }
554 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000555 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000556 GenericValue GV = getConstantValue(Op0);
557 GV.DoubleVal = double(GV.FloatVal);
558 return GV;
559 }
560 case Instruction::UIToFP: {
561 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000562 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000563 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000564 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000565 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000566 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000567 const uint64_t zero[] = {0, 0};
568 APFloat apf = APFloat(APInt(80, 2, zero));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000569 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000570 false,
571 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000572 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000573 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000574 return GV;
575 }
576 case Instruction::SIToFP: {
577 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000578 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000579 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000580 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000581 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000582 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000583 const uint64_t zero[] = { 0, 0};
584 APFloat apf = APFloat(APInt(80, 2, zero));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000585 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000586 true,
587 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000588 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000589 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000590 return GV;
591 }
592 case Instruction::FPToUI: // double->APInt conversion handles sign
593 case Instruction::FPToSI: {
594 GenericValue GV = getConstantValue(Op0);
595 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000596 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000597 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000598 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000599 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000600 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000601 APFloat apf = APFloat(GV.IntVal);
602 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000603 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000604 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000605 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000606 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000607 GV.IntVal = v; // endian?
608 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 return GV;
610 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000611 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000612 GenericValue GV = getConstantValue(Op0);
613 uint32_t PtrWidth = TD->getPointerSizeInBits();
614 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
615 return GV;
616 }
617 case Instruction::IntToPtr: {
618 GenericValue GV = getConstantValue(Op0);
619 uint32_t PtrWidth = TD->getPointerSizeInBits();
620 if (PtrWidth != GV.IntVal.getBitWidth())
621 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
622 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
623 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000624 return GV;
625 }
626 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000627 GenericValue GV = getConstantValue(Op0);
628 const Type* DestTy = CE->getType();
629 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000630 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000631 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000632 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000633 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000634 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000635 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 GV.DoubleVal = GV.IntVal.bitsToDouble();
637 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000638 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000639 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 GV.IntVal.floatToBits(GV.FloatVal);
641 break;
642 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000643 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000644 GV.IntVal.doubleToBits(GV.DoubleVal);
645 break;
646 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000647 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000648 break; // getConstantValue(Op0) above already converted it
649 }
650 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000651 }
Chris Lattner9a231222003-05-14 17:51:49 +0000652 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000653 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000654 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000655 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000657 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000658 case Instruction::UDiv:
659 case Instruction::SDiv:
660 case Instruction::URem:
661 case Instruction::SRem:
662 case Instruction::And:
663 case Instruction::Or:
664 case Instruction::Xor: {
665 GenericValue LHS = getConstantValue(Op0);
666 GenericValue RHS = getConstantValue(CE->getOperand(1));
667 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000668 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000669 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000670 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000672 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
674 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
675 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
676 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
677 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
678 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
679 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
680 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
681 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
682 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
683 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000684 break;
685 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000686 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000687 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000688 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000689 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000690 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000691 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000692 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000694 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000695 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000696 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000697 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000698 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000699 break;
700 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000701 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000702 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000703 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000704 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000705 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000706 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000707 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000708 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000709 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000710 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000711 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000712 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000713 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000714 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000715 case Type::X86_FP80TyID:
716 case Type::PPC_FP128TyID:
717 case Type::FP128TyID: {
718 APFloat apfLHS = APFloat(LHS.IntVal);
719 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000720 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000721 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000722 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000723 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000724 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000725 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000726 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000727 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000728 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000729 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000730 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000731 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000732 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000733 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000734 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000735 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000736 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000737 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000738 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000739 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000740 break;
741 }
742 }
743 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000744 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000745 return GV;
746 }
Chris Lattner9a231222003-05-14 17:51:49 +0000747 default:
748 break;
749 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000750
751 SmallString<256> Msg;
752 raw_svector_ostream OS(Msg);
753 OS << "ConstantExpr not handled: " << *CE;
754 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000755 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000756
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000757 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000758 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000759 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000760 case Type::FloatTyID:
761 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000762 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000763 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000764 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000765 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000766 case Type::X86_FP80TyID:
767 case Type::FP128TyID:
768 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000769 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000770 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000771 case Type::IntegerTyID:
772 Result.IntVal = cast<ConstantInt>(C)->getValue();
773 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000774 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000775 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000776 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000777 else if (const Function *F = dyn_cast<Function>(C))
778 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000779 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000780 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000781 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
782 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
783 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000784 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000785 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000786 break;
787 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000788 SmallString<256> Msg;
789 raw_svector_ostream OS(Msg);
790 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
791 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000792 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000793
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000794 return Result;
795}
796
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000797/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
798/// with the integer held in IntVal.
799static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
800 unsigned StoreBytes) {
801 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
802 uint8_t *Src = (uint8_t *)IntVal.getRawData();
803
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000804 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000805 // Little-endian host - the source is ordered from LSB to MSB. Order the
806 // destination from LSB to MSB: Do a straight copy.
807 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000808 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000809 // Big-endian host - the source is an array of 64 bit words ordered from
810 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
811 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
812 while (StoreBytes > sizeof(uint64_t)) {
813 StoreBytes -= sizeof(uint64_t);
814 // May not be aligned so use memcpy.
815 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
816 Src += sizeof(uint64_t);
817 }
818
819 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
820 }
821}
822
Evan Cheng89687e32008-11-04 06:10:31 +0000823void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
824 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000825 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
826
Reid Spencer8fb0f192007-03-06 03:04:04 +0000827 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000828 case Type::IntegerTyID:
829 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000830 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000831 case Type::FloatTyID:
832 *((float*)Ptr) = Val.FloatVal;
833 break;
834 case Type::DoubleTyID:
835 *((double*)Ptr) = Val.DoubleVal;
836 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000837 case Type::X86_FP80TyID:
838 memcpy(Ptr, Val.IntVal.getRawData(), 10);
839 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000840 case Type::PointerTyID:
841 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
842 if (StoreBytes != sizeof(PointerTy))
843 memset(Ptr, 0, StoreBytes);
844
Reid Spencer8fb0f192007-03-06 03:04:04 +0000845 *((PointerTy*)Ptr) = Val.PointerVal;
846 break;
847 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000848 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000849 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000850
Chris Lattnerb67c9582009-01-22 19:53:00 +0000851 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000852 // Host and target are different endian - reverse the stored bytes.
853 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
854}
855
856/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
857/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
858static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
859 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
860 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
861
Chris Lattnerb67c9582009-01-22 19:53:00 +0000862 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000863 // Little-endian host - the destination must be ordered from LSB to MSB.
864 // The source is ordered from LSB to MSB: Do a straight copy.
865 memcpy(Dst, Src, LoadBytes);
866 else {
867 // Big-endian - the destination is an array of 64 bit words ordered from
868 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
869 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
870 // a word.
871 while (LoadBytes > sizeof(uint64_t)) {
872 LoadBytes -= sizeof(uint64_t);
873 // May not be aligned so use memcpy.
874 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
875 Dst += sizeof(uint64_t);
876 }
877
878 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
879 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000880}
881
Misha Brukman4afac182003-10-10 17:45:12 +0000882/// FIXME: document
883///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000884void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000885 GenericValue *Ptr,
886 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000887 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000888
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000889 switch (Ty->getTypeID()) {
890 case Type::IntegerTyID:
891 // An APInt with all words initially zero.
892 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
893 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
894 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000895 case Type::FloatTyID:
896 Result.FloatVal = *((float*)Ptr);
897 break;
898 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000899 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000900 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000901 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000902 Result.PointerVal = *((PointerTy*)Ptr);
903 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000904 case Type::X86_FP80TyID: {
905 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000906 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000907 uint64_t y[2];
908 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000909 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000910 break;
911 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000912 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000913 SmallString<256> Msg;
914 raw_svector_ostream OS(Msg);
915 OS << "Cannot load value of type " << *Ty << "!";
916 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000917 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000918}
919
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000920void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000921 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000922 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000923 if (isa<UndefValue>(Init)) {
924 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000925 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000926 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000927 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000928 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
929 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
930 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000931 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000932 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000933 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000934 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
935 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000936 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000937 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
938 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
939 return;
940 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
941 const StructLayout *SL =
942 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
943 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
944 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
945 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000946 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000947 GenericValue Val = getConstantValue(Init);
948 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
949 return;
950 }
951
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000952 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000953 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000954}
955
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000956/// EmitGlobals - Emit all of the global variables to memory, storing their
957/// addresses into GlobalAddress. This must make sure to copy the contents of
958/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000959void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000960 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000961 // to hold them. If there is more than one module, do a prepass over globals
962 // to figure out how the different modules should link together.
Chris Lattnerfe854032006-08-16 01:24:12 +0000963 std::map<std::pair<std::string, const Type*>,
964 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000965
Chris Lattnerfe854032006-08-16 01:24:12 +0000966 if (Modules.size() != 1) {
967 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000968 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000969 for (Module::const_global_iterator I = M.global_begin(),
970 E = M.global_end(); I != E; ++I) {
971 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000972 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000973 GV->hasAppendingLinkage() || !GV->hasName())
974 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000975
976 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +0000977 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
978
979 // If this is the first time we've seen this global, it is the canonical
980 // version.
981 if (!GVEntry) {
982 GVEntry = GV;
983 continue;
984 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000985
Chris Lattnerfe854032006-08-16 01:24:12 +0000986 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000987 if (GVEntry->hasExternalLinkage() ||
988 GVEntry->hasDLLImportLinkage() ||
989 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000990 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000991
Chris Lattnerfe854032006-08-16 01:24:12 +0000992 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000993 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000994 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000995 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000996 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000997 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000999
Chris Lattnerfe854032006-08-16 01:24:12 +00001000 std::vector<const GlobalValue*> NonCanonicalGlobals;
1001 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001002 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001003 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1004 I != E; ++I) {
1005 // In the multi-module case, see what this global maps to.
1006 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001007 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001008 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1009 // If something else is the canonical global, ignore this one.
1010 if (GVEntry != &*I) {
1011 NonCanonicalGlobals.push_back(I);
1012 continue;
1013 }
1014 }
1015 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001016
Reid Spencer5cbf9852007-01-30 20:08:39 +00001017 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001018 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001019 } else {
1020 // External variable reference. Try to use the dynamic loader to
1021 // get a pointer to it.
1022 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001023 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001024 addGlobalMapping(I, SymAddr);
1025 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001026 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001027 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001028 }
1029 }
1030 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001031
Chris Lattnerfe854032006-08-16 01:24:12 +00001032 // If there are multiple modules, map the non-canonical globals to their
1033 // canonical location.
1034 if (!NonCanonicalGlobals.empty()) {
1035 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1036 const GlobalValue *GV = NonCanonicalGlobals[i];
1037 const GlobalValue *CGV =
1038 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1039 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1040 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001041 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001042 }
1043 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001044
1045 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001046 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001047 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1048 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001049 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001050 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001051 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001052 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1053 if (GVEntry != &*I) // Not the canonical variable.
1054 continue;
1055 }
1056 EmitGlobalVariable(I);
1057 }
1058 }
1059 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001060}
1061
1062// EmitGlobalVariable - This method emits the specified global variable to the
1063// address specified in GlobalAddresses, or allocates new memory if it's not
1064// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001065void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001066 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001067
Chris Lattner24b0a182003-12-20 02:45:37 +00001068 if (GA == 0) {
1069 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001070 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001071 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001072 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001073
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001074 // Don't initialize if it's thread local, let the client do it.
1075 if (!GV->isThreadLocal())
1076 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001077
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001078 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001079 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001080 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001081 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001082}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001083
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001084ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1085 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001086}
1087
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001088sys::Mutex *
1089ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001090 return &EES->EE.lock;
1091}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001092
1093void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1094 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001095 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1096 EES->GlobalAddressReverseMap.erase(OldVal);
1097}
1098
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001099void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1100 const GlobalValue *,
1101 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001102 assert(false && "The ExecutionEngine doesn't know how to handle a"
1103 " RAUW on a value it has a global mapping for.");
1104}