blob: a56951d2c5269ab13131331e10f05ef27a8972d9 [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;
Chris Lattnerfe854032006-08-16 01:24:12 +000043 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000044 assert(P && "ModuleProvider is null?");
45}
46
Brian Gaeke8e539482003-09-04 22:57:27 +000047ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000048 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000049 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
50 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000051}
52
Devang Patel73d0e212007-10-15 19:56:32 +000053/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54/// Release module from ModuleProvider.
55Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
56 std::string *ErrInfo) {
57 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
58 E = Modules.end(); I != E; ++I) {
59 ModuleProvider *MP = *I;
60 if (MP == P) {
61 Modules.erase(I);
62 return MP->releaseModule(ErrInfo);
63 }
64 }
65 return NULL;
66}
67
Chris Lattnerfe854032006-08-16 01:24:12 +000068/// FindFunctionNamed - Search all of the active modules to find the one that
69/// defines FnName. This is very slow operation and shouldn't be used for
70/// general code.
71Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
72 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000073 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000074 return F;
75 }
76 return 0;
77}
78
79
Chris Lattnere7fd5532006-05-08 22:00:52 +000080/// addGlobalMapping - Tell the execution engine that the specified global is
81/// at the specified location. This is used internally as functions are JIT'd
82/// and as global variables are laid out in memory. It can and should also be
83/// used by clients of the EE that want to have an LLVM global overlay
84/// existing data in memory.
85void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
86 MutexGuard locked(lock);
87
88 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
89 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
90 CurVal = Addr;
91
92 // If we are using the reverse mapping, add it too
93 if (!state.getGlobalAddressReverseMap(locked).empty()) {
94 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
95 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
96 V = GV;
97 }
98}
99
100/// clearAllGlobalMappings - Clear all global mappings and start over again
101/// use in dynamic compilation scenarios when you want to move globals
102void ExecutionEngine::clearAllGlobalMappings() {
103 MutexGuard locked(lock);
104
105 state.getGlobalAddressMap(locked).clear();
106 state.getGlobalAddressReverseMap(locked).clear();
107}
108
109/// updateGlobalMapping - Replace an existing mapping for GV with a new
110/// address. This updates both maps as required. If "Addr" is null, the
111/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000112void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000113 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000114
115 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
116
Chris Lattnere7fd5532006-05-08 22:00:52 +0000117 // Deleting from the mapping?
118 if (Addr == 0) {
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000119 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
120 void *OldVal;
121 if (I == Map.end())
122 OldVal = 0;
123 else {
124 OldVal = I->second;
125 Map.erase(I);
126 }
127
Chris Lattnere7fd5532006-05-08 22:00:52 +0000128 if (!state.getGlobalAddressReverseMap(locked).empty())
129 state.getGlobalAddressReverseMap(locked).erase(Addr);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000130 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000131 }
132
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000133 void *&CurVal = Map[GV];
134 void *OldVal = CurVal;
135
Chris Lattnere7fd5532006-05-08 22:00:52 +0000136 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
137 state.getGlobalAddressReverseMap(locked).erase(CurVal);
138 CurVal = Addr;
139
140 // If we are using the reverse mapping, add it too
141 if (!state.getGlobalAddressReverseMap(locked).empty()) {
142 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
143 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
144 V = GV;
145 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000146 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000147}
148
149/// getPointerToGlobalIfAvailable - This returns the address of the specified
150/// global value if it is has already been codegen'd, otherwise it returns null.
151///
152void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
153 MutexGuard locked(lock);
154
155 std::map<const GlobalValue*, void*>::iterator I =
156 state.getGlobalAddressMap(locked).find(GV);
157 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
158}
159
Chris Lattner55d86482003-12-31 20:21:04 +0000160/// getGlobalValueAtAddress - Return the LLVM global value object that starts
161/// at the specified address.
162///
163const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000164 MutexGuard locked(lock);
165
Chris Lattner55d86482003-12-31 20:21:04 +0000166 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000167 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000168 for (std::map<const GlobalValue*, void *>::iterator
169 I = state.getGlobalAddressMap(locked).begin(),
170 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
171 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
172 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000173 }
174
175 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000176 state.getGlobalAddressReverseMap(locked).find(Addr);
177 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000178}
Chris Lattner87f03102003-12-26 06:50:30 +0000179
180// CreateArgv - Turn a vector of strings into a nice argv style array of
181// pointers to null terminated strings.
182//
183static void *CreateArgv(ExecutionEngine *EE,
184 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000185 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000186 char *Result = new char[(InputArgv.size()+1)*PtrSize];
187
Bill Wendling480f0932006-11-27 23:54:50 +0000188 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000189 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000190
191 for (unsigned i = 0; i != InputArgv.size(); ++i) {
192 unsigned Size = InputArgv[i].size()+1;
193 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000194 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000195
Chris Lattner87f03102003-12-26 06:50:30 +0000196 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
197 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000198
Chris Lattner87f03102003-12-26 06:50:30 +0000199 // Endian safe: Result[i] = (PointerTy)Dest;
200 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
201 SBytePtr);
202 }
203
204 // Null terminate it
205 EE->StoreValueToMemory(PTOGV(0),
206 (GenericValue*)(Result+InputArgv.size()*PtrSize),
207 SBytePtr);
208 return Result;
209}
210
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000211
212/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000213/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000214/// value of isDtors.
215void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
216 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000217
Chris Lattnerfe854032006-08-16 01:24:12 +0000218 // Execute global ctors/dtors for each module in the program.
219 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
220 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
221
222 // If this global has internal linkage, or if it has a use, then it must be
223 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
224 // this is the case, don't execute any of the global ctors, __main will do
225 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000226 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000227
228 // Should be an array of '{ int, void ()* }' structs. The first value is
229 // the init priority, which we ignore.
230 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
231 if (!InitList) continue;
232 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
233 if (ConstantStruct *CS =
234 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
235 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000236
Chris Lattnerfe854032006-08-16 01:24:12 +0000237 Constant *FP = CS->getOperand(1);
238 if (FP->isNullValue())
239 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000240
Chris Lattnerfe854032006-08-16 01:24:12 +0000241 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000242 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000243 FP = CE->getOperand(0);
244 if (Function *F = dyn_cast<Function>(FP)) {
245 // Execute the ctor/dtor function!
246 runFunction(F, std::vector<GenericValue>());
247 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000248 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000249 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000250}
251
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000252/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
253static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
254 unsigned PtrSize = EE->getTargetData()->getPointerSize();
255 for (unsigned i = 0; i < PtrSize; ++i)
256 if (*(i + (uint8_t*)Loc))
257 return false;
258 return true;
259}
260
Chris Lattner87f03102003-12-26 06:50:30 +0000261/// runFunctionAsMain - This is a helper function which wraps runFunction to
262/// handle the common task of starting up main with the specified argc, argv,
263/// and envp parameters.
264int ExecutionEngine::runFunctionAsMain(Function *Fn,
265 const std::vector<std::string> &argv,
266 const char * const * envp) {
267 std::vector<GenericValue> GVArgs;
268 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000269 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000270
271 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000272 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000273 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000274 const Type* PPInt8Ty =
275 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000276 switch (NumArgs) {
277 case 3:
278 if (FTy->getParamType(2) != PPInt8Ty) {
279 cerr << "Invalid type for third argument of main() supplied\n";
280 abort();
281 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000282 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000283 case 2:
284 if (FTy->getParamType(1) != PPInt8Ty) {
285 cerr << "Invalid type for second argument of main() supplied\n";
286 abort();
287 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000288 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000289 case 1:
290 if (FTy->getParamType(0) != Type::Int32Ty) {
291 cerr << "Invalid type for first argument of main() supplied\n";
292 abort();
293 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000294 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000295 case 0:
296 if (FTy->getReturnType() != Type::Int32Ty &&
297 FTy->getReturnType() != Type::VoidTy) {
298 cerr << "Invalid return type of main() supplied\n";
299 abort();
300 }
301 break;
302 default:
303 cerr << "Invalid number of arguments of main() supplied\n";
304 abort();
305 }
306
Chris Lattnerf24d0992004-08-16 01:05:35 +0000307 if (NumArgs) {
308 GVArgs.push_back(GVArgc); // Arg #0 = argc.
309 if (NumArgs > 1) {
310 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000311 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000312 "argv[0] was null after CreateArgv");
313 if (NumArgs > 2) {
314 std::vector<std::string> EnvVars;
315 for (unsigned i = 0; envp[i]; ++i)
316 EnvVars.push_back(envp[i]);
317 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
318 }
319 }
320 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000321 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000322}
323
Misha Brukman19684162003-10-16 21:18:05 +0000324/// If possible, create a JIT, unless the caller specifically requests an
325/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000326/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000327///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000328ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000329 bool ForceInterpreter,
330 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000331 ExecutionEngine *EE = 0;
332
Nick Lewycky6456d862008-03-08 02:49:45 +0000333 // Make sure we can resolve symbols in the program as well. The zero arg
334 // to the function tells DynamicLibrary to load the program, not a library.
335 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
336 return 0;
337
Chris Lattner73011782003-12-28 09:44:37 +0000338 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000339 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000340 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000341
342 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000343 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000344 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000345
Brian Gaeke82d82772003-09-03 20:34:19 +0000346 return EE;
347}
348
Chris Lattner8b5295b2007-10-21 22:57:11 +0000349ExecutionEngine *ExecutionEngine::create(Module *M) {
350 return create(new ExistingModuleProvider(M));
351}
352
Misha Brukman4afac182003-10-10 17:45:12 +0000353/// getPointerToGlobal - This returns the address of the specified global
354/// value. This may involve code generation if it's a function.
355///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000356void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000357 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000358 return getPointerToFunction(F);
359
Reid Spenceree448632005-07-12 15:51:55 +0000360 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000361 void *p = state.getGlobalAddressMap(locked)[GV];
362 if (p)
363 return p;
364
365 // Global variable might have been added since interpreter started.
366 if (GlobalVariable *GVar =
367 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
368 EmitGlobalVariable(GVar);
369 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000370 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000371 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000372}
373
Reid Spencer3da59db2006-11-27 01:05:10 +0000374/// This function converts a Constant* into a GenericValue. The interesting
375/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000376/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000377GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000378 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000379 if (isa<UndefValue>(C))
380 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000381
Reid Spencer3da59db2006-11-27 01:05:10 +0000382 // If the value is a ConstantExpr
383 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000384 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000385 switch (CE->getOpcode()) {
386 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000387 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000388 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000389 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000390 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000391 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000392
Reid Spencer8fb0f192007-03-06 03:04:04 +0000393 char* tmp = (char*) Result.PointerVal;
394 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000395 return Result;
396 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000397 case Instruction::Trunc: {
398 GenericValue GV = getConstantValue(Op0);
399 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
400 GV.IntVal = GV.IntVal.trunc(BitWidth);
401 return GV;
402 }
403 case Instruction::ZExt: {
404 GenericValue GV = getConstantValue(Op0);
405 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
406 GV.IntVal = GV.IntVal.zext(BitWidth);
407 return GV;
408 }
409 case Instruction::SExt: {
410 GenericValue GV = getConstantValue(Op0);
411 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
412 GV.IntVal = GV.IntVal.sext(BitWidth);
413 return GV;
414 }
415 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000416 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000417 GenericValue GV = getConstantValue(Op0);
418 GV.FloatVal = float(GV.DoubleVal);
419 return GV;
420 }
421 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000422 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000423 GenericValue GV = getConstantValue(Op0);
424 GV.DoubleVal = double(GV.FloatVal);
425 return GV;
426 }
427 case Instruction::UIToFP: {
428 GenericValue GV = getConstantValue(Op0);
429 if (CE->getType() == Type::FloatTy)
430 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000431 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000432 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000433 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000434 const uint64_t zero[] = {0, 0};
435 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000436 (void)apf.convertFromAPInt(GV.IntVal,
437 false,
438 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000439 GV.IntVal = apf.convertToAPInt();
440 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000441 return GV;
442 }
443 case Instruction::SIToFP: {
444 GenericValue GV = getConstantValue(Op0);
445 if (CE->getType() == Type::FloatTy)
446 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000447 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000448 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000449 else if (CE->getType() == Type::X86_FP80Ty) {
450 const uint64_t zero[] = { 0, 0};
451 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000452 (void)apf.convertFromAPInt(GV.IntVal,
453 true,
454 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000455 GV.IntVal = apf.convertToAPInt();
456 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000457 return GV;
458 }
459 case Instruction::FPToUI: // double->APInt conversion handles sign
460 case Instruction::FPToSI: {
461 GenericValue GV = getConstantValue(Op0);
462 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
463 if (Op0->getType() == Type::FloatTy)
464 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000465 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000466 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000467 else if (Op0->getType() == Type::X86_FP80Ty) {
468 APFloat apf = APFloat(GV.IntVal);
469 uint64_t v;
470 (void)apf.convertToInteger(&v, BitWidth,
471 CE->getOpcode()==Instruction::FPToSI,
472 APFloat::rmTowardZero);
473 GV.IntVal = v; // endian?
474 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000475 return GV;
476 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000477 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000478 GenericValue GV = getConstantValue(Op0);
479 uint32_t PtrWidth = TD->getPointerSizeInBits();
480 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
481 return GV;
482 }
483 case Instruction::IntToPtr: {
484 GenericValue GV = getConstantValue(Op0);
485 uint32_t PtrWidth = TD->getPointerSizeInBits();
486 if (PtrWidth != GV.IntVal.getBitWidth())
487 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
488 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
489 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000490 return GV;
491 }
492 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000493 GenericValue GV = getConstantValue(Op0);
494 const Type* DestTy = CE->getType();
495 switch (Op0->getType()->getTypeID()) {
496 default: assert(0 && "Invalid bitcast operand");
497 case Type::IntegerTyID:
498 assert(DestTy->isFloatingPoint() && "invalid bitcast");
499 if (DestTy == Type::FloatTy)
500 GV.FloatVal = GV.IntVal.bitsToFloat();
501 else if (DestTy == Type::DoubleTy)
502 GV.DoubleVal = GV.IntVal.bitsToDouble();
503 break;
504 case Type::FloatTyID:
505 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
506 GV.IntVal.floatToBits(GV.FloatVal);
507 break;
508 case Type::DoubleTyID:
509 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
510 GV.IntVal.doubleToBits(GV.DoubleVal);
511 break;
512 case Type::PointerTyID:
513 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
514 break; // getConstantValue(Op0) above already converted it
515 }
516 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000517 }
Chris Lattner9a231222003-05-14 17:51:49 +0000518 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000519 case Instruction::Sub:
520 case Instruction::Mul:
521 case Instruction::UDiv:
522 case Instruction::SDiv:
523 case Instruction::URem:
524 case Instruction::SRem:
525 case Instruction::And:
526 case Instruction::Or:
527 case Instruction::Xor: {
528 GenericValue LHS = getConstantValue(Op0);
529 GenericValue RHS = getConstantValue(CE->getOperand(1));
530 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000531 switch (CE->getOperand(0)->getType()->getTypeID()) {
532 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000533 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000534 switch (CE->getOpcode()) {
535 default: assert(0 && "Invalid integer opcode");
536 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
537 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
538 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
539 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
540 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
541 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
542 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
543 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
544 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
545 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
546 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000547 break;
548 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000549 switch (CE->getOpcode()) {
550 default: assert(0 && "Invalid float opcode"); abort();
551 case Instruction::Add:
552 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
553 case Instruction::Sub:
554 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
555 case Instruction::Mul:
556 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
557 case Instruction::FDiv:
558 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
559 case Instruction::FRem:
560 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
561 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000562 break;
563 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000564 switch (CE->getOpcode()) {
565 default: assert(0 && "Invalid double opcode"); abort();
566 case Instruction::Add:
567 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
568 case Instruction::Sub:
569 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
570 case Instruction::Mul:
571 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
572 case Instruction::FDiv:
573 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
574 case Instruction::FRem:
575 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
576 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000577 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000578 case Type::X86_FP80TyID:
579 case Type::PPC_FP128TyID:
580 case Type::FP128TyID: {
581 APFloat apfLHS = APFloat(LHS.IntVal);
582 switch (CE->getOpcode()) {
583 default: assert(0 && "Invalid long double opcode"); abort();
584 case Instruction::Add:
585 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
586 GV.IntVal = apfLHS.convertToAPInt();
587 break;
588 case Instruction::Sub:
589 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
590 GV.IntVal = apfLHS.convertToAPInt();
591 break;
592 case Instruction::Mul:
593 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
594 GV.IntVal = apfLHS.convertToAPInt();
595 break;
596 case Instruction::FDiv:
597 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
598 GV.IntVal = apfLHS.convertToAPInt();
599 break;
600 case Instruction::FRem:
601 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
602 GV.IntVal = apfLHS.convertToAPInt();
603 break;
604 }
605 }
606 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000607 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000608 return GV;
609 }
Chris Lattner9a231222003-05-14 17:51:49 +0000610 default:
611 break;
612 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000613 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000614 abort();
615 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000616
Reid Spencerbce30f12007-03-06 22:23:15 +0000617 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000618 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000619 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000620 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000621 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000622 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000623 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000624 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000625 case Type::X86_FP80TyID:
626 case Type::FP128TyID:
627 case Type::PPC_FP128TyID:
628 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
629 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000630 case Type::IntegerTyID:
631 Result.IntVal = cast<ConstantInt>(C)->getValue();
632 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000633 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000634 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000635 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000636 else if (const Function *F = dyn_cast<Function>(C))
637 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
638 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
639 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
640 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000641 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000642 break;
643 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000644 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000645 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000646 }
647 return Result;
648}
649
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000650/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
651/// with the integer held in IntVal.
652static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
653 unsigned StoreBytes) {
654 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
655 uint8_t *Src = (uint8_t *)IntVal.getRawData();
656
657 if (sys::littleEndianHost())
658 // Little-endian host - the source is ordered from LSB to MSB. Order the
659 // destination from LSB to MSB: Do a straight copy.
660 memcpy(Dst, Src, StoreBytes);
661 else {
662 // Big-endian host - the source is an array of 64 bit words ordered from
663 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
664 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
665 while (StoreBytes > sizeof(uint64_t)) {
666 StoreBytes -= sizeof(uint64_t);
667 // May not be aligned so use memcpy.
668 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
669 Src += sizeof(uint64_t);
670 }
671
672 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
673 }
674}
675
Nate Begeman37efe672006-04-22 18:53:45 +0000676/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
677/// is the address of the memory at which to store Val, cast to GenericValue *.
678/// It is not a pointer to a GenericValue containing the address at which to
679/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000680void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000681 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000682 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
683
Reid Spencer8fb0f192007-03-06 03:04:04 +0000684 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000685 case Type::IntegerTyID:
686 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000687 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000688 case Type::FloatTyID:
689 *((float*)Ptr) = Val.FloatVal;
690 break;
691 case Type::DoubleTyID:
692 *((double*)Ptr) = Val.DoubleVal;
693 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000694 case Type::X86_FP80TyID: {
695 uint16_t *Dest = (uint16_t*)Ptr;
696 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
697 // This is endian dependent, but it will only work on x86 anyway.
698 Dest[0] = Src[4];
699 Dest[1] = Src[0];
700 Dest[2] = Src[1];
701 Dest[3] = Src[2];
702 Dest[4] = Src[3];
703 break;
704 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000705 case Type::PointerTyID:
706 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
707 if (StoreBytes != sizeof(PointerTy))
708 memset(Ptr, 0, StoreBytes);
709
Reid Spencer8fb0f192007-03-06 03:04:04 +0000710 *((PointerTy*)Ptr) = Val.PointerVal;
711 break;
712 default:
713 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000714 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000715
716 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
717 // Host and target are different endian - reverse the stored bytes.
718 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
719}
720
721/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
722/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
723static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
724 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
725 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
726
727 if (sys::littleEndianHost())
728 // Little-endian host - the destination must be ordered from LSB to MSB.
729 // The source is ordered from LSB to MSB: Do a straight copy.
730 memcpy(Dst, Src, LoadBytes);
731 else {
732 // Big-endian - the destination is an array of 64 bit words ordered from
733 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
734 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
735 // a word.
736 while (LoadBytes > sizeof(uint64_t)) {
737 LoadBytes -= sizeof(uint64_t);
738 // May not be aligned so use memcpy.
739 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
740 Dst += sizeof(uint64_t);
741 }
742
743 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
744 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000745}
746
Misha Brukman4afac182003-10-10 17:45:12 +0000747/// FIXME: document
748///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000749void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000750 GenericValue *Ptr,
751 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000752 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000753
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000754 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
755 // Host and target are different endian - reverse copy the stored
756 // bytes into a buffer, and load from that.
757 uint8_t *Src = (uint8_t*)Ptr;
758 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
759 std::reverse_copy(Src, Src + LoadBytes, Buf);
760 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000761 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000762
763 switch (Ty->getTypeID()) {
764 case Type::IntegerTyID:
765 // An APInt with all words initially zero.
766 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
767 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
768 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000769 case Type::FloatTyID:
770 Result.FloatVal = *((float*)Ptr);
771 break;
772 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000773 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000774 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000775 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000776 Result.PointerVal = *((PointerTy*)Ptr);
777 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000778 case Type::X86_FP80TyID: {
779 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000780 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000781 uint16_t *p = (uint16_t*)Ptr;
782 union {
783 uint16_t x[8];
784 uint64_t y[2];
785 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000786 x[0] = p[1];
787 x[1] = p[2];
788 x[2] = p[3];
789 x[3] = p[4];
790 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000791 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000792 break;
793 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000794 default:
795 cerr << "Cannot load value of type " << *Ty << "!\n";
796 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000797 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000798}
799
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000800// InitializeMemory - Recursive function to apply a Constant value into the
801// specified memory location...
802//
803void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000804 if (isa<UndefValue>(Init)) {
805 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000806 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000807 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000808 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000809 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
810 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
811 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000812 } else if (isa<ConstantAggregateZero>(Init)) {
813 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
814 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000815 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000816 GenericValue Val = getConstantValue(Init);
817 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
818 return;
819 }
820
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000821 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000822 case Type::ArrayTyID: {
823 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000824 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000825 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000826 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
827 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000828 return;
829 }
830
831 case Type::StructTyID: {
832 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
833 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000834 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000835 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000836 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000837 return;
838 }
839
840 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000841 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000842 assert(0 && "Unknown constant type to initialize memory with!");
843 }
844}
845
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000846/// EmitGlobals - Emit all of the global variables to memory, storing their
847/// addresses into GlobalAddress. This must make sure to copy the contents of
848/// their initializers into the memory.
849///
850void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000851 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000852
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000853 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000854 // to hold them. If there is more than one module, do a prepass over globals
855 // to figure out how the different modules should link together.
856 //
857 std::map<std::pair<std::string, const Type*>,
858 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000859
Chris Lattnerfe854032006-08-16 01:24:12 +0000860 if (Modules.size() != 1) {
861 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
862 Module &M = *Modules[m]->getModule();
863 for (Module::const_global_iterator I = M.global_begin(),
864 E = M.global_end(); I != E; ++I) {
865 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000866 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000867 GV->hasAppendingLinkage() || !GV->hasName())
868 continue;// Ignore external globals and globals with internal linkage.
869
870 const GlobalValue *&GVEntry =
871 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
872
873 // If this is the first time we've seen this global, it is the canonical
874 // version.
875 if (!GVEntry) {
876 GVEntry = GV;
877 continue;
878 }
879
880 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000881 if (GVEntry->hasExternalLinkage() ||
882 GVEntry->hasDLLImportLinkage() ||
883 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000884 continue;
885
886 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
887 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000888 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000889 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000890 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000891 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000892 }
893
894 std::vector<const GlobalValue*> NonCanonicalGlobals;
895 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
896 Module &M = *Modules[m]->getModule();
897 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
898 I != E; ++I) {
899 // In the multi-module case, see what this global maps to.
900 if (!LinkedGlobalsMap.empty()) {
901 if (const GlobalValue *GVEntry =
902 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
903 // If something else is the canonical global, ignore this one.
904 if (GVEntry != &*I) {
905 NonCanonicalGlobals.push_back(I);
906 continue;
907 }
908 }
909 }
910
Reid Spencer5cbf9852007-01-30 20:08:39 +0000911 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000912 // Get the type of the global.
913 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000914
Chris Lattnerfe854032006-08-16 01:24:12 +0000915 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000916 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000917 addGlobalMapping(I, new char[Size]);
918 } else {
919 // External variable reference. Try to use the dynamic loader to
920 // get a pointer to it.
921 if (void *SymAddr =
922 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
923 addGlobalMapping(I, SymAddr);
924 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000925 cerr << "Could not resolve external global address: "
926 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000927 abort();
928 }
929 }
930 }
931
932 // If there are multiple modules, map the non-canonical globals to their
933 // canonical location.
934 if (!NonCanonicalGlobals.empty()) {
935 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
936 const GlobalValue *GV = NonCanonicalGlobals[i];
937 const GlobalValue *CGV =
938 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
939 void *Ptr = getPointerToGlobalIfAvailable(CGV);
940 assert(Ptr && "Canonical global wasn't codegen'd!");
941 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
942 }
943 }
944
Reid Spencera54b7cb2007-01-12 07:05:14 +0000945 // Now that all of the globals are set up in memory, loop through them all
946 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000947 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
948 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000949 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000950 if (!LinkedGlobalsMap.empty()) {
951 if (const GlobalValue *GVEntry =
952 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
953 if (GVEntry != &*I) // Not the canonical variable.
954 continue;
955 }
956 EmitGlobalVariable(I);
957 }
958 }
959 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000960}
961
962// EmitGlobalVariable - This method emits the specified global variable to the
963// address specified in GlobalAddresses, or allocates new memory if it's not
964// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000965void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000966 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000967 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000968
Chris Lattnerc07ed132003-12-20 03:36:47 +0000969 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000970 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000971 if (GA == 0) {
972 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000973 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000974 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000975 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000976
Chris Lattner24b0a182003-12-20 02:45:37 +0000977 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000978 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000979 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000980}