blob: 13e07acc1519ed3d515122825928eed214ad10a7 [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"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000029#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/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) {
Eric Christopher515c67e2011-03-04 23:37:39 +000082 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
83 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
84 for (; it != ite; ++it)
85 ExceptionTableDeregister(it->second);
Duncan Sandsb35fd442010-10-21 08:57:29 +000086 AllExceptionTables.clear();
87 }
88}
89
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000090namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000091/// \brief Helper class which uses a value handler to automatically deletes the
92/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000093class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96
97public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000098 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000100 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
101 const Type *ElTy = GV->getType()->getElementType();
102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
104 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
105 TD.getPreferredAlignment(GV))
106 + GVSize);
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109 }
110
111 virtual void deleted() {
112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
114 // required.
115 this->~GVMemoryBlock();
116 ::operator delete(this);
117 }
118};
119} // anonymous namespace
120
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000121char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000122 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000123}
124
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000125bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000126 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000127 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000128 Module *Found = *I;
129 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000130 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000131 clearGlobalMappingsFromModule(M);
132 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000133 }
134 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000135 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000136}
137
Chris Lattnerfe854032006-08-16 01:24:12 +0000138Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
139 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000140 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000141 return F;
142 }
143 return 0;
144}
145
146
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000147void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
148 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000149 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000150 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000151
152 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
153 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000154 if (I == GlobalAddressMap.end())
155 OldVal = 0;
156 else {
157 OldVal = I->second;
158 GlobalAddressMap.erase(I);
159 }
160
161 GlobalAddressReverseMap.erase(OldVal);
162 return OldVal;
163}
164
Chris Lattnere7fd5532006-05-08 22:00:52 +0000165void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
166 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000167
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000168 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000169 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000170 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000171 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
172 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000173
174 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000175 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000176 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000177 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000178 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
179 V = GV;
180 }
181}
182
Chris Lattnere7fd5532006-05-08 22:00:52 +0000183void ExecutionEngine::clearAllGlobalMappings() {
184 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000185
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000186 EEState.getGlobalAddressMap(locked).clear();
187 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000188}
189
Nate Begemanf049e072008-05-21 16:34:48 +0000190void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
191 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000192
193 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000194 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000195 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
196 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000197 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000198}
199
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000200void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000201 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000202
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000203 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000204 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000205
Chris Lattnere7fd5532006-05-08 22:00:52 +0000206 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000207 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000208 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000209
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000210 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000211 void *OldVal = CurVal;
212
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000213 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
214 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000215 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000216
217 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000218 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000219 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000221 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
222 V = GV;
223 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000224 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000225}
226
Chris Lattnere7fd5532006-05-08 22:00:52 +0000227void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
228 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000229
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000230 ExecutionEngineState::GlobalAddressMapTy::iterator I =
231 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000232 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000233}
234
Chris Lattner55d86482003-12-31 20:21:04 +0000235const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000236 MutexGuard locked(lock);
237
Chris Lattner55d86482003-12-31 20:21:04 +0000238 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000239 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000240 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000241 I = EEState.getGlobalAddressMap(locked).begin(),
242 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000243 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
244 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000245 }
246
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000247 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000248 EEState.getGlobalAddressReverseMap(locked).find(Addr);
249 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000250}
Chris Lattner87f03102003-12-26 06:50:30 +0000251
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000252namespace {
253class ArgvArray {
254 char *Array;
255 std::vector<char*> Values;
256public:
257 ArgvArray() : Array(NULL) {}
258 ~ArgvArray() { clear(); }
259 void clear() {
260 delete[] Array;
261 Array = NULL;
262 for (size_t I = 0, E = Values.size(); I != E; ++I) {
263 delete[] Values[I];
264 }
265 Values.clear();
266 }
267 /// Turn a vector of strings into a nice argv style array of pointers to null
268 /// terminated strings.
269 void *reset(LLVMContext &C, ExecutionEngine *EE,
270 const std::vector<std::string> &InputArgv);
271};
272} // anonymous namespace
273void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
274 const std::vector<std::string> &InputArgv) {
275 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000276 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000277 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000278
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000279 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000280 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000281
282 for (unsigned i = 0; i != InputArgv.size(); ++i) {
283 unsigned Size = InputArgv[i].size()+1;
284 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000285 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000286 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000287
Chris Lattner87f03102003-12-26 06:50:30 +0000288 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
289 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000290
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000291 // Endian safe: Array[i] = (PointerTy)Dest;
292 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000293 SBytePtr);
294 }
295
296 // Null terminate it
297 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000298 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000299 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000300 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000301}
302
Chris Lattnerfbd39762009-09-23 01:46:04 +0000303void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
304 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000305 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000306 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000307
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000308 // If this global has internal linkage, or if it has a use, then it must be
309 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
310 // this is the case, don't execute any of the global ctors, __main will do
311 // it.
312 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
313
Nick Lewyckya040d472011-04-06 20:38:44 +0000314 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000315 // the init priority, which we ignore.
Nick Lewycky2c44a802011-04-08 07:30:21 +0000316 ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000317 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Nick Lewycky2c44a802011-04-08 07:30:21 +0000318 ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000319
320 Constant *FP = CS->getOperand(1);
321 if (FP->isNullValue())
322 break; // Found a null terminator, exit.
323
324 // Strip off constant expression casts.
325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
326 if (CE->isCast())
327 FP = CE->getOperand(0);
328
329 // Execute the ctor/dtor function!
330 if (Function *F = dyn_cast<Function>(FP))
331 runFunction(F, std::vector<GenericValue>());
332
333 // FIXME: It is marginally lame that we just do nothing here if we see an
334 // entry we don't recognize. It might not be unreasonable for the verifier
335 // to not even allow this and just assert here.
336 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000337}
338
Evan Cheng18314dc2008-09-30 15:51:21 +0000339void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
340 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000341 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
342 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000343}
344
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000345#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000346/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
347static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
348 unsigned PtrSize = EE->getTargetData()->getPointerSize();
349 for (unsigned i = 0; i < PtrSize; ++i)
350 if (*(i + (uint8_t*)Loc))
351 return false;
352 return true;
353}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000354#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000355
Chris Lattner87f03102003-12-26 06:50:30 +0000356int ExecutionEngine::runFunctionAsMain(Function *Fn,
357 const std::vector<std::string> &argv,
358 const char * const * envp) {
359 std::vector<GenericValue> GVArgs;
360 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000361 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000362
363 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000364 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000365 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000366 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000367
368 // Check the argument types.
369 if (NumArgs > 3)
370 report_fatal_error("Invalid number of arguments of main() supplied");
371 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
372 report_fatal_error("Invalid type for third argument of main() supplied");
373 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
374 report_fatal_error("Invalid type for second argument of main() supplied");
375 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
376 report_fatal_error("Invalid type for first argument of main() supplied");
377 if (!FTy->getReturnType()->isIntegerTy() &&
378 !FTy->getReturnType()->isVoidTy())
379 report_fatal_error("Invalid return type of main() supplied");
380
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000381 ArgvArray CArgv;
382 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000383 if (NumArgs) {
384 GVArgs.push_back(GVArgc); // Arg #0 = argc.
385 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000386 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000387 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000388 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000389 "argv[0] was null after CreateArgv");
390 if (NumArgs > 2) {
391 std::vector<std::string> EnvVars;
392 for (unsigned i = 0; envp[i]; ++i)
393 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000394 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000395 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000396 }
397 }
398 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000399
Reid Spencer8fb0f192007-03-06 03:04:04 +0000400 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000401}
402
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000403ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000404 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000405 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000406 CodeGenOpt::Level OptLevel,
407 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000408 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000409 .setEngineKind(ForceInterpreter
410 ? EngineKind::Interpreter
411 : EngineKind::JIT)
412 .setErrorStr(ErrorStr)
413 .setOptLevel(OptLevel)
414 .setAllocateGVsWithCode(GVsWithCode)
415 .create();
416}
Brian Gaeke82d82772003-09-03 20:34:19 +0000417
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000418ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000419 // Make sure we can resolve symbols in the program as well. The zero arg
420 // to the function tells DynamicLibrary to load the program, not a library.
421 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
422 return 0;
423
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000424 // If the user specified a memory manager but didn't specify which engine to
425 // create, we assume they only want the JIT, and we fail if they only want
426 // the interpreter.
427 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000428 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000429 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000430 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000431 if (ErrorStr)
432 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000433 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000434 }
435 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000436
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000437 // Unless the interpreter was explicitly selected or the JIT is not linked,
438 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000439 if (WhichEngine & EngineKind::JIT) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000440 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
441 ExecutionEngine *EE =
442 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
443 AllocateGVsWithCode, CMModel,
444 MArch, MCPU, MAttrs);
445 if (EE) return EE;
446 } else if (ExecutionEngine::JITCtor) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000447 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000448 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000449 AllocateGVsWithCode, CMModel,
450 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000451 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000452 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000453 }
454
455 // If we can't make a JIT and we didn't request one specifically, try making
456 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000457 if (WhichEngine & EngineKind::Interpreter) {
458 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000459 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000460 if (ErrorStr)
461 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000462 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000463 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000464
465 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
466 if (ErrorStr)
467 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000468 }
469
Chris Lattnerfbd39762009-09-23 01:46:04 +0000470 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000471}
472
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000473void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000474 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000475 return getPointerToFunction(F);
476
Reid Spenceree448632005-07-12 15:51:55 +0000477 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000478 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
479 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000480
481 // Global variable might have been added since interpreter started.
482 if (GlobalVariable *GVar =
483 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
484 EmitGlobalVariable(GVar);
485 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000486 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000487
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000488 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000489}
490
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000491/// \brief Converts a Constant* into a GenericValue, including handling of
492/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000493GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000494 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000495 if (isa<UndefValue>(C)) {
496 GenericValue Result;
497 switch (C->getType()->getTypeID()) {
498 case Type::IntegerTyID:
499 case Type::X86_FP80TyID:
500 case Type::FP128TyID:
501 case Type::PPC_FP128TyID:
502 // Although the value is undefined, we still have to construct an APInt
503 // with the correct bit width.
504 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
505 break;
506 default:
507 break;
508 }
509 return Result;
510 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000511
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000512 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000513 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000514 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000515 switch (CE->getOpcode()) {
516 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000517 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000518 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000519 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000520 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000521 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000522
Reid Spencer8fb0f192007-03-06 03:04:04 +0000523 char* tmp = (char*) Result.PointerVal;
524 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000525 return Result;
526 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000527 case Instruction::Trunc: {
528 GenericValue GV = getConstantValue(Op0);
529 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
530 GV.IntVal = GV.IntVal.trunc(BitWidth);
531 return GV;
532 }
533 case Instruction::ZExt: {
534 GenericValue GV = getConstantValue(Op0);
535 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
536 GV.IntVal = GV.IntVal.zext(BitWidth);
537 return GV;
538 }
539 case Instruction::SExt: {
540 GenericValue GV = getConstantValue(Op0);
541 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
542 GV.IntVal = GV.IntVal.sext(BitWidth);
543 return GV;
544 }
545 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000546 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000547 GenericValue GV = getConstantValue(Op0);
548 GV.FloatVal = float(GV.DoubleVal);
549 return GV;
550 }
551 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000552 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000553 GenericValue GV = getConstantValue(Op0);
554 GV.DoubleVal = double(GV.FloatVal);
555 return GV;
556 }
557 case Instruction::UIToFP: {
558 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000559 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000560 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000561 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000562 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000563 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000564 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000565 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000566 false,
567 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000568 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000569 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000570 return GV;
571 }
572 case Instruction::SIToFP: {
573 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000574 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000575 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000576 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000577 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000578 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000579 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000580 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000581 true,
582 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000583 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000584 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000585 return GV;
586 }
587 case Instruction::FPToUI: // double->APInt conversion handles sign
588 case Instruction::FPToSI: {
589 GenericValue GV = getConstantValue(Op0);
590 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000591 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000592 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000593 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000594 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000595 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000596 APFloat apf = APFloat(GV.IntVal);
597 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000598 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000599 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000600 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000601 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000602 GV.IntVal = v; // endian?
603 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000604 return GV;
605 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000606 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000607 GenericValue GV = getConstantValue(Op0);
608 uint32_t PtrWidth = TD->getPointerSizeInBits();
609 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
610 return GV;
611 }
612 case Instruction::IntToPtr: {
613 GenericValue GV = getConstantValue(Op0);
614 uint32_t PtrWidth = TD->getPointerSizeInBits();
615 if (PtrWidth != GV.IntVal.getBitWidth())
616 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
617 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
618 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000619 return GV;
620 }
621 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000622 GenericValue GV = getConstantValue(Op0);
623 const Type* DestTy = CE->getType();
624 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000625 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000627 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000628 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000629 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000630 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000631 GV.DoubleVal = GV.IntVal.bitsToDouble();
632 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000633 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000634 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000635 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 break;
637 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000638 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000639 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 break;
641 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000642 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 break; // getConstantValue(Op0) above already converted it
644 }
645 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000646 }
Chris Lattner9a231222003-05-14 17:51:49 +0000647 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000648 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000649 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000650 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000651 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000652 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000653 case Instruction::UDiv:
654 case Instruction::SDiv:
655 case Instruction::URem:
656 case Instruction::SRem:
657 case Instruction::And:
658 case Instruction::Or:
659 case Instruction::Xor: {
660 GenericValue LHS = getConstantValue(Op0);
661 GenericValue RHS = getConstantValue(CE->getOperand(1));
662 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000663 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000664 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000665 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000666 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000667 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000668 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
669 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
670 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
671 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
672 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
673 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
674 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
675 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
676 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
677 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
678 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000679 break;
680 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000681 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000682 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000683 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000684 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000685 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000686 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000687 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000688 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000689 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000690 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000691 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000692 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000694 break;
695 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000696 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000697 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000698 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000699 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000700 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000701 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000702 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000703 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000704 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000705 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000706 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000707 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000708 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000709 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000710 case Type::X86_FP80TyID:
711 case Type::PPC_FP128TyID:
712 case Type::FP128TyID: {
713 APFloat apfLHS = APFloat(LHS.IntVal);
714 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000715 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000716 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000717 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000718 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000719 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000720 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000721 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000722 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000723 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000724 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000725 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000726 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000727 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000728 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000729 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000730 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000731 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000732 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000733 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000734 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000735 break;
736 }
737 }
738 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000739 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 return GV;
741 }
Chris Lattner9a231222003-05-14 17:51:49 +0000742 default:
743 break;
744 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000745
746 SmallString<256> Msg;
747 raw_svector_ostream OS(Msg);
748 OS << "ConstantExpr not handled: " << *CE;
749 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000750 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000751
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000752 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000753 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000754 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000755 case Type::FloatTyID:
756 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000757 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000758 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000759 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000760 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000761 case Type::X86_FP80TyID:
762 case Type::FP128TyID:
763 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000764 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000765 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000766 case Type::IntegerTyID:
767 Result.IntVal = cast<ConstantInt>(C)->getValue();
768 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000769 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000770 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000771 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000772 else if (const Function *F = dyn_cast<Function>(C))
773 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000774 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000775 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000776 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
777 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
778 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000779 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000780 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000781 break;
782 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000783 SmallString<256> Msg;
784 raw_svector_ostream OS(Msg);
785 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
786 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000787 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000788
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000789 return Result;
790}
791
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000792/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
793/// with the integer held in IntVal.
794static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
795 unsigned StoreBytes) {
796 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
797 uint8_t *Src = (uint8_t *)IntVal.getRawData();
798
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000799 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000800 // Little-endian host - the source is ordered from LSB to MSB. Order the
801 // destination from LSB to MSB: Do a straight copy.
802 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000803 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000804 // Big-endian host - the source is an array of 64 bit words ordered from
805 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
806 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
807 while (StoreBytes > sizeof(uint64_t)) {
808 StoreBytes -= sizeof(uint64_t);
809 // May not be aligned so use memcpy.
810 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
811 Src += sizeof(uint64_t);
812 }
813
814 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
815 }
816}
817
Evan Cheng89687e32008-11-04 06:10:31 +0000818void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
819 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000820 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
821
Reid Spencer8fb0f192007-03-06 03:04:04 +0000822 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000823 case Type::IntegerTyID:
824 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000825 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000826 case Type::FloatTyID:
827 *((float*)Ptr) = Val.FloatVal;
828 break;
829 case Type::DoubleTyID:
830 *((double*)Ptr) = Val.DoubleVal;
831 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000832 case Type::X86_FP80TyID:
833 memcpy(Ptr, Val.IntVal.getRawData(), 10);
834 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000835 case Type::PointerTyID:
836 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
837 if (StoreBytes != sizeof(PointerTy))
838 memset(Ptr, 0, StoreBytes);
839
Reid Spencer8fb0f192007-03-06 03:04:04 +0000840 *((PointerTy*)Ptr) = Val.PointerVal;
841 break;
842 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000843 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000844 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000845
Chris Lattnerb67c9582009-01-22 19:53:00 +0000846 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000847 // Host and target are different endian - reverse the stored bytes.
848 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
849}
850
851/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
852/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
853static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
854 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
855 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
856
Chris Lattnerb67c9582009-01-22 19:53:00 +0000857 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000858 // Little-endian host - the destination must be ordered from LSB to MSB.
859 // The source is ordered from LSB to MSB: Do a straight copy.
860 memcpy(Dst, Src, LoadBytes);
861 else {
862 // Big-endian - the destination is an array of 64 bit words ordered from
863 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
864 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
865 // a word.
866 while (LoadBytes > sizeof(uint64_t)) {
867 LoadBytes -= sizeof(uint64_t);
868 // May not be aligned so use memcpy.
869 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
870 Dst += sizeof(uint64_t);
871 }
872
873 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
874 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000875}
876
Misha Brukman4afac182003-10-10 17:45:12 +0000877/// FIXME: document
878///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000879void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000880 GenericValue *Ptr,
881 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000882 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000883
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000884 switch (Ty->getTypeID()) {
885 case Type::IntegerTyID:
886 // An APInt with all words initially zero.
887 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
888 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
889 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000890 case Type::FloatTyID:
891 Result.FloatVal = *((float*)Ptr);
892 break;
893 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000894 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000895 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000896 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000897 Result.PointerVal = *((PointerTy*)Ptr);
898 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000899 case Type::X86_FP80TyID: {
900 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000901 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000902 uint64_t y[2];
903 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000904 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000905 break;
906 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000907 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000908 SmallString<256> Msg;
909 raw_svector_ostream OS(Msg);
910 OS << "Cannot load value of type " << *Ty << "!";
911 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000912 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000913}
914
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000915void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000916 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000917 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000918 if (isa<UndefValue>(Init)) {
919 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000920 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000921 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000922 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000923 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
924 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
925 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000926 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000927 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000928 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000929 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
930 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000931 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000932 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
933 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
934 return;
935 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
936 const StructLayout *SL =
937 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
938 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
939 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
940 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000941 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000942 GenericValue Val = getConstantValue(Init);
943 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
944 return;
945 }
946
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000947 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000948 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000949}
950
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000951/// EmitGlobals - Emit all of the global variables to memory, storing their
952/// addresses into GlobalAddress. This must make sure to copy the contents of
953/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000954void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000955 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000956 // to hold them. If there is more than one module, do a prepass over globals
957 // to figure out how the different modules should link together.
Chris Lattnerfe854032006-08-16 01:24:12 +0000958 std::map<std::pair<std::string, const Type*>,
959 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000960
Chris Lattnerfe854032006-08-16 01:24:12 +0000961 if (Modules.size() != 1) {
962 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000963 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000964 for (Module::const_global_iterator I = M.global_begin(),
965 E = M.global_end(); I != E; ++I) {
966 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000967 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000968 GV->hasAppendingLinkage() || !GV->hasName())
969 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000970
971 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +0000972 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
973
974 // If this is the first time we've seen this global, it is the canonical
975 // version.
976 if (!GVEntry) {
977 GVEntry = GV;
978 continue;
979 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000980
Chris Lattnerfe854032006-08-16 01:24:12 +0000981 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000982 if (GVEntry->hasExternalLinkage() ||
983 GVEntry->hasDLLImportLinkage() ||
984 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000985 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000986
Chris Lattnerfe854032006-08-16 01:24:12 +0000987 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000988 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000989 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000990 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000991 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000992 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000993 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000994
Chris Lattnerfe854032006-08-16 01:24:12 +0000995 std::vector<const GlobalValue*> NonCanonicalGlobals;
996 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000997 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
999 I != E; ++I) {
1000 // In the multi-module case, see what this global maps to.
1001 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001002 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001003 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1004 // If something else is the canonical global, ignore this one.
1005 if (GVEntry != &*I) {
1006 NonCanonicalGlobals.push_back(I);
1007 continue;
1008 }
1009 }
1010 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001011
Reid Spencer5cbf9852007-01-30 20:08:39 +00001012 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001013 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001014 } else {
1015 // External variable reference. Try to use the dynamic loader to
1016 // get a pointer to it.
1017 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001018 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001019 addGlobalMapping(I, SymAddr);
1020 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001021 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001022 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001023 }
1024 }
1025 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001026
Chris Lattnerfe854032006-08-16 01:24:12 +00001027 // If there are multiple modules, map the non-canonical globals to their
1028 // canonical location.
1029 if (!NonCanonicalGlobals.empty()) {
1030 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1031 const GlobalValue *GV = NonCanonicalGlobals[i];
1032 const GlobalValue *CGV =
1033 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1034 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1035 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001036 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001037 }
1038 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001039
1040 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001041 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001042 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1043 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001044 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001045 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001046 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001047 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1048 if (GVEntry != &*I) // Not the canonical variable.
1049 continue;
1050 }
1051 EmitGlobalVariable(I);
1052 }
1053 }
1054 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001055}
1056
1057// EmitGlobalVariable - This method emits the specified global variable to the
1058// address specified in GlobalAddresses, or allocates new memory if it's not
1059// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001060void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001061 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001062
Chris Lattner24b0a182003-12-20 02:45:37 +00001063 if (GA == 0) {
1064 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001065 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001066 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001067 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001068
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001069 // Don't initialize if it's thread local, let the client do it.
1070 if (!GV->isThreadLocal())
1071 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001072
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001073 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001074 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001075 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001076 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001077}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001078
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001079ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1080 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001081}
1082
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001083sys::Mutex *
1084ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001085 return &EES->EE.lock;
1086}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001087
1088void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1089 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001090 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1091 EES->GlobalAddressReverseMap.erase(OldVal);
1092}
1093
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001094void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1095 const GlobalValue *,
1096 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001097 assert(false && "The ExecutionEngine doesn't know how to handle a"
1098 " RAUW on a value it has a global mapping for.");
1099}