blob: 4678d0c1830881ab7c9fb2082968c3eab83990a1 [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"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000016#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Module.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/ModuleProvider.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000020#include "llvm/ADT/Statistic.h"
Duncan Sands8a43e9e2007-12-14 19:38:31 +000021#include "llvm/Config/alloca.h"
Misha Brukman19684162003-10-16 21:18:05 +000022#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000026#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000027#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000028#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000029#include <cmath>
30#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000031using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032
Chris Lattner36343732006-12-19 22:43:32 +000033STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner2fe4bb02006-03-22 06:07:50 +000036ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000038ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
39
Chris Lattner2fe4bb02006-03-22 06:07:50 +000040
Chris Lattnerd958a5a2007-10-22 02:50:12 +000041ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000042 LazyCompilationDisabled = false;
Evan Cheng446531e2008-09-24 16:25:55 +000043 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000044 SymbolSearchingDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000045 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000046 assert(P && "ModuleProvider is null?");
47}
48
Brian Gaeke8e539482003-09-04 22:57:27 +000049ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000050 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000051 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
52 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000053}
54
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000055char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
56 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000057 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000058 return new char[GVSize];
59}
60
Devang Patel73d0e212007-10-15 19:56:32 +000061/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
Nate Begeman60789e42009-01-23 19:27:28 +000062/// Relases the Module from the ModuleProvider, materializing it in the
63/// process, and returns the materialized Module.
Devang Patel73d0e212007-10-15 19:56:32 +000064Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
65 std::string *ErrInfo) {
66 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
67 E = Modules.end(); I != E; ++I) {
68 ModuleProvider *MP = *I;
69 if (MP == P) {
70 Modules.erase(I);
Nate Begemanf049e072008-05-21 16:34:48 +000071 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel73d0e212007-10-15 19:56:32 +000072 return MP->releaseModule(ErrInfo);
73 }
74 }
75 return NULL;
76}
77
Nate Begeman60789e42009-01-23 19:27:28 +000078/// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
79/// and deletes the ModuleProvider and owned Module. Avoids materializing
80/// the underlying module.
81void ExecutionEngine::deleteModuleProvider(ModuleProvider *P,
82 std::string *ErrInfo) {
83 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
84 E = Modules.end(); I != E; ++I) {
85 ModuleProvider *MP = *I;
86 if (MP == P) {
87 Modules.erase(I);
88 clearGlobalMappingsFromModule(MP->getModule());
89 delete MP;
90 return;
91 }
92 }
93}
94
Chris Lattnerfe854032006-08-16 01:24:12 +000095/// FindFunctionNamed - Search all of the active modules to find the one that
96/// defines FnName. This is very slow operation and shouldn't be used for
97/// general code.
98Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
99 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +0000100 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000101 return F;
102 }
103 return 0;
104}
105
106
Chris Lattnere7fd5532006-05-08 22:00:52 +0000107/// addGlobalMapping - Tell the execution engine that the specified global is
108/// at the specified location. This is used internally as functions are JIT'd
109/// and as global variables are laid out in memory. It can and should also be
110/// used by clients of the EE that want to have an LLVM global overlay
111/// existing data in memory.
112void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
113 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000114
Evan Cheng366cf292008-11-07 22:30:29 +0000115 DOUT << "JIT: Map \'" << GV->getNameStart() << "\' to [" << Addr << "]\n";
Chris Lattnere7fd5532006-05-08 22:00:52 +0000116 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
117 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
118 CurVal = Addr;
119
120 // If we are using the reverse mapping, add it too
121 if (!state.getGlobalAddressReverseMap(locked).empty()) {
122 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
123 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
124 V = GV;
125 }
126}
127
128/// clearAllGlobalMappings - Clear all global mappings and start over again
129/// use in dynamic compilation scenarios when you want to move globals
130void ExecutionEngine::clearAllGlobalMappings() {
131 MutexGuard locked(lock);
132
133 state.getGlobalAddressMap(locked).clear();
134 state.getGlobalAddressReverseMap(locked).clear();
135}
136
Nate Begemanf049e072008-05-21 16:34:48 +0000137/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
138/// particular module, because it has been removed from the JIT.
139void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
140 MutexGuard locked(lock);
141
142 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
143 state.getGlobalAddressMap(locked).erase(FI);
144 state.getGlobalAddressReverseMap(locked).erase(FI);
145 }
146 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
147 GI != GE; ++GI) {
148 state.getGlobalAddressMap(locked).erase(GI);
149 state.getGlobalAddressReverseMap(locked).erase(GI);
150 }
151}
152
Chris Lattnere7fd5532006-05-08 22:00:52 +0000153/// updateGlobalMapping - Replace an existing mapping for GV with a new
154/// address. This updates both maps as required. If "Addr" is null, the
155/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000156void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000157 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000158
159 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
160
Chris Lattnere7fd5532006-05-08 22:00:52 +0000161 // Deleting from the mapping?
162 if (Addr == 0) {
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000163 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
164 void *OldVal;
165 if (I == Map.end())
166 OldVal = 0;
167 else {
168 OldVal = I->second;
169 Map.erase(I);
170 }
171
Chris Lattnere7fd5532006-05-08 22:00:52 +0000172 if (!state.getGlobalAddressReverseMap(locked).empty())
173 state.getGlobalAddressReverseMap(locked).erase(Addr);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000174 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000175 }
176
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000177 void *&CurVal = Map[GV];
178 void *OldVal = CurVal;
179
Chris Lattnere7fd5532006-05-08 22:00:52 +0000180 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
181 state.getGlobalAddressReverseMap(locked).erase(CurVal);
182 CurVal = Addr;
183
184 // If we are using the reverse mapping, add it too
185 if (!state.getGlobalAddressReverseMap(locked).empty()) {
186 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188 V = GV;
189 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000190 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000191}
192
193/// getPointerToGlobalIfAvailable - This returns the address of the specified
194/// global value if it is has already been codegen'd, otherwise it returns null.
195///
196void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
198
199 std::map<const GlobalValue*, void*>::iterator I =
200 state.getGlobalAddressMap(locked).find(GV);
201 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
202}
203
Chris Lattner55d86482003-12-31 20:21:04 +0000204/// getGlobalValueAtAddress - Return the LLVM global value object that starts
205/// at the specified address.
206///
207const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000208 MutexGuard locked(lock);
209
Chris Lattner55d86482003-12-31 20:21:04 +0000210 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000211 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000212 for (std::map<const GlobalValue*, void *>::iterator
213 I = state.getGlobalAddressMap(locked).begin(),
214 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
215 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
216 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000217 }
218
219 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000220 state.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000222}
Chris Lattner87f03102003-12-26 06:50:30 +0000223
224// CreateArgv - Turn a vector of strings into a nice argv style array of
225// pointers to null terminated strings.
226//
227static void *CreateArgv(ExecutionEngine *EE,
228 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000229 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000230 char *Result = new char[(InputArgv.size()+1)*PtrSize];
231
Evan Chengeb5d95a2008-11-06 17:46:04 +0000232 DOUT << "JIT: ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000233 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000234
235 for (unsigned i = 0; i != InputArgv.size(); ++i) {
236 unsigned Size = InputArgv[i].size()+1;
237 char *Dest = new char[Size];
Evan Chengeb5d95a2008-11-06 17:46:04 +0000238 DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000239
Chris Lattner87f03102003-12-26 06:50:30 +0000240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
241 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000242
Chris Lattner87f03102003-12-26 06:50:30 +0000243 // Endian safe: Result[i] = (PointerTy)Dest;
244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245 SBytePtr);
246 }
247
248 // Null terminate it
249 EE->StoreValueToMemory(PTOGV(0),
250 (GenericValue*)(Result+InputArgv.size()*PtrSize),
251 SBytePtr);
252 return Result;
253}
254
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000255
256/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000257/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000258/// value of isDtors.
Evan Cheng18314dc2008-09-30 15:51:21 +0000259void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000260 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000261
Chris Lattnerfe854032006-08-16 01:24:12 +0000262 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000263
Evan Cheng18314dc2008-09-30 15:51:21 +0000264 GlobalVariable *GV = module->getNamedGlobal(Name);
265
266 // If this global has internal linkage, or if it has a use, then it must be
267 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
268 // this is the case, don't execute any of the global ctors, __main will do
269 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000270 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000271
272 // Should be an array of '{ int, void ()* }' structs. The first value is
273 // the init priority, which we ignore.
274 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
275 if (!InitList) return;
276 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
277 if (ConstantStruct *CS =
278 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
279 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
280
281 Constant *FP = CS->getOperand(1);
282 if (FP->isNullValue())
283 break; // Found a null terminator, exit.
284
285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
286 if (CE->isCast())
287 FP = CE->getOperand(0);
288 if (Function *F = dyn_cast<Function>(FP)) {
289 // Execute the ctor/dtor function!
290 runFunction(F, std::vector<GenericValue>());
291 }
292 }
293}
294
295/// runStaticConstructorsDestructors - This method is used to execute all of
296/// the static constructors or destructors for a program, depending on the
297/// value of isDtors.
298void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
299 // Execute global ctors/dtors for each module in the program.
300 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
301 runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000302}
303
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000304#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000305/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
306static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
307 unsigned PtrSize = EE->getTargetData()->getPointerSize();
308 for (unsigned i = 0; i < PtrSize; ++i)
309 if (*(i + (uint8_t*)Loc))
310 return false;
311 return true;
312}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000313#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000314
Chris Lattner87f03102003-12-26 06:50:30 +0000315/// runFunctionAsMain - This is a helper function which wraps runFunction to
316/// handle the common task of starting up main with the specified argc, argv,
317/// and envp parameters.
318int ExecutionEngine::runFunctionAsMain(Function *Fn,
319 const std::vector<std::string> &argv,
320 const char * const * envp) {
321 std::vector<GenericValue> GVArgs;
322 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000323 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000324
325 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000326 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000327 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000328 const Type* PPInt8Ty =
329 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000330 switch (NumArgs) {
331 case 3:
332 if (FTy->getParamType(2) != PPInt8Ty) {
333 cerr << "Invalid type for third argument of main() supplied\n";
334 abort();
335 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000336 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000337 case 2:
338 if (FTy->getParamType(1) != PPInt8Ty) {
339 cerr << "Invalid type for second argument of main() supplied\n";
340 abort();
341 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000342 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000343 case 1:
344 if (FTy->getParamType(0) != Type::Int32Ty) {
345 cerr << "Invalid type for first argument of main() supplied\n";
346 abort();
347 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000348 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000349 case 0:
Chris Lattner45f36832009-02-04 17:48:18 +0000350 if (!isa<IntegerType>(FTy->getReturnType()) &&
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000351 FTy->getReturnType() != Type::VoidTy) {
352 cerr << "Invalid return type of main() supplied\n";
353 abort();
354 }
355 break;
356 default:
357 cerr << "Invalid number of arguments of main() supplied\n";
358 abort();
359 }
360
Chris Lattnerf24d0992004-08-16 01:05:35 +0000361 if (NumArgs) {
362 GVArgs.push_back(GVArgc); // Arg #0 = argc.
363 if (NumArgs > 1) {
364 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000365 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000366 "argv[0] was null after CreateArgv");
367 if (NumArgs > 2) {
368 std::vector<std::string> EnvVars;
369 for (unsigned i = 0; envp[i]; ++i)
370 EnvVars.push_back(envp[i]);
371 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
372 }
373 }
374 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000375 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000376}
377
Misha Brukman19684162003-10-16 21:18:05 +0000378/// If possible, create a JIT, unless the caller specifically requests an
379/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000380/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000381///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000382ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000383 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000384 std::string *ErrorStr,
385 bool Fast) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000386 ExecutionEngine *EE = 0;
387
Nick Lewycky6456d862008-03-08 02:49:45 +0000388 // Make sure we can resolve symbols in the program as well. The zero arg
389 // to the function tells DynamicLibrary to load the program, not a library.
390 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
391 return 0;
392
Chris Lattner73011782003-12-28 09:44:37 +0000393 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000394 if (!ForceInterpreter && JITCtor)
Evan Cheng502f20b2008-08-08 08:11:34 +0000395 EE = JITCtor(MP, ErrorStr, Fast);
Brian Gaeke82d82772003-09-03 20:34:19 +0000396
397 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000398 if (EE == 0 && InterpCtor)
Evan Cheng502f20b2008-08-08 08:11:34 +0000399 EE = InterpCtor(MP, ErrorStr, Fast);
Chris Lattner73011782003-12-28 09:44:37 +0000400
Brian Gaeke82d82772003-09-03 20:34:19 +0000401 return EE;
402}
403
Chris Lattner8b5295b2007-10-21 22:57:11 +0000404ExecutionEngine *ExecutionEngine::create(Module *M) {
405 return create(new ExistingModuleProvider(M));
406}
407
Misha Brukman4afac182003-10-10 17:45:12 +0000408/// getPointerToGlobal - This returns the address of the specified global
409/// value. This may involve code generation if it's a function.
410///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000411void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000412 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000413 return getPointerToFunction(F);
414
Reid Spenceree448632005-07-12 15:51:55 +0000415 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000416 void *p = state.getGlobalAddressMap(locked)[GV];
417 if (p)
418 return p;
419
420 // Global variable might have been added since interpreter started.
421 if (GlobalVariable *GVar =
422 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
423 EmitGlobalVariable(GVar);
424 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000425 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000426 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000427}
428
Reid Spencer3da59db2006-11-27 01:05:10 +0000429/// This function converts a Constant* into a GenericValue. The interesting
430/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000431/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000432GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000433 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000434 if (isa<UndefValue>(C))
435 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000436
Reid Spencer3da59db2006-11-27 01:05:10 +0000437 // If the value is a ConstantExpr
438 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000439 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000440 switch (CE->getOpcode()) {
441 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000442 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000443 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000444 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000445 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000446 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000447
Reid Spencer8fb0f192007-03-06 03:04:04 +0000448 char* tmp = (char*) Result.PointerVal;
449 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000450 return Result;
451 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000452 case Instruction::Trunc: {
453 GenericValue GV = getConstantValue(Op0);
454 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
455 GV.IntVal = GV.IntVal.trunc(BitWidth);
456 return GV;
457 }
458 case Instruction::ZExt: {
459 GenericValue GV = getConstantValue(Op0);
460 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
461 GV.IntVal = GV.IntVal.zext(BitWidth);
462 return GV;
463 }
464 case Instruction::SExt: {
465 GenericValue GV = getConstantValue(Op0);
466 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
467 GV.IntVal = GV.IntVal.sext(BitWidth);
468 return GV;
469 }
470 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000471 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000472 GenericValue GV = getConstantValue(Op0);
473 GV.FloatVal = float(GV.DoubleVal);
474 return GV;
475 }
476 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000477 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000478 GenericValue GV = getConstantValue(Op0);
479 GV.DoubleVal = double(GV.FloatVal);
480 return GV;
481 }
482 case Instruction::UIToFP: {
483 GenericValue GV = getConstantValue(Op0);
484 if (CE->getType() == Type::FloatTy)
485 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000486 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000487 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000488 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000489 const uint64_t zero[] = {0, 0};
490 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000491 (void)apf.convertFromAPInt(GV.IntVal,
492 false,
493 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000494 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000495 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000496 return GV;
497 }
498 case Instruction::SIToFP: {
499 GenericValue GV = getConstantValue(Op0);
500 if (CE->getType() == Type::FloatTy)
501 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000502 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000503 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000504 else if (CE->getType() == Type::X86_FP80Ty) {
505 const uint64_t zero[] = { 0, 0};
506 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000507 (void)apf.convertFromAPInt(GV.IntVal,
508 true,
509 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000510 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000511 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000512 return GV;
513 }
514 case Instruction::FPToUI: // double->APInt conversion handles sign
515 case Instruction::FPToSI: {
516 GenericValue GV = getConstantValue(Op0);
517 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
518 if (Op0->getType() == Type::FloatTy)
519 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000520 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000521 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000522 else if (Op0->getType() == Type::X86_FP80Ty) {
523 APFloat apf = APFloat(GV.IntVal);
524 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000525 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000526 (void)apf.convertToInteger(&v, BitWidth,
527 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000528 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000529 GV.IntVal = v; // endian?
530 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000531 return GV;
532 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000533 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000534 GenericValue GV = getConstantValue(Op0);
535 uint32_t PtrWidth = TD->getPointerSizeInBits();
536 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
537 return GV;
538 }
539 case Instruction::IntToPtr: {
540 GenericValue GV = getConstantValue(Op0);
541 uint32_t PtrWidth = TD->getPointerSizeInBits();
542 if (PtrWidth != GV.IntVal.getBitWidth())
543 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
544 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
545 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000546 return GV;
547 }
548 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000549 GenericValue GV = getConstantValue(Op0);
550 const Type* DestTy = CE->getType();
551 switch (Op0->getType()->getTypeID()) {
552 default: assert(0 && "Invalid bitcast operand");
553 case Type::IntegerTyID:
554 assert(DestTy->isFloatingPoint() && "invalid bitcast");
555 if (DestTy == Type::FloatTy)
556 GV.FloatVal = GV.IntVal.bitsToFloat();
557 else if (DestTy == Type::DoubleTy)
558 GV.DoubleVal = GV.IntVal.bitsToDouble();
559 break;
560 case Type::FloatTyID:
561 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
562 GV.IntVal.floatToBits(GV.FloatVal);
563 break;
564 case Type::DoubleTyID:
565 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
566 GV.IntVal.doubleToBits(GV.DoubleVal);
567 break;
568 case Type::PointerTyID:
569 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
570 break; // getConstantValue(Op0) above already converted it
571 }
572 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000573 }
Chris Lattner9a231222003-05-14 17:51:49 +0000574 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000575 case Instruction::Sub:
576 case Instruction::Mul:
577 case Instruction::UDiv:
578 case Instruction::SDiv:
579 case Instruction::URem:
580 case Instruction::SRem:
581 case Instruction::And:
582 case Instruction::Or:
583 case Instruction::Xor: {
584 GenericValue LHS = getConstantValue(Op0);
585 GenericValue RHS = getConstantValue(CE->getOperand(1));
586 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000587 switch (CE->getOperand(0)->getType()->getTypeID()) {
588 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000589 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000590 switch (CE->getOpcode()) {
591 default: assert(0 && "Invalid integer opcode");
592 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
593 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
594 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
595 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
596 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
597 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
598 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
599 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
600 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
601 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
602 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000603 break;
604 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 switch (CE->getOpcode()) {
606 default: assert(0 && "Invalid float opcode"); abort();
607 case Instruction::Add:
608 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
609 case Instruction::Sub:
610 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
611 case Instruction::Mul:
612 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
613 case Instruction::FDiv:
614 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
615 case Instruction::FRem:
616 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
617 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000618 break;
619 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000620 switch (CE->getOpcode()) {
621 default: assert(0 && "Invalid double opcode"); abort();
622 case Instruction::Add:
623 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
624 case Instruction::Sub:
625 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
626 case Instruction::Mul:
627 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
628 case Instruction::FDiv:
629 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
630 case Instruction::FRem:
631 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
632 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000633 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000634 case Type::X86_FP80TyID:
635 case Type::PPC_FP128TyID:
636 case Type::FP128TyID: {
637 APFloat apfLHS = APFloat(LHS.IntVal);
638 switch (CE->getOpcode()) {
639 default: assert(0 && "Invalid long double opcode"); abort();
640 case Instruction::Add:
641 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000642 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000643 break;
644 case Instruction::Sub:
645 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000646 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000647 break;
648 case Instruction::Mul:
649 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000650 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000651 break;
652 case Instruction::FDiv:
653 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000654 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000655 break;
656 case Instruction::FRem:
657 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000658 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000659 break;
660 }
661 }
662 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000663 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000664 return GV;
665 }
Chris Lattner9a231222003-05-14 17:51:49 +0000666 default:
667 break;
668 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000670 abort();
671 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000672
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000674 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000675 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000676 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000677 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000678 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000679 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000680 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000681 case Type::X86_FP80TyID:
682 case Type::FP128TyID:
683 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000684 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000685 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000686 case Type::IntegerTyID:
687 Result.IntVal = cast<ConstantInt>(C)->getValue();
688 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000689 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000690 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000691 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000692 else if (const Function *F = dyn_cast<Function>(C))
693 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
694 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
695 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
696 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000697 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000698 break;
699 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000700 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000701 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000702 }
703 return Result;
704}
705
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000706/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
707/// with the integer held in IntVal.
708static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
709 unsigned StoreBytes) {
710 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
711 uint8_t *Src = (uint8_t *)IntVal.getRawData();
712
Chris Lattnerb67c9582009-01-22 19:53:00 +0000713 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000714 // Little-endian host - the source is ordered from LSB to MSB. Order the
715 // destination from LSB to MSB: Do a straight copy.
716 memcpy(Dst, Src, StoreBytes);
717 else {
718 // Big-endian host - the source is an array of 64 bit words ordered from
719 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
720 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
721 while (StoreBytes > sizeof(uint64_t)) {
722 StoreBytes -= sizeof(uint64_t);
723 // May not be aligned so use memcpy.
724 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
725 Src += sizeof(uint64_t);
726 }
727
728 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
729 }
730}
731
Nate Begeman37efe672006-04-22 18:53:45 +0000732/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
733/// is the address of the memory at which to store Val, cast to GenericValue *.
734/// It is not a pointer to a GenericValue containing the address at which to
735/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000736void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
737 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000738 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
739
Reid Spencer8fb0f192007-03-06 03:04:04 +0000740 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000741 case Type::IntegerTyID:
742 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000743 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000744 case Type::FloatTyID:
745 *((float*)Ptr) = Val.FloatVal;
746 break;
747 case Type::DoubleTyID:
748 *((double*)Ptr) = Val.DoubleVal;
749 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000750 case Type::X86_FP80TyID: {
751 uint16_t *Dest = (uint16_t*)Ptr;
752 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
753 // This is endian dependent, but it will only work on x86 anyway.
754 Dest[0] = Src[4];
755 Dest[1] = Src[0];
756 Dest[2] = Src[1];
757 Dest[3] = Src[2];
758 Dest[4] = Src[3];
759 break;
760 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000761 case Type::PointerTyID:
762 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
763 if (StoreBytes != sizeof(PointerTy))
764 memset(Ptr, 0, StoreBytes);
765
Reid Spencer8fb0f192007-03-06 03:04:04 +0000766 *((PointerTy*)Ptr) = Val.PointerVal;
767 break;
768 default:
769 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000770 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000771
Chris Lattnerb67c9582009-01-22 19:53:00 +0000772 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000773 // Host and target are different endian - reverse the stored bytes.
774 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
775}
776
777/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
778/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
779static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
780 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
781 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
782
Chris Lattnerb67c9582009-01-22 19:53:00 +0000783 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000784 // Little-endian host - the destination must be ordered from LSB to MSB.
785 // The source is ordered from LSB to MSB: Do a straight copy.
786 memcpy(Dst, Src, LoadBytes);
787 else {
788 // Big-endian - the destination is an array of 64 bit words ordered from
789 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
790 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
791 // a word.
792 while (LoadBytes > sizeof(uint64_t)) {
793 LoadBytes -= sizeof(uint64_t);
794 // May not be aligned so use memcpy.
795 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
796 Dst += sizeof(uint64_t);
797 }
798
799 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
800 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000801}
802
Misha Brukman4afac182003-10-10 17:45:12 +0000803/// FIXME: document
804///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000805void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000806 GenericValue *Ptr,
807 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000808 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000809
Chris Lattnerb67c9582009-01-22 19:53:00 +0000810 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000811 // Host and target are different endian - reverse copy the stored
812 // bytes into a buffer, and load from that.
813 uint8_t *Src = (uint8_t*)Ptr;
814 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
815 std::reverse_copy(Src, Src + LoadBytes, Buf);
816 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000817 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000818
819 switch (Ty->getTypeID()) {
820 case Type::IntegerTyID:
821 // An APInt with all words initially zero.
822 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
823 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
824 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000825 case Type::FloatTyID:
826 Result.FloatVal = *((float*)Ptr);
827 break;
828 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000829 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000830 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000831 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000832 Result.PointerVal = *((PointerTy*)Ptr);
833 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000834 case Type::X86_FP80TyID: {
835 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000836 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000837 uint16_t *p = (uint16_t*)Ptr;
838 union {
839 uint16_t x[8];
840 uint64_t y[2];
841 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000842 x[0] = p[1];
843 x[1] = p[2];
844 x[2] = p[3];
845 x[3] = p[4];
846 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000847 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000848 break;
849 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000850 default:
851 cerr << "Cannot load value of type " << *Ty << "!\n";
852 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000853 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000854}
855
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000856// InitializeMemory - Recursive function to apply a Constant value into the
857// specified memory location...
858//
859void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Evan Chengeb5d95a2008-11-06 17:46:04 +0000860 DOUT << "JIT: Initializing " << Addr << " ";
Dale Johannesendd947ea2008-08-07 01:30:15 +0000861 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000862 if (isa<UndefValue>(Init)) {
863 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000864 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000865 unsigned ElementSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000866 getTargetData()->getTypePaddedSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000867 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
868 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
869 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000870 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000871 memset(Addr, 0, (size_t)getTargetData()->getTypePaddedSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000872 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000873 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
874 unsigned ElementSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000875 getTargetData()->getTypePaddedSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000876 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
877 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
878 return;
879 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
880 const StructLayout *SL =
881 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
882 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
883 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
884 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000885 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000886 GenericValue Val = getConstantValue(Init);
887 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
888 return;
889 }
890
Dan Gohman638e3782008-05-20 03:20:09 +0000891 cerr << "Bad Type: " << *Init->getType() << "\n";
892 assert(0 && "Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000893}
894
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000895/// EmitGlobals - Emit all of the global variables to memory, storing their
896/// addresses into GlobalAddress. This must make sure to copy the contents of
897/// their initializers into the memory.
898///
899void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000900
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000901 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000902 // to hold them. If there is more than one module, do a prepass over globals
903 // to figure out how the different modules should link together.
904 //
905 std::map<std::pair<std::string, const Type*>,
906 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000907
Chris Lattnerfe854032006-08-16 01:24:12 +0000908 if (Modules.size() != 1) {
909 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
910 Module &M = *Modules[m]->getModule();
911 for (Module::const_global_iterator I = M.global_begin(),
912 E = M.global_end(); I != E; ++I) {
913 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000914 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000915 GV->hasAppendingLinkage() || !GV->hasName())
916 continue;// Ignore external globals and globals with internal linkage.
917
918 const GlobalValue *&GVEntry =
919 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
920
921 // If this is the first time we've seen this global, it is the canonical
922 // version.
923 if (!GVEntry) {
924 GVEntry = GV;
925 continue;
926 }
927
928 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000929 if (GVEntry->hasExternalLinkage() ||
930 GVEntry->hasDLLImportLinkage() ||
931 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000932 continue;
933
934 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000935 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000936 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000937 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000938 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000939 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000940 }
941
942 std::vector<const GlobalValue*> NonCanonicalGlobals;
943 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
944 Module &M = *Modules[m]->getModule();
945 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
946 I != E; ++I) {
947 // In the multi-module case, see what this global maps to.
948 if (!LinkedGlobalsMap.empty()) {
949 if (const GlobalValue *GVEntry =
950 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
951 // If something else is the canonical global, ignore this one.
952 if (GVEntry != &*I) {
953 NonCanonicalGlobals.push_back(I);
954 continue;
955 }
956 }
957 }
958
Reid Spencer5cbf9852007-01-30 20:08:39 +0000959 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000960 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +0000961 } else {
962 // External variable reference. Try to use the dynamic loader to
963 // get a pointer to it.
964 if (void *SymAddr =
965 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
966 addGlobalMapping(I, SymAddr);
967 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000968 cerr << "Could not resolve external global address: "
969 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000970 abort();
971 }
972 }
973 }
974
975 // If there are multiple modules, map the non-canonical globals to their
976 // canonical location.
977 if (!NonCanonicalGlobals.empty()) {
978 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
979 const GlobalValue *GV = NonCanonicalGlobals[i];
980 const GlobalValue *CGV =
981 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
982 void *Ptr = getPointerToGlobalIfAvailable(CGV);
983 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +0000984 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +0000985 }
986 }
987
Reid Spencera54b7cb2007-01-12 07:05:14 +0000988 // Now that all of the globals are set up in memory, loop through them all
989 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000990 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
991 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000992 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000993 if (!LinkedGlobalsMap.empty()) {
994 if (const GlobalValue *GVEntry =
995 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
996 if (GVEntry != &*I) // Not the canonical variable.
997 continue;
998 }
999 EmitGlobalVariable(I);
1000 }
1001 }
1002 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001003}
1004
1005// EmitGlobalVariable - This method emits the specified global variable to the
1006// address specified in GlobalAddresses, or allocates new memory if it's not
1007// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001008void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001009 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001010
Chris Lattner24b0a182003-12-20 02:45:37 +00001011 if (GA == 0) {
1012 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001013 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001014 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001015 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001016
1017 // Don't initialize if it's thread local, let the client do it.
1018 if (!GV->isThreadLocal())
1019 InitializeMemory(GV->getInitializer(), GA);
1020
1021 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001022 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001023 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001024 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001025}