blob: 4995fa99cda38d894ddb9b012c83e5887e0780f9 [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"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000032#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000033#include <cmath>
34#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000035using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036
Chris Lattner36343732006-12-19 22:43:32 +000037STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039
Jeffrey Yasskin46882612010-02-05 16:19:36 +000040ExecutionEngine *(*ExecutionEngine::JITCtor)(
41 Module *M,
42 std::string *ErrorStr,
43 JITMemoryManager *JMM,
44 CodeGenOpt::Level OptLevel,
45 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000046 TargetMachine *TM) = 0;
Daniel Dunbar6d135972010-11-17 16:06:37 +000047ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
48 Module *M,
49 std::string *ErrorStr,
50 JITMemoryManager *JMM,
51 CodeGenOpt::Level OptLevel,
52 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000053 TargetMachine *TM) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000054ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000055 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000056
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000057ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000058 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000059 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000060 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000061 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000062 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000063 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000064 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000065 Modules.push_back(M);
66 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000067}
68
Brian Gaeke8e539482003-09-04 22:57:27 +000069ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000070 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000071 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
72 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000073}
74
Duncan Sandsb35fd442010-10-21 08:57:29 +000075void ExecutionEngine::DeregisterAllTables() {
76 if (ExceptionTableDeregister) {
Eric Christopher515c67e2011-03-04 23:37:39 +000077 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79 for (; it != ite; ++it)
80 ExceptionTableDeregister(it->second);
Duncan Sandsb35fd442010-10-21 08:57:29 +000081 AllExceptionTables.clear();
82 }
83}
84
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000085namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000086/// \brief Helper class which uses a value handler to automatically deletes the
87/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000088class GVMemoryBlock : public CallbackVH {
89 GVMemoryBlock(const GlobalVariable *GV)
90 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
91
92public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000093 /// \brief Returns the address the GlobalVariable should be written into. The
94 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000095 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000096 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000097 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98 void *RawMemory = ::operator new(
99 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
100 TD.getPreferredAlignment(GV))
101 + GVSize);
102 new(RawMemory) GVMemoryBlock(GV);
103 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
104 }
105
106 virtual void deleted() {
107 // We allocated with operator new and with some extra memory hanging off the
108 // end, so don't just delete this. I'm not sure if this is actually
109 // required.
110 this->~GVMemoryBlock();
111 ::operator delete(this);
112 }
113};
114} // anonymous namespace
115
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000116char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000117 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000118}
119
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000120bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000121 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000122 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000123 Module *Found = *I;
124 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000125 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000126 clearGlobalMappingsFromModule(M);
127 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000128 }
129 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000130 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000131}
132
Chris Lattnerfe854032006-08-16 01:24:12 +0000133Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000135 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000136 return F;
137 }
138 return 0;
139}
140
141
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000142void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000144 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000145 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000146
147 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
148 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000149 if (I == GlobalAddressMap.end())
150 OldVal = 0;
151 else {
152 OldVal = I->second;
153 GlobalAddressMap.erase(I);
154 }
155
156 GlobalAddressReverseMap.erase(OldVal);
157 return OldVal;
158}
159
Chris Lattnere7fd5532006-05-08 22:00:52 +0000160void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000162
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000164 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
167 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000168
169 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000171 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000172 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000173 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
174 V = GV;
175 }
176}
177
Chris Lattnere7fd5532006-05-08 22:00:52 +0000178void ExecutionEngine::clearAllGlobalMappings() {
179 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000180
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000181 EEState.getGlobalAddressMap(locked).clear();
182 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000183}
184
Nate Begemanf049e072008-05-21 16:34:48 +0000185void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000187
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000189 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000190 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
191 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000192 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000193}
194
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000195void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000196 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000197
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000198 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000199 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000200
Chris Lattnere7fd5532006-05-08 22:00:52 +0000201 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000202 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000203 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000204
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000205 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000206 void *OldVal = CurVal;
207
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000208 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000210 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000211
212 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000213 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000214 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000215 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000216 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
217 V = GV;
218 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000219 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220}
221
Chris Lattnere7fd5532006-05-08 22:00:52 +0000222void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000224
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000225 ExecutionEngineState::GlobalAddressMapTy::iterator I =
226 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000227 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000228}
229
Chris Lattner55d86482003-12-31 20:21:04 +0000230const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000231 MutexGuard locked(lock);
232
Chris Lattner55d86482003-12-31 20:21:04 +0000233 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000234 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000235 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000236 I = EEState.getGlobalAddressMap(locked).begin(),
237 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000238 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000240 }
241
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000242 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000243 EEState.getGlobalAddressReverseMap(locked).find(Addr);
244 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000245}
Chris Lattner87f03102003-12-26 06:50:30 +0000246
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000247namespace {
248class ArgvArray {
249 char *Array;
250 std::vector<char*> Values;
251public:
252 ArgvArray() : Array(NULL) {}
253 ~ArgvArray() { clear(); }
254 void clear() {
255 delete[] Array;
256 Array = NULL;
257 for (size_t I = 0, E = Values.size(); I != E; ++I) {
258 delete[] Values[I];
259 }
260 Values.clear();
261 }
262 /// Turn a vector of strings into a nice argv style array of pointers to null
263 /// terminated strings.
264 void *reset(LLVMContext &C, ExecutionEngine *EE,
265 const std::vector<std::string> &InputArgv);
266};
267} // anonymous namespace
268void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv) {
270 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000271 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000272 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000273
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000275 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000276
277 for (unsigned i = 0; i != InputArgv.size(); ++i) {
278 unsigned Size = InputArgv[i].size()+1;
279 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000280 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000281 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000282
Chris Lattner87f03102003-12-26 06:50:30 +0000283 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
284 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000285
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000286 // Endian safe: Array[i] = (PointerTy)Dest;
287 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000288 SBytePtr);
289 }
290
291 // Null terminate it
292 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000293 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000294 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000295 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000296}
297
Chris Lattnerfbd39762009-09-23 01:46:04 +0000298void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
299 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000300 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000301 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000302
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000303 // If this global has internal linkage, or if it has a use, then it must be
304 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
305 // this is the case, don't execute any of the global ctors, __main will do
306 // it.
307 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
308
Nick Lewyckya040d472011-04-06 20:38:44 +0000309 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000310 // the init priority, which we ignore.
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000311 if (isa<ConstantAggregateZero>(GV->getInitializer()))
312 return;
Nick Lewycky2c44a802011-04-08 07:30:21 +0000313 ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000315 if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
316 continue;
Nick Lewycky2c44a802011-04-08 07:30:21 +0000317 ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000318
319 Constant *FP = CS->getOperand(1);
320 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000321 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000322
323 // Strip off constant expression casts.
324 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325 if (CE->isCast())
326 FP = CE->getOperand(0);
327
328 // Execute the ctor/dtor function!
329 if (Function *F = dyn_cast<Function>(FP))
330 runFunction(F, std::vector<GenericValue>());
331
332 // FIXME: It is marginally lame that we just do nothing here if we see an
333 // entry we don't recognize. It might not be unreasonable for the verifier
334 // to not even allow this and just assert here.
335 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000336}
337
Evan Cheng18314dc2008-09-30 15:51:21 +0000338void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
339 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000340 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
341 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000342}
343
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000344#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000345/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
346static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
347 unsigned PtrSize = EE->getTargetData()->getPointerSize();
348 for (unsigned i = 0; i < PtrSize; ++i)
349 if (*(i + (uint8_t*)Loc))
350 return false;
351 return true;
352}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000353#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000354
Chris Lattner87f03102003-12-26 06:50:30 +0000355int ExecutionEngine::runFunctionAsMain(Function *Fn,
356 const std::vector<std::string> &argv,
357 const char * const * envp) {
358 std::vector<GenericValue> GVArgs;
359 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000360 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000361
362 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000363 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000364 FunctionType *FTy = Fn->getFunctionType();
365 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000366
367 // Check the argument types.
368 if (NumArgs > 3)
369 report_fatal_error("Invalid number of arguments of main() supplied");
370 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
371 report_fatal_error("Invalid type for third argument of main() supplied");
372 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
373 report_fatal_error("Invalid type for second argument of main() supplied");
374 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
375 report_fatal_error("Invalid type for first argument of main() supplied");
376 if (!FTy->getReturnType()->isIntegerTy() &&
377 !FTy->getReturnType()->isVoidTy())
378 report_fatal_error("Invalid return type of main() supplied");
379
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000380 ArgvArray CArgv;
381 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000382 if (NumArgs) {
383 GVArgs.push_back(GVArgc); // Arg #0 = argc.
384 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000385 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000386 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000387 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000388 "argv[0] was null after CreateArgv");
389 if (NumArgs > 2) {
390 std::vector<std::string> EnvVars;
391 for (unsigned i = 0; envp[i]; ++i)
392 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000393 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000394 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000395 }
396 }
397 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000398
Reid Spencer8fb0f192007-03-06 03:04:04 +0000399 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000400}
401
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000402ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000403 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000404 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000405 CodeGenOpt::Level OptLevel,
406 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000407 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000408 .setEngineKind(ForceInterpreter
409 ? EngineKind::Interpreter
410 : EngineKind::JIT)
411 .setErrorStr(ErrorStr)
412 .setOptLevel(OptLevel)
413 .setAllocateGVsWithCode(GVsWithCode)
414 .create();
415}
Brian Gaeke82d82772003-09-03 20:34:19 +0000416
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000417/// createJIT - This is the factory method for creating a JIT for the current
418/// machine, it does not fall back to the interpreter. This takes ownership
419/// of the module.
420ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421 std::string *ErrorStr,
422 JITMemoryManager *JMM,
423 CodeGenOpt::Level OptLevel,
424 bool GVsWithCode,
Evan Cheng43966132011-07-19 06:37:02 +0000425 Reloc::Model RM,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000426 CodeModel::Model CMM) {
427 if (ExecutionEngine::JITCtor == 0) {
428 if (ErrorStr)
429 *ErrorStr = "JIT has not been linked in.";
430 return 0;
431 }
432
433 // Use the defaults for extra parameters. Users can use EngineBuilder to
434 // set them.
435 StringRef MArch = "";
436 StringRef MCPU = "";
437 SmallVector<std::string, 1> MAttrs;
438
439 TargetMachine *TM =
Evan Cheng43966132011-07-19 06:37:02 +0000440 EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, RM, ErrorStr);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000441 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
442 TM->setCodeModel(CMM);
443
444 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, GVsWithCode, TM);
445}
446
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000447ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000448 // Make sure we can resolve symbols in the program as well. The zero arg
449 // to the function tells DynamicLibrary to load the program, not a library.
450 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
451 return 0;
452
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000453 // If the user specified a memory manager but didn't specify which engine to
454 // create, we assume they only want the JIT, and we fail if they only want
455 // the interpreter.
456 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000457 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000458 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000459 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000460 if (ErrorStr)
461 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000462 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000463 }
464 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000465
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000466 // Unless the interpreter was explicitly selected or the JIT is not linked,
467 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000468 if (WhichEngine & EngineKind::JIT) {
Evan Cheng43966132011-07-19 06:37:02 +0000469 if (TargetMachine *TM = EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs,
470 RelocModel, ErrorStr)) {
Dylan Noblesmithc5b28582011-05-13 21:51:29 +0000471 TM->setCodeModel(CMModel);
472
473 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
474 ExecutionEngine *EE =
475 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
476 AllocateGVsWithCode, TM);
477 if (EE) return EE;
478 } else if (ExecutionEngine::JITCtor) {
479 ExecutionEngine *EE =
480 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
481 AllocateGVsWithCode, TM);
482 if (EE) return EE;
483 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000484 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000485 }
486
487 // If we can't make a JIT and we didn't request one specifically, try making
488 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000489 if (WhichEngine & EngineKind::Interpreter) {
490 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000491 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000492 if (ErrorStr)
493 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000494 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000495 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000496
497 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
498 if (ErrorStr)
499 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000500 }
501
Chris Lattnerfbd39762009-09-23 01:46:04 +0000502 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000503}
504
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000505void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000506 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000507 return getPointerToFunction(F);
508
Reid Spenceree448632005-07-12 15:51:55 +0000509 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000510 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
511 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000512
513 // Global variable might have been added since interpreter started.
514 if (GlobalVariable *GVar =
515 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
516 EmitGlobalVariable(GVar);
517 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000518 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000519
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000520 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000521}
522
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000523/// \brief Converts a Constant* into a GenericValue, including handling of
524/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000525GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000526 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000527 if (isa<UndefValue>(C)) {
528 GenericValue Result;
529 switch (C->getType()->getTypeID()) {
530 case Type::IntegerTyID:
531 case Type::X86_FP80TyID:
532 case Type::FP128TyID:
533 case Type::PPC_FP128TyID:
534 // Although the value is undefined, we still have to construct an APInt
535 // with the correct bit width.
536 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
537 break;
538 default:
539 break;
540 }
541 return Result;
542 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000543
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000544 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000545 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000546 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000547 switch (CE->getOpcode()) {
548 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000549 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000550 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000551 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000552 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000553 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000554
Reid Spencer8fb0f192007-03-06 03:04:04 +0000555 char* tmp = (char*) Result.PointerVal;
556 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000557 return Result;
558 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000559 case Instruction::Trunc: {
560 GenericValue GV = getConstantValue(Op0);
561 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
562 GV.IntVal = GV.IntVal.trunc(BitWidth);
563 return GV;
564 }
565 case Instruction::ZExt: {
566 GenericValue GV = getConstantValue(Op0);
567 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
568 GV.IntVal = GV.IntVal.zext(BitWidth);
569 return GV;
570 }
571 case Instruction::SExt: {
572 GenericValue GV = getConstantValue(Op0);
573 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
574 GV.IntVal = GV.IntVal.sext(BitWidth);
575 return GV;
576 }
577 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000578 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000579 GenericValue GV = getConstantValue(Op0);
580 GV.FloatVal = float(GV.DoubleVal);
581 return GV;
582 }
583 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000584 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000585 GenericValue GV = getConstantValue(Op0);
586 GV.DoubleVal = double(GV.FloatVal);
587 return GV;
588 }
589 case Instruction::UIToFP: {
590 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000591 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000592 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000593 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000594 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000595 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000596 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000597 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000598 false,
599 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000600 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000601 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000602 return GV;
603 }
604 case Instruction::SIToFP: {
605 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000606 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000607 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000608 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000610 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000611 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000612 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000613 true,
614 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000615 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000616 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000617 return GV;
618 }
619 case Instruction::FPToUI: // double->APInt conversion handles sign
620 case Instruction::FPToSI: {
621 GenericValue GV = getConstantValue(Op0);
622 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000623 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000624 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000625 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000627 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000628 APFloat apf = APFloat(GV.IntVal);
629 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000630 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000631 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000632 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000633 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000634 GV.IntVal = v; // endian?
635 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 return GV;
637 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000638 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000639 GenericValue GV = getConstantValue(Op0);
640 uint32_t PtrWidth = TD->getPointerSizeInBits();
641 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
642 return GV;
643 }
644 case Instruction::IntToPtr: {
645 GenericValue GV = getConstantValue(Op0);
646 uint32_t PtrWidth = TD->getPointerSizeInBits();
647 if (PtrWidth != GV.IntVal.getBitWidth())
648 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
649 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
650 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000651 return GV;
652 }
653 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000654 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000655 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000657 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000658 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000659 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000660 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000661 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000662 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 GV.DoubleVal = GV.IntVal.bitsToDouble();
664 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000665 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000666 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000667 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000668 break;
669 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000670 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000671 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000672 break;
673 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000674 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000675 break; // getConstantValue(Op0) above already converted it
676 }
677 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000678 }
Chris Lattner9a231222003-05-14 17:51:49 +0000679 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000680 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000681 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000682 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000684 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000685 case Instruction::UDiv:
686 case Instruction::SDiv:
687 case Instruction::URem:
688 case Instruction::SRem:
689 case Instruction::And:
690 case Instruction::Or:
691 case Instruction::Xor: {
692 GenericValue LHS = getConstantValue(Op0);
693 GenericValue RHS = getConstantValue(CE->getOperand(1));
694 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000695 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000696 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000697 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000698 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000699 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000700 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
701 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
702 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
703 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
704 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
705 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
706 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
707 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
708 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
709 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
710 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000711 break;
712 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000713 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000714 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000715 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000716 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000717 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000718 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000719 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000721 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000722 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000723 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000724 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000725 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000726 break;
727 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000728 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000729 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000730 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000731 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000732 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000733 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000734 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000735 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000736 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000737 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000738 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000739 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000741 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000742 case Type::X86_FP80TyID:
743 case Type::PPC_FP128TyID:
744 case Type::FP128TyID: {
745 APFloat apfLHS = APFloat(LHS.IntVal);
746 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000747 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000748 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000749 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000750 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000751 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000752 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000753 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000754 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000755 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000756 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000757 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000758 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000759 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000760 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000761 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000762 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000763 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000764 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000765 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000766 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000767 break;
768 }
769 }
770 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000771 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000772 return GV;
773 }
Chris Lattner9a231222003-05-14 17:51:49 +0000774 default:
775 break;
776 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000777
778 SmallString<256> Msg;
779 raw_svector_ostream OS(Msg);
780 OS << "ConstantExpr not handled: " << *CE;
781 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000782 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000783
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000784 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000785 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000786 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000787 case Type::FloatTyID:
788 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000789 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000790 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000791 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000792 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000793 case Type::X86_FP80TyID:
794 case Type::FP128TyID:
795 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000796 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000797 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 case Type::IntegerTyID:
799 Result.IntVal = cast<ConstantInt>(C)->getValue();
800 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000801 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000802 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000803 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000804 else if (const Function *F = dyn_cast<Function>(C))
805 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000806 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000807 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000808 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
809 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
810 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000811 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000812 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000813 break;
814 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000815 SmallString<256> Msg;
816 raw_svector_ostream OS(Msg);
817 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
818 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000819 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000820
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000821 return Result;
822}
823
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000824/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
825/// with the integer held in IntVal.
826static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
827 unsigned StoreBytes) {
828 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
829 uint8_t *Src = (uint8_t *)IntVal.getRawData();
830
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000831 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000832 // Little-endian host - the source is ordered from LSB to MSB. Order the
833 // destination from LSB to MSB: Do a straight copy.
834 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000835 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000836 // Big-endian host - the source is an array of 64 bit words ordered from
837 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
838 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
839 while (StoreBytes > sizeof(uint64_t)) {
840 StoreBytes -= sizeof(uint64_t);
841 // May not be aligned so use memcpy.
842 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
843 Src += sizeof(uint64_t);
844 }
845
846 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
847 }
848}
849
Evan Cheng89687e32008-11-04 06:10:31 +0000850void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000851 GenericValue *Ptr, Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000852 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
853
Reid Spencer8fb0f192007-03-06 03:04:04 +0000854 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000855 case Type::IntegerTyID:
856 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000857 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000858 case Type::FloatTyID:
859 *((float*)Ptr) = Val.FloatVal;
860 break;
861 case Type::DoubleTyID:
862 *((double*)Ptr) = Val.DoubleVal;
863 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000864 case Type::X86_FP80TyID:
865 memcpy(Ptr, Val.IntVal.getRawData(), 10);
866 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000867 case Type::PointerTyID:
868 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
869 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +0000870 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000871
Reid Spencer8fb0f192007-03-06 03:04:04 +0000872 *((PointerTy*)Ptr) = Val.PointerVal;
873 break;
874 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000875 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000876 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000877
Chris Lattnerb67c9582009-01-22 19:53:00 +0000878 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000879 // Host and target are different endian - reverse the stored bytes.
880 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
881}
882
883/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
884/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
885static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
886 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
887 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
888
Chris Lattnerb67c9582009-01-22 19:53:00 +0000889 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000890 // Little-endian host - the destination must be ordered from LSB to MSB.
891 // The source is ordered from LSB to MSB: Do a straight copy.
892 memcpy(Dst, Src, LoadBytes);
893 else {
894 // Big-endian - the destination is an array of 64 bit words ordered from
895 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
896 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
897 // a word.
898 while (LoadBytes > sizeof(uint64_t)) {
899 LoadBytes -= sizeof(uint64_t);
900 // May not be aligned so use memcpy.
901 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
902 Dst += sizeof(uint64_t);
903 }
904
905 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
906 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000907}
908
Misha Brukman4afac182003-10-10 17:45:12 +0000909/// FIXME: document
910///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000911void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000912 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000913 Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000914 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000915
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000916 switch (Ty->getTypeID()) {
917 case Type::IntegerTyID:
918 // An APInt with all words initially zero.
919 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
920 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
921 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000922 case Type::FloatTyID:
923 Result.FloatVal = *((float*)Ptr);
924 break;
925 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000926 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000927 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000928 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000929 Result.PointerVal = *((PointerTy*)Ptr);
930 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000931 case Type::X86_FP80TyID: {
932 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000933 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000934 uint64_t y[2];
935 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +0000936 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000937 break;
938 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000939 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000940 SmallString<256> Msg;
941 raw_svector_ostream OS(Msg);
942 OS << "Cannot load value of type " << *Ty << "!";
943 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000944 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000945}
946
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000947void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000948 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000949 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000950 if (isa<UndefValue>(Init)) {
951 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000952 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000953 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000954 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000955 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
956 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
957 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000958 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000959 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000960 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000961 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
962 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000963 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000964 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
965 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
966 return;
967 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
968 const StructLayout *SL =
969 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
970 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
971 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
972 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000973 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000974 GenericValue Val = getConstantValue(Init);
975 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
976 return;
977 }
978
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000979 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000980 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000981}
982
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000983/// EmitGlobals - Emit all of the global variables to memory, storing their
984/// addresses into GlobalAddress. This must make sure to copy the contents of
985/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000986void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000987 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000988 // to hold them. If there is more than one module, do a prepass over globals
989 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000990 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +0000991 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000992
Chris Lattnerfe854032006-08-16 01:24:12 +0000993 if (Modules.size() != 1) {
994 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000995 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000996 for (Module::const_global_iterator I = M.global_begin(),
997 E = M.global_end(); I != E; ++I) {
998 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000999 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +00001000 GV->hasAppendingLinkage() || !GV->hasName())
1001 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001002
1003 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001004 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1005
1006 // If this is the first time we've seen this global, it is the canonical
1007 // version.
1008 if (!GVEntry) {
1009 GVEntry = GV;
1010 continue;
1011 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001012
Chris Lattnerfe854032006-08-16 01:24:12 +00001013 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001014 if (GVEntry->hasExternalLinkage() ||
1015 GVEntry->hasDLLImportLinkage() ||
1016 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001017 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001018
Chris Lattnerfe854032006-08-16 01:24:12 +00001019 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001020 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001021 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001022 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001023 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001024 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001025 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001026
Chris Lattnerfe854032006-08-16 01:24:12 +00001027 std::vector<const GlobalValue*> NonCanonicalGlobals;
1028 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001029 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001030 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1031 I != E; ++I) {
1032 // In the multi-module case, see what this global maps to.
1033 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001034 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001035 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1036 // If something else is the canonical global, ignore this one.
1037 if (GVEntry != &*I) {
1038 NonCanonicalGlobals.push_back(I);
1039 continue;
1040 }
1041 }
1042 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001043
Reid Spencer5cbf9852007-01-30 20:08:39 +00001044 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001045 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001046 } else {
1047 // External variable reference. Try to use the dynamic loader to
1048 // get a pointer to it.
1049 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001050 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001051 addGlobalMapping(I, SymAddr);
1052 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001053 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001054 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001055 }
1056 }
1057 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001058
Chris Lattnerfe854032006-08-16 01:24:12 +00001059 // If there are multiple modules, map the non-canonical globals to their
1060 // canonical location.
1061 if (!NonCanonicalGlobals.empty()) {
1062 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1063 const GlobalValue *GV = NonCanonicalGlobals[i];
1064 const GlobalValue *CGV =
1065 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1066 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1067 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001068 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001069 }
1070 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001071
1072 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001073 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001074 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1075 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001076 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001077 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001078 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001079 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1080 if (GVEntry != &*I) // Not the canonical variable.
1081 continue;
1082 }
1083 EmitGlobalVariable(I);
1084 }
1085 }
1086 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001087}
1088
1089// EmitGlobalVariable - This method emits the specified global variable to the
1090// address specified in GlobalAddresses, or allocates new memory if it's not
1091// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001092void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001093 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001094
Chris Lattner24b0a182003-12-20 02:45:37 +00001095 if (GA == 0) {
1096 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001097 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001098 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001099 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001100
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001101 // Don't initialize if it's thread local, let the client do it.
1102 if (!GV->isThreadLocal())
1103 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001104
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001105 Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001106 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001107 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001108 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001109}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001110
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001111ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1112 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001113}
1114
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001115sys::Mutex *
1116ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001117 return &EES->EE.lock;
1118}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001119
1120void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1121 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001122 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1123 EES->GlobalAddressReverseMap.erase(OldVal);
1124}
1125
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001126void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1127 const GlobalValue *,
1128 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001129 assert(false && "The ExecutionEngine doesn't know how to handle a"
1130 " RAUW on a value it has a global mapping for.");
1131}