blob: 52a69eaea77c40edc8a2873207443184df9f2117 [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 Cheng1b088f32008-06-17 16:49:02 +000043 SymbolSearchingDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000044 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000045 assert(P && "ModuleProvider is null?");
46}
47
Brian Gaeke8e539482003-09-04 22:57:27 +000048ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000049 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000050 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
51 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000052}
53
Devang Patel73d0e212007-10-15 19:56:32 +000054/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
55/// Release module from ModuleProvider.
56Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
57 std::string *ErrInfo) {
58 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
59 E = Modules.end(); I != E; ++I) {
60 ModuleProvider *MP = *I;
61 if (MP == P) {
62 Modules.erase(I);
Nate Begemanf049e072008-05-21 16:34:48 +000063 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel73d0e212007-10-15 19:56:32 +000064 return MP->releaseModule(ErrInfo);
65 }
66 }
67 return NULL;
68}
69
Chris Lattnerfe854032006-08-16 01:24:12 +000070/// FindFunctionNamed - Search all of the active modules to find the one that
71/// defines FnName. This is very slow operation and shouldn't be used for
72/// general code.
73Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
74 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000075 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000076 return F;
77 }
78 return 0;
79}
80
81
Chris Lattnere7fd5532006-05-08 22:00:52 +000082/// addGlobalMapping - Tell the execution engine that the specified global is
83/// at the specified location. This is used internally as functions are JIT'd
84/// and as global variables are laid out in memory. It can and should also be
85/// used by clients of the EE that want to have an LLVM global overlay
86/// existing data in memory.
87void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
88 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +000089
90 DOUT << "Map " << *GV << " to " << Addr << "\n";
Chris Lattnere7fd5532006-05-08 22:00:52 +000091 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
92 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
93 CurVal = Addr;
94
95 // If we are using the reverse mapping, add it too
96 if (!state.getGlobalAddressReverseMap(locked).empty()) {
97 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
98 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
99 V = GV;
100 }
101}
102
103/// clearAllGlobalMappings - Clear all global mappings and start over again
104/// use in dynamic compilation scenarios when you want to move globals
105void ExecutionEngine::clearAllGlobalMappings() {
106 MutexGuard locked(lock);
107
108 state.getGlobalAddressMap(locked).clear();
109 state.getGlobalAddressReverseMap(locked).clear();
110}
111
Nate Begemanf049e072008-05-21 16:34:48 +0000112/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
113/// particular module, because it has been removed from the JIT.
114void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
115 MutexGuard locked(lock);
116
117 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
118 state.getGlobalAddressMap(locked).erase(FI);
119 state.getGlobalAddressReverseMap(locked).erase(FI);
120 }
121 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
122 GI != GE; ++GI) {
123 state.getGlobalAddressMap(locked).erase(GI);
124 state.getGlobalAddressReverseMap(locked).erase(GI);
125 }
126}
127
Chris Lattnere7fd5532006-05-08 22:00:52 +0000128/// updateGlobalMapping - Replace an existing mapping for GV with a new
129/// address. This updates both maps as required. If "Addr" is null, the
130/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000131void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000132 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000133
134 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
135
Chris Lattnere7fd5532006-05-08 22:00:52 +0000136 // Deleting from the mapping?
137 if (Addr == 0) {
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000138 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
139 void *OldVal;
140 if (I == Map.end())
141 OldVal = 0;
142 else {
143 OldVal = I->second;
144 Map.erase(I);
145 }
146
Chris Lattnere7fd5532006-05-08 22:00:52 +0000147 if (!state.getGlobalAddressReverseMap(locked).empty())
148 state.getGlobalAddressReverseMap(locked).erase(Addr);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000149 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000150 }
151
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000152 void *&CurVal = Map[GV];
153 void *OldVal = CurVal;
154
Chris Lattnere7fd5532006-05-08 22:00:52 +0000155 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
156 state.getGlobalAddressReverseMap(locked).erase(CurVal);
157 CurVal = Addr;
158
159 // If we are using the reverse mapping, add it too
160 if (!state.getGlobalAddressReverseMap(locked).empty()) {
161 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
162 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
163 V = GV;
164 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000165 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000166}
167
168/// getPointerToGlobalIfAvailable - This returns the address of the specified
169/// global value if it is has already been codegen'd, otherwise it returns null.
170///
171void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
172 MutexGuard locked(lock);
173
174 std::map<const GlobalValue*, void*>::iterator I =
175 state.getGlobalAddressMap(locked).find(GV);
176 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
177}
178
Chris Lattner55d86482003-12-31 20:21:04 +0000179/// getGlobalValueAtAddress - Return the LLVM global value object that starts
180/// at the specified address.
181///
182const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000183 MutexGuard locked(lock);
184
Chris Lattner55d86482003-12-31 20:21:04 +0000185 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000186 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187 for (std::map<const GlobalValue*, void *>::iterator
188 I = state.getGlobalAddressMap(locked).begin(),
189 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
190 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
191 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000192 }
193
194 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000195 state.getGlobalAddressReverseMap(locked).find(Addr);
196 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000197}
Chris Lattner87f03102003-12-26 06:50:30 +0000198
199// CreateArgv - Turn a vector of strings into a nice argv style array of
200// pointers to null terminated strings.
201//
202static void *CreateArgv(ExecutionEngine *EE,
203 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000204 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000205 char *Result = new char[(InputArgv.size()+1)*PtrSize];
206
Bill Wendling480f0932006-11-27 23:54:50 +0000207 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000208 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000209
210 for (unsigned i = 0; i != InputArgv.size(); ++i) {
211 unsigned Size = InputArgv[i].size()+1;
212 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000213 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000214
Chris Lattner87f03102003-12-26 06:50:30 +0000215 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
216 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000217
Chris Lattner87f03102003-12-26 06:50:30 +0000218 // Endian safe: Result[i] = (PointerTy)Dest;
219 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
220 SBytePtr);
221 }
222
223 // Null terminate it
224 EE->StoreValueToMemory(PTOGV(0),
225 (GenericValue*)(Result+InputArgv.size()*PtrSize),
226 SBytePtr);
227 return Result;
228}
229
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000230
231/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000232/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000233/// value of isDtors.
234void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
235 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000236
Chris Lattnerfe854032006-08-16 01:24:12 +0000237 // Execute global ctors/dtors for each module in the program.
238 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
239 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
240
241 // If this global has internal linkage, or if it has a use, then it must be
242 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
243 // this is the case, don't execute any of the global ctors, __main will do
244 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000245 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000246
247 // Should be an array of '{ int, void ()* }' structs. The first value is
248 // the init priority, which we ignore.
249 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
250 if (!InitList) continue;
251 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
252 if (ConstantStruct *CS =
253 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
254 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000255
Chris Lattnerfe854032006-08-16 01:24:12 +0000256 Constant *FP = CS->getOperand(1);
257 if (FP->isNullValue())
258 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000259
Chris Lattnerfe854032006-08-16 01:24:12 +0000260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000261 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000262 FP = CE->getOperand(0);
263 if (Function *F = dyn_cast<Function>(FP)) {
264 // Execute the ctor/dtor function!
265 runFunction(F, std::vector<GenericValue>());
266 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000267 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000268 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000269}
270
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000271#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000272/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
273static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
274 unsigned PtrSize = EE->getTargetData()->getPointerSize();
275 for (unsigned i = 0; i < PtrSize; ++i)
276 if (*(i + (uint8_t*)Loc))
277 return false;
278 return true;
279}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000280#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000281
Chris Lattner87f03102003-12-26 06:50:30 +0000282/// runFunctionAsMain - This is a helper function which wraps runFunction to
283/// handle the common task of starting up main with the specified argc, argv,
284/// and envp parameters.
285int ExecutionEngine::runFunctionAsMain(Function *Fn,
286 const std::vector<std::string> &argv,
287 const char * const * envp) {
288 std::vector<GenericValue> GVArgs;
289 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000290 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000291
292 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000293 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000294 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000295 const Type* PPInt8Ty =
296 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000297 switch (NumArgs) {
298 case 3:
299 if (FTy->getParamType(2) != PPInt8Ty) {
300 cerr << "Invalid type for third argument of main() supplied\n";
301 abort();
302 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000303 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000304 case 2:
305 if (FTy->getParamType(1) != PPInt8Ty) {
306 cerr << "Invalid type for second argument of main() supplied\n";
307 abort();
308 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000309 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000310 case 1:
311 if (FTy->getParamType(0) != Type::Int32Ty) {
312 cerr << "Invalid type for first argument of main() supplied\n";
313 abort();
314 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000315 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000316 case 0:
317 if (FTy->getReturnType() != Type::Int32Ty &&
318 FTy->getReturnType() != Type::VoidTy) {
319 cerr << "Invalid return type of main() supplied\n";
320 abort();
321 }
322 break;
323 default:
324 cerr << "Invalid number of arguments of main() supplied\n";
325 abort();
326 }
327
Chris Lattnerf24d0992004-08-16 01:05:35 +0000328 if (NumArgs) {
329 GVArgs.push_back(GVArgc); // Arg #0 = argc.
330 if (NumArgs > 1) {
331 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000332 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000333 "argv[0] was null after CreateArgv");
334 if (NumArgs > 2) {
335 std::vector<std::string> EnvVars;
336 for (unsigned i = 0; envp[i]; ++i)
337 EnvVars.push_back(envp[i]);
338 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
339 }
340 }
341 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000342 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000343}
344
Misha Brukman19684162003-10-16 21:18:05 +0000345/// If possible, create a JIT, unless the caller specifically requests an
346/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000347/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000348///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000349ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000350 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000351 std::string *ErrorStr,
352 bool Fast) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000353 ExecutionEngine *EE = 0;
354
Nick Lewycky6456d862008-03-08 02:49:45 +0000355 // Make sure we can resolve symbols in the program as well. The zero arg
356 // to the function tells DynamicLibrary to load the program, not a library.
357 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
358 return 0;
359
Chris Lattner73011782003-12-28 09:44:37 +0000360 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000361 if (!ForceInterpreter && JITCtor)
Evan Cheng502f20b2008-08-08 08:11:34 +0000362 EE = JITCtor(MP, ErrorStr, Fast);
Brian Gaeke82d82772003-09-03 20:34:19 +0000363
364 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000365 if (EE == 0 && InterpCtor)
Evan Cheng502f20b2008-08-08 08:11:34 +0000366 EE = InterpCtor(MP, ErrorStr, Fast);
Chris Lattner73011782003-12-28 09:44:37 +0000367
Brian Gaeke82d82772003-09-03 20:34:19 +0000368 return EE;
369}
370
Chris Lattner8b5295b2007-10-21 22:57:11 +0000371ExecutionEngine *ExecutionEngine::create(Module *M) {
372 return create(new ExistingModuleProvider(M));
373}
374
Misha Brukman4afac182003-10-10 17:45:12 +0000375/// getPointerToGlobal - This returns the address of the specified global
376/// value. This may involve code generation if it's a function.
377///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000378void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000379 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000380 return getPointerToFunction(F);
381
Reid Spenceree448632005-07-12 15:51:55 +0000382 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000383 void *p = state.getGlobalAddressMap(locked)[GV];
384 if (p)
385 return p;
386
387 // Global variable might have been added since interpreter started.
388 if (GlobalVariable *GVar =
389 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
390 EmitGlobalVariable(GVar);
391 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000392 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000393 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000394}
395
Reid Spencer3da59db2006-11-27 01:05:10 +0000396/// This function converts a Constant* into a GenericValue. The interesting
397/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000398/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000399GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000400 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000401 if (isa<UndefValue>(C))
402 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000403
Reid Spencer3da59db2006-11-27 01:05:10 +0000404 // If the value is a ConstantExpr
405 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000406 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000407 switch (CE->getOpcode()) {
408 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000409 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000410 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000411 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000412 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000413 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000414
Reid Spencer8fb0f192007-03-06 03:04:04 +0000415 char* tmp = (char*) Result.PointerVal;
416 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000417 return Result;
418 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000419 case Instruction::Trunc: {
420 GenericValue GV = getConstantValue(Op0);
421 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
422 GV.IntVal = GV.IntVal.trunc(BitWidth);
423 return GV;
424 }
425 case Instruction::ZExt: {
426 GenericValue GV = getConstantValue(Op0);
427 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
428 GV.IntVal = GV.IntVal.zext(BitWidth);
429 return GV;
430 }
431 case Instruction::SExt: {
432 GenericValue GV = getConstantValue(Op0);
433 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
434 GV.IntVal = GV.IntVal.sext(BitWidth);
435 return GV;
436 }
437 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000438 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000439 GenericValue GV = getConstantValue(Op0);
440 GV.FloatVal = float(GV.DoubleVal);
441 return GV;
442 }
443 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000444 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000445 GenericValue GV = getConstantValue(Op0);
446 GV.DoubleVal = double(GV.FloatVal);
447 return GV;
448 }
449 case Instruction::UIToFP: {
450 GenericValue GV = getConstantValue(Op0);
451 if (CE->getType() == Type::FloatTy)
452 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000453 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000454 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000455 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000456 const uint64_t zero[] = {0, 0};
457 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000458 (void)apf.convertFromAPInt(GV.IntVal,
459 false,
460 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000461 GV.IntVal = apf.convertToAPInt();
462 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000463 return GV;
464 }
465 case Instruction::SIToFP: {
466 GenericValue GV = getConstantValue(Op0);
467 if (CE->getType() == Type::FloatTy)
468 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000469 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000470 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000471 else if (CE->getType() == Type::X86_FP80Ty) {
472 const uint64_t zero[] = { 0, 0};
473 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000474 (void)apf.convertFromAPInt(GV.IntVal,
475 true,
476 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000477 GV.IntVal = apf.convertToAPInt();
478 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000479 return GV;
480 }
481 case Instruction::FPToUI: // double->APInt conversion handles sign
482 case Instruction::FPToSI: {
483 GenericValue GV = getConstantValue(Op0);
484 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
485 if (Op0->getType() == Type::FloatTy)
486 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000487 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000488 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000489 else if (Op0->getType() == Type::X86_FP80Ty) {
490 APFloat apf = APFloat(GV.IntVal);
491 uint64_t v;
492 (void)apf.convertToInteger(&v, BitWidth,
493 CE->getOpcode()==Instruction::FPToSI,
494 APFloat::rmTowardZero);
495 GV.IntVal = v; // endian?
496 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000497 return GV;
498 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000499 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000500 GenericValue GV = getConstantValue(Op0);
501 uint32_t PtrWidth = TD->getPointerSizeInBits();
502 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
503 return GV;
504 }
505 case Instruction::IntToPtr: {
506 GenericValue GV = getConstantValue(Op0);
507 uint32_t PtrWidth = TD->getPointerSizeInBits();
508 if (PtrWidth != GV.IntVal.getBitWidth())
509 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
510 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
511 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000512 return GV;
513 }
514 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000515 GenericValue GV = getConstantValue(Op0);
516 const Type* DestTy = CE->getType();
517 switch (Op0->getType()->getTypeID()) {
518 default: assert(0 && "Invalid bitcast operand");
519 case Type::IntegerTyID:
520 assert(DestTy->isFloatingPoint() && "invalid bitcast");
521 if (DestTy == Type::FloatTy)
522 GV.FloatVal = GV.IntVal.bitsToFloat();
523 else if (DestTy == Type::DoubleTy)
524 GV.DoubleVal = GV.IntVal.bitsToDouble();
525 break;
526 case Type::FloatTyID:
527 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
528 GV.IntVal.floatToBits(GV.FloatVal);
529 break;
530 case Type::DoubleTyID:
531 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
532 GV.IntVal.doubleToBits(GV.DoubleVal);
533 break;
534 case Type::PointerTyID:
535 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
536 break; // getConstantValue(Op0) above already converted it
537 }
538 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000539 }
Chris Lattner9a231222003-05-14 17:51:49 +0000540 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000541 case Instruction::Sub:
542 case Instruction::Mul:
543 case Instruction::UDiv:
544 case Instruction::SDiv:
545 case Instruction::URem:
546 case Instruction::SRem:
547 case Instruction::And:
548 case Instruction::Or:
549 case Instruction::Xor: {
550 GenericValue LHS = getConstantValue(Op0);
551 GenericValue RHS = getConstantValue(CE->getOperand(1));
552 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000553 switch (CE->getOperand(0)->getType()->getTypeID()) {
554 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000555 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000556 switch (CE->getOpcode()) {
557 default: assert(0 && "Invalid integer opcode");
558 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
559 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
560 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
561 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
562 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
563 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
564 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
565 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
566 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
567 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
568 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000569 break;
570 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000571 switch (CE->getOpcode()) {
572 default: assert(0 && "Invalid float opcode"); abort();
573 case Instruction::Add:
574 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
575 case Instruction::Sub:
576 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
577 case Instruction::Mul:
578 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
579 case Instruction::FDiv:
580 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
581 case Instruction::FRem:
582 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
583 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000584 break;
585 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000586 switch (CE->getOpcode()) {
587 default: assert(0 && "Invalid double opcode"); abort();
588 case Instruction::Add:
589 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
590 case Instruction::Sub:
591 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
592 case Instruction::Mul:
593 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
594 case Instruction::FDiv:
595 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
596 case Instruction::FRem:
597 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
598 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000599 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000600 case Type::X86_FP80TyID:
601 case Type::PPC_FP128TyID:
602 case Type::FP128TyID: {
603 APFloat apfLHS = APFloat(LHS.IntVal);
604 switch (CE->getOpcode()) {
605 default: assert(0 && "Invalid long double opcode"); abort();
606 case Instruction::Add:
607 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
608 GV.IntVal = apfLHS.convertToAPInt();
609 break;
610 case Instruction::Sub:
611 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
612 GV.IntVal = apfLHS.convertToAPInt();
613 break;
614 case Instruction::Mul:
615 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
616 GV.IntVal = apfLHS.convertToAPInt();
617 break;
618 case Instruction::FDiv:
619 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
620 GV.IntVal = apfLHS.convertToAPInt();
621 break;
622 case Instruction::FRem:
623 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
624 GV.IntVal = apfLHS.convertToAPInt();
625 break;
626 }
627 }
628 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000629 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000630 return GV;
631 }
Chris Lattner9a231222003-05-14 17:51:49 +0000632 default:
633 break;
634 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000635 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000636 abort();
637 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000638
Reid Spencerbce30f12007-03-06 22:23:15 +0000639 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000640 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000641 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000642 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000643 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000644 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000645 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000646 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000647 case Type::X86_FP80TyID:
648 case Type::FP128TyID:
649 case Type::PPC_FP128TyID:
650 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
651 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000652 case Type::IntegerTyID:
653 Result.IntVal = cast<ConstantInt>(C)->getValue();
654 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000655 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000656 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000657 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000658 else if (const Function *F = dyn_cast<Function>(C))
659 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
660 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
661 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
662 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000663 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000664 break;
665 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000666 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000667 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000668 }
669 return Result;
670}
671
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000672/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
673/// with the integer held in IntVal.
674static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
675 unsigned StoreBytes) {
676 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
677 uint8_t *Src = (uint8_t *)IntVal.getRawData();
678
679 if (sys::littleEndianHost())
680 // Little-endian host - the source is ordered from LSB to MSB. Order the
681 // destination from LSB to MSB: Do a straight copy.
682 memcpy(Dst, Src, StoreBytes);
683 else {
684 // Big-endian host - the source is an array of 64 bit words ordered from
685 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
686 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
687 while (StoreBytes > sizeof(uint64_t)) {
688 StoreBytes -= sizeof(uint64_t);
689 // May not be aligned so use memcpy.
690 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
691 Src += sizeof(uint64_t);
692 }
693
694 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
695 }
696}
697
Nate Begeman37efe672006-04-22 18:53:45 +0000698/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
699/// is the address of the memory at which to store Val, cast to GenericValue *.
700/// It is not a pointer to a GenericValue containing the address at which to
701/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000702void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000703 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000704 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
705
Reid Spencer8fb0f192007-03-06 03:04:04 +0000706 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000707 case Type::IntegerTyID:
708 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000709 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000710 case Type::FloatTyID:
711 *((float*)Ptr) = Val.FloatVal;
712 break;
713 case Type::DoubleTyID:
714 *((double*)Ptr) = Val.DoubleVal;
715 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000716 case Type::X86_FP80TyID: {
717 uint16_t *Dest = (uint16_t*)Ptr;
718 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
719 // This is endian dependent, but it will only work on x86 anyway.
720 Dest[0] = Src[4];
721 Dest[1] = Src[0];
722 Dest[2] = Src[1];
723 Dest[3] = Src[2];
724 Dest[4] = Src[3];
725 break;
726 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000727 case Type::PointerTyID:
728 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
729 if (StoreBytes != sizeof(PointerTy))
730 memset(Ptr, 0, StoreBytes);
731
Reid Spencer8fb0f192007-03-06 03:04:04 +0000732 *((PointerTy*)Ptr) = Val.PointerVal;
733 break;
734 default:
735 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000736 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000737
738 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
739 // Host and target are different endian - reverse the stored bytes.
740 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
741}
742
743/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
744/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
745static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
746 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
747 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
748
749 if (sys::littleEndianHost())
750 // Little-endian host - the destination must be ordered from LSB to MSB.
751 // The source is ordered from LSB to MSB: Do a straight copy.
752 memcpy(Dst, Src, LoadBytes);
753 else {
754 // Big-endian - the destination is an array of 64 bit words ordered from
755 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
756 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
757 // a word.
758 while (LoadBytes > sizeof(uint64_t)) {
759 LoadBytes -= sizeof(uint64_t);
760 // May not be aligned so use memcpy.
761 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
762 Dst += sizeof(uint64_t);
763 }
764
765 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
766 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000767}
768
Misha Brukman4afac182003-10-10 17:45:12 +0000769/// FIXME: document
770///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000771void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000772 GenericValue *Ptr,
773 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000774 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000775
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000776 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
777 // Host and target are different endian - reverse copy the stored
778 // bytes into a buffer, and load from that.
779 uint8_t *Src = (uint8_t*)Ptr;
780 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
781 std::reverse_copy(Src, Src + LoadBytes, Buf);
782 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000783 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000784
785 switch (Ty->getTypeID()) {
786 case Type::IntegerTyID:
787 // An APInt with all words initially zero.
788 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
789 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
790 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000791 case Type::FloatTyID:
792 Result.FloatVal = *((float*)Ptr);
793 break;
794 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000795 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000796 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000797 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 Result.PointerVal = *((PointerTy*)Ptr);
799 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000800 case Type::X86_FP80TyID: {
801 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000802 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000803 uint16_t *p = (uint16_t*)Ptr;
804 union {
805 uint16_t x[8];
806 uint64_t y[2];
807 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000808 x[0] = p[1];
809 x[1] = p[2];
810 x[2] = p[3];
811 x[3] = p[4];
812 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000813 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000814 break;
815 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000816 default:
817 cerr << "Cannot load value of type " << *Ty << "!\n";
818 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000819 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000820}
821
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000822// InitializeMemory - Recursive function to apply a Constant value into the
823// specified memory location...
824//
825void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000826 DOUT << "Initializing " << Addr;
827 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000828 if (isa<UndefValue>(Init)) {
829 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000830 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000831 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000832 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000833 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
834 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
835 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000836 } else if (isa<ConstantAggregateZero>(Init)) {
837 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
838 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000839 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
840 unsigned ElementSize =
841 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
842 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
843 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
844 return;
845 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
846 const StructLayout *SL =
847 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
848 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
849 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
850 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000851 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000852 GenericValue Val = getConstantValue(Init);
853 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
854 return;
855 }
856
Dan Gohman638e3782008-05-20 03:20:09 +0000857 cerr << "Bad Type: " << *Init->getType() << "\n";
858 assert(0 && "Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000859}
860
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000861/// EmitGlobals - Emit all of the global variables to memory, storing their
862/// addresses into GlobalAddress. This must make sure to copy the contents of
863/// their initializers into the memory.
864///
865void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000866 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000867
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000868 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000869 // to hold them. If there is more than one module, do a prepass over globals
870 // to figure out how the different modules should link together.
871 //
872 std::map<std::pair<std::string, const Type*>,
873 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000874
Chris Lattnerfe854032006-08-16 01:24:12 +0000875 if (Modules.size() != 1) {
876 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
877 Module &M = *Modules[m]->getModule();
878 for (Module::const_global_iterator I = M.global_begin(),
879 E = M.global_end(); I != E; ++I) {
880 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000881 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000882 GV->hasAppendingLinkage() || !GV->hasName())
883 continue;// Ignore external globals and globals with internal linkage.
884
885 const GlobalValue *&GVEntry =
886 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
887
888 // If this is the first time we've seen this global, it is the canonical
889 // version.
890 if (!GVEntry) {
891 GVEntry = GV;
892 continue;
893 }
894
895 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000896 if (GVEntry->hasExternalLinkage() ||
897 GVEntry->hasDLLImportLinkage() ||
898 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000899 continue;
900
901 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000902 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000903 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000904 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000905 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000906 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000907 }
908
909 std::vector<const GlobalValue*> NonCanonicalGlobals;
910 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
911 Module &M = *Modules[m]->getModule();
912 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
913 I != E; ++I) {
914 // In the multi-module case, see what this global maps to.
915 if (!LinkedGlobalsMap.empty()) {
916 if (const GlobalValue *GVEntry =
917 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
918 // If something else is the canonical global, ignore this one.
919 if (GVEntry != &*I) {
920 NonCanonicalGlobals.push_back(I);
921 continue;
922 }
923 }
924 }
925
Reid Spencer5cbf9852007-01-30 20:08:39 +0000926 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000927 // Get the type of the global.
928 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000929
Chris Lattnerfe854032006-08-16 01:24:12 +0000930 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000931 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000932 addGlobalMapping(I, new char[Size]);
933 } else {
934 // External variable reference. Try to use the dynamic loader to
935 // get a pointer to it.
936 if (void *SymAddr =
937 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
938 addGlobalMapping(I, SymAddr);
939 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000940 cerr << "Could not resolve external global address: "
941 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000942 abort();
943 }
944 }
945 }
946
947 // If there are multiple modules, map the non-canonical globals to their
948 // canonical location.
949 if (!NonCanonicalGlobals.empty()) {
950 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
951 const GlobalValue *GV = NonCanonicalGlobals[i];
952 const GlobalValue *CGV =
953 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
954 void *Ptr = getPointerToGlobalIfAvailable(CGV);
955 assert(Ptr && "Canonical global wasn't codegen'd!");
956 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
957 }
958 }
959
Reid Spencera54b7cb2007-01-12 07:05:14 +0000960 // Now that all of the globals are set up in memory, loop through them all
961 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000962 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
963 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000964 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000965 if (!LinkedGlobalsMap.empty()) {
966 if (const GlobalValue *GVEntry =
967 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
968 if (GVEntry != &*I) // Not the canonical variable.
969 continue;
970 }
971 EmitGlobalVariable(I);
972 }
973 }
974 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000975}
976
977// EmitGlobalVariable - This method emits the specified global variable to the
978// address specified in GlobalAddresses, or allocates new memory if it's not
979// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000980void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000981 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000982 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000983
Chris Lattnerc07ed132003-12-20 03:36:47 +0000984 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000985 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000986 if (GA == 0) {
987 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000988 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000989 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000990 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000991
Chris Lattner24b0a182003-12-20 02:45:37 +0000992 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000993 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000994 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000995}