blob: fe6b811ea65b7faed883744eba904ac8559e998e [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"
Jeff Cohen2b7d7b52007-03-12 17:57:00 +000029#include <math.h>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000030using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000031
Chris Lattner36343732006-12-19 22:43:32 +000032STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
33STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034
Chris Lattner2fe4bb02006-03-22 06:07:50 +000035ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
37
Chris Lattnerd958a5a2007-10-22 02:50:12 +000038ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000039 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000040 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000041 assert(P && "ModuleProvider is null?");
42}
43
Brian Gaeke8e539482003-09-04 22:57:27 +000044ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000045 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000046 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
47 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000048}
49
Devang Patel73d0e212007-10-15 19:56:32 +000050/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
51/// Release module from ModuleProvider.
52Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
53 std::string *ErrInfo) {
54 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
55 E = Modules.end(); I != E; ++I) {
56 ModuleProvider *MP = *I;
57 if (MP == P) {
58 Modules.erase(I);
59 return MP->releaseModule(ErrInfo);
60 }
61 }
62 return NULL;
63}
64
Chris Lattnerfe854032006-08-16 01:24:12 +000065/// FindFunctionNamed - Search all of the active modules to find the one that
66/// defines FnName. This is very slow operation and shouldn't be used for
67/// general code.
68Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
69 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000070 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000071 return F;
72 }
73 return 0;
74}
75
76
Chris Lattnere7fd5532006-05-08 22:00:52 +000077/// addGlobalMapping - Tell the execution engine that the specified global is
78/// at the specified location. This is used internally as functions are JIT'd
79/// and as global variables are laid out in memory. It can and should also be
80/// used by clients of the EE that want to have an LLVM global overlay
81/// existing data in memory.
82void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
83 MutexGuard locked(lock);
84
85 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
86 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
87 CurVal = Addr;
88
89 // If we are using the reverse mapping, add it too
90 if (!state.getGlobalAddressReverseMap(locked).empty()) {
91 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
92 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
93 V = GV;
94 }
95}
96
97/// clearAllGlobalMappings - Clear all global mappings and start over again
98/// use in dynamic compilation scenarios when you want to move globals
99void ExecutionEngine::clearAllGlobalMappings() {
100 MutexGuard locked(lock);
101
102 state.getGlobalAddressMap(locked).clear();
103 state.getGlobalAddressReverseMap(locked).clear();
104}
105
106/// updateGlobalMapping - Replace an existing mapping for GV with a new
107/// address. This updates both maps as required. If "Addr" is null, the
108/// entry for the global is removed from the mappings.
109void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
110 MutexGuard locked(lock);
111
112 // Deleting from the mapping?
113 if (Addr == 0) {
114 state.getGlobalAddressMap(locked).erase(GV);
115 if (!state.getGlobalAddressReverseMap(locked).empty())
116 state.getGlobalAddressReverseMap(locked).erase(Addr);
117 return;
118 }
119
120 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
121 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
122 state.getGlobalAddressReverseMap(locked).erase(CurVal);
123 CurVal = Addr;
124
125 // If we are using the reverse mapping, add it too
126 if (!state.getGlobalAddressReverseMap(locked).empty()) {
127 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
128 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
129 V = GV;
130 }
131}
132
133/// getPointerToGlobalIfAvailable - This returns the address of the specified
134/// global value if it is has already been codegen'd, otherwise it returns null.
135///
136void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
137 MutexGuard locked(lock);
138
139 std::map<const GlobalValue*, void*>::iterator I =
140 state.getGlobalAddressMap(locked).find(GV);
141 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
142}
143
Chris Lattner55d86482003-12-31 20:21:04 +0000144/// getGlobalValueAtAddress - Return the LLVM global value object that starts
145/// at the specified address.
146///
147const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000148 MutexGuard locked(lock);
149
Chris Lattner55d86482003-12-31 20:21:04 +0000150 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000151 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000152 for (std::map<const GlobalValue*, void *>::iterator
153 I = state.getGlobalAddressMap(locked).begin(),
154 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
155 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
156 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000157 }
158
159 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000160 state.getGlobalAddressReverseMap(locked).find(Addr);
161 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000162}
Chris Lattner87f03102003-12-26 06:50:30 +0000163
164// CreateArgv - Turn a vector of strings into a nice argv style array of
165// pointers to null terminated strings.
166//
167static void *CreateArgv(ExecutionEngine *EE,
168 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000169 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000170 char *Result = new char[(InputArgv.size()+1)*PtrSize];
171
Bill Wendling480f0932006-11-27 23:54:50 +0000172 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000173 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000174
175 for (unsigned i = 0; i != InputArgv.size(); ++i) {
176 unsigned Size = InputArgv[i].size()+1;
177 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000178 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000179
Chris Lattner87f03102003-12-26 06:50:30 +0000180 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
181 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000182
Chris Lattner87f03102003-12-26 06:50:30 +0000183 // Endian safe: Result[i] = (PointerTy)Dest;
184 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
185 SBytePtr);
186 }
187
188 // Null terminate it
189 EE->StoreValueToMemory(PTOGV(0),
190 (GenericValue*)(Result+InputArgv.size()*PtrSize),
191 SBytePtr);
192 return Result;
193}
194
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000195
196/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000197/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000198/// value of isDtors.
199void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
200 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000201
Chris Lattnerfe854032006-08-16 01:24:12 +0000202 // Execute global ctors/dtors for each module in the program.
203 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
204 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
205
206 // If this global has internal linkage, or if it has a use, then it must be
207 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
208 // this is the case, don't execute any of the global ctors, __main will do
209 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000210 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000211
212 // Should be an array of '{ int, void ()* }' structs. The first value is
213 // the init priority, which we ignore.
214 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
215 if (!InitList) continue;
216 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
217 if (ConstantStruct *CS =
218 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
219 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000220
Chris Lattnerfe854032006-08-16 01:24:12 +0000221 Constant *FP = CS->getOperand(1);
222 if (FP->isNullValue())
223 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000224
Chris Lattnerfe854032006-08-16 01:24:12 +0000225 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000227 FP = CE->getOperand(0);
228 if (Function *F = dyn_cast<Function>(FP)) {
229 // Execute the ctor/dtor function!
230 runFunction(F, std::vector<GenericValue>());
231 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000232 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000233 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000234}
235
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000236/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
237static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
238 unsigned PtrSize = EE->getTargetData()->getPointerSize();
239 for (unsigned i = 0; i < PtrSize; ++i)
240 if (*(i + (uint8_t*)Loc))
241 return false;
242 return true;
243}
244
Chris Lattner87f03102003-12-26 06:50:30 +0000245/// runFunctionAsMain - This is a helper function which wraps runFunction to
246/// handle the common task of starting up main with the specified argc, argv,
247/// and envp parameters.
248int ExecutionEngine::runFunctionAsMain(Function *Fn,
249 const std::vector<std::string> &argv,
250 const char * const * envp) {
251 std::vector<GenericValue> GVArgs;
252 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000253 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000254
255 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000256 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000257 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000258 const Type* PPInt8Ty =
259 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000260 switch (NumArgs) {
261 case 3:
262 if (FTy->getParamType(2) != PPInt8Ty) {
263 cerr << "Invalid type for third argument of main() supplied\n";
264 abort();
265 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000266 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000267 case 2:
268 if (FTy->getParamType(1) != PPInt8Ty) {
269 cerr << "Invalid type for second argument of main() supplied\n";
270 abort();
271 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000272 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000273 case 1:
274 if (FTy->getParamType(0) != Type::Int32Ty) {
275 cerr << "Invalid type for first argument of main() supplied\n";
276 abort();
277 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000278 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000279 case 0:
280 if (FTy->getReturnType() != Type::Int32Ty &&
281 FTy->getReturnType() != Type::VoidTy) {
282 cerr << "Invalid return type of main() supplied\n";
283 abort();
284 }
285 break;
286 default:
287 cerr << "Invalid number of arguments of main() supplied\n";
288 abort();
289 }
290
Chris Lattnerf24d0992004-08-16 01:05:35 +0000291 if (NumArgs) {
292 GVArgs.push_back(GVArgc); // Arg #0 = argc.
293 if (NumArgs > 1) {
294 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000295 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000296 "argv[0] was null after CreateArgv");
297 if (NumArgs > 2) {
298 std::vector<std::string> EnvVars;
299 for (unsigned i = 0; envp[i]; ++i)
300 EnvVars.push_back(envp[i]);
301 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
302 }
303 }
304 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000305 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000306}
307
Misha Brukman19684162003-10-16 21:18:05 +0000308/// If possible, create a JIT, unless the caller specifically requests an
309/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000310/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000311///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000313 bool ForceInterpreter,
314 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000315 ExecutionEngine *EE = 0;
316
Chris Lattner73011782003-12-28 09:44:37 +0000317 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000318 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000319 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000320
321 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000322 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000323 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000324
Chris Lattner726c1ef2006-03-23 05:22:51 +0000325 if (EE) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000326 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000327 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattnerc6185032007-10-21 22:58:11 +0000328 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
329 delete EE;
330 return 0;
Chris Lattner6f3ada52006-05-14 19:01:55 +0000331 }
Chris Lattner726c1ef2006-03-23 05:22:51 +0000332 }
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000333
Brian Gaeke82d82772003-09-03 20:34:19 +0000334 return EE;
335}
336
Chris Lattner8b5295b2007-10-21 22:57:11 +0000337ExecutionEngine *ExecutionEngine::create(Module *M) {
338 return create(new ExistingModuleProvider(M));
339}
340
Misha Brukman4afac182003-10-10 17:45:12 +0000341/// getPointerToGlobal - This returns the address of the specified global
342/// value. This may involve code generation if it's a function.
343///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000344void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000345 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000346 return getPointerToFunction(F);
347
Reid Spenceree448632005-07-12 15:51:55 +0000348 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000349 void *p = state.getGlobalAddressMap(locked)[GV];
350 if (p)
351 return p;
352
353 // Global variable might have been added since interpreter started.
354 if (GlobalVariable *GVar =
355 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
356 EmitGlobalVariable(GVar);
357 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000358 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000359 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000360}
361
Reid Spencer3da59db2006-11-27 01:05:10 +0000362/// This function converts a Constant* into a GenericValue. The interesting
363/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000364/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000365GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000366 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000367 if (isa<UndefValue>(C))
368 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000369
Reid Spencer3da59db2006-11-27 01:05:10 +0000370 // If the value is a ConstantExpr
371 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000372 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000373 switch (CE->getOpcode()) {
374 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000375 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000376 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000377 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000378 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000379 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000380
Reid Spencer8fb0f192007-03-06 03:04:04 +0000381 char* tmp = (char*) Result.PointerVal;
382 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000383 return Result;
384 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000385 case Instruction::Trunc: {
386 GenericValue GV = getConstantValue(Op0);
387 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
388 GV.IntVal = GV.IntVal.trunc(BitWidth);
389 return GV;
390 }
391 case Instruction::ZExt: {
392 GenericValue GV = getConstantValue(Op0);
393 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
394 GV.IntVal = GV.IntVal.zext(BitWidth);
395 return GV;
396 }
397 case Instruction::SExt: {
398 GenericValue GV = getConstantValue(Op0);
399 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
400 GV.IntVal = GV.IntVal.sext(BitWidth);
401 return GV;
402 }
403 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000404 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000405 GenericValue GV = getConstantValue(Op0);
406 GV.FloatVal = float(GV.DoubleVal);
407 return GV;
408 }
409 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000410 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000411 GenericValue GV = getConstantValue(Op0);
412 GV.DoubleVal = double(GV.FloatVal);
413 return GV;
414 }
415 case Instruction::UIToFP: {
416 GenericValue GV = getConstantValue(Op0);
417 if (CE->getType() == Type::FloatTy)
418 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000419 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000420 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000421 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000422 const uint64_t zero[] = {0, 0};
423 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000424 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000425 GV.IntVal.getBitWidth(), false,
Dale Johannesen88216af2007-09-30 18:19:03 +0000426 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000427 GV.IntVal = apf.convertToAPInt();
428 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000429 return GV;
430 }
431 case Instruction::SIToFP: {
432 GenericValue GV = getConstantValue(Op0);
433 if (CE->getType() == Type::FloatTy)
434 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000435 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000436 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000437 else if (CE->getType() == Type::X86_FP80Ty) {
438 const uint64_t zero[] = { 0, 0};
439 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000440 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000441 GV.IntVal.getBitWidth(), true,
Dale Johannesen88216af2007-09-30 18:19:03 +0000442 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000443 GV.IntVal = apf.convertToAPInt();
444 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000445 return GV;
446 }
447 case Instruction::FPToUI: // double->APInt conversion handles sign
448 case Instruction::FPToSI: {
449 GenericValue GV = getConstantValue(Op0);
450 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
451 if (Op0->getType() == Type::FloatTy)
452 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000453 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000454 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000455 else if (Op0->getType() == Type::X86_FP80Ty) {
456 APFloat apf = APFloat(GV.IntVal);
457 uint64_t v;
458 (void)apf.convertToInteger(&v, BitWidth,
459 CE->getOpcode()==Instruction::FPToSI,
460 APFloat::rmTowardZero);
461 GV.IntVal = v; // endian?
462 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000463 return GV;
464 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000465 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000466 GenericValue GV = getConstantValue(Op0);
467 uint32_t PtrWidth = TD->getPointerSizeInBits();
468 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
469 return GV;
470 }
471 case Instruction::IntToPtr: {
472 GenericValue GV = getConstantValue(Op0);
473 uint32_t PtrWidth = TD->getPointerSizeInBits();
474 if (PtrWidth != GV.IntVal.getBitWidth())
475 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
476 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
477 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 return GV;
479 }
480 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000481 GenericValue GV = getConstantValue(Op0);
482 const Type* DestTy = CE->getType();
483 switch (Op0->getType()->getTypeID()) {
484 default: assert(0 && "Invalid bitcast operand");
485 case Type::IntegerTyID:
486 assert(DestTy->isFloatingPoint() && "invalid bitcast");
487 if (DestTy == Type::FloatTy)
488 GV.FloatVal = GV.IntVal.bitsToFloat();
489 else if (DestTy == Type::DoubleTy)
490 GV.DoubleVal = GV.IntVal.bitsToDouble();
491 break;
492 case Type::FloatTyID:
493 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
494 GV.IntVal.floatToBits(GV.FloatVal);
495 break;
496 case Type::DoubleTyID:
497 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
498 GV.IntVal.doubleToBits(GV.DoubleVal);
499 break;
500 case Type::PointerTyID:
501 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
502 break; // getConstantValue(Op0) above already converted it
503 }
504 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000505 }
Chris Lattner9a231222003-05-14 17:51:49 +0000506 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000507 case Instruction::Sub:
508 case Instruction::Mul:
509 case Instruction::UDiv:
510 case Instruction::SDiv:
511 case Instruction::URem:
512 case Instruction::SRem:
513 case Instruction::And:
514 case Instruction::Or:
515 case Instruction::Xor: {
516 GenericValue LHS = getConstantValue(Op0);
517 GenericValue RHS = getConstantValue(CE->getOperand(1));
518 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000519 switch (CE->getOperand(0)->getType()->getTypeID()) {
520 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000521 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000522 switch (CE->getOpcode()) {
523 default: assert(0 && "Invalid integer opcode");
524 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
525 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
526 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
527 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
528 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
529 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
530 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
531 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
532 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
533 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
534 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000535 break;
536 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000537 switch (CE->getOpcode()) {
538 default: assert(0 && "Invalid float opcode"); abort();
539 case Instruction::Add:
540 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
541 case Instruction::Sub:
542 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
543 case Instruction::Mul:
544 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
545 case Instruction::FDiv:
546 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
547 case Instruction::FRem:
548 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
549 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000550 break;
551 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000552 switch (CE->getOpcode()) {
553 default: assert(0 && "Invalid double opcode"); abort();
554 case Instruction::Add:
555 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
556 case Instruction::Sub:
557 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
558 case Instruction::Mul:
559 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
560 case Instruction::FDiv:
561 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
562 case Instruction::FRem:
563 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
564 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000565 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000566 case Type::X86_FP80TyID:
567 case Type::PPC_FP128TyID:
568 case Type::FP128TyID: {
569 APFloat apfLHS = APFloat(LHS.IntVal);
570 switch (CE->getOpcode()) {
571 default: assert(0 && "Invalid long double opcode"); abort();
572 case Instruction::Add:
573 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
574 GV.IntVal = apfLHS.convertToAPInt();
575 break;
576 case Instruction::Sub:
577 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
578 GV.IntVal = apfLHS.convertToAPInt();
579 break;
580 case Instruction::Mul:
581 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
582 GV.IntVal = apfLHS.convertToAPInt();
583 break;
584 case Instruction::FDiv:
585 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
586 GV.IntVal = apfLHS.convertToAPInt();
587 break;
588 case Instruction::FRem:
589 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
590 GV.IntVal = apfLHS.convertToAPInt();
591 break;
592 }
593 }
594 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000595 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000596 return GV;
597 }
Chris Lattner9a231222003-05-14 17:51:49 +0000598 default:
599 break;
600 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000602 abort();
603 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000604
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000606 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000607 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000608 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000609 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000610 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000611 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000612 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000613 case Type::X86_FP80TyID:
614 case Type::FP128TyID:
615 case Type::PPC_FP128TyID:
616 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
617 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000618 case Type::IntegerTyID:
619 Result.IntVal = cast<ConstantInt>(C)->getValue();
620 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000621 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000622 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000623 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000624 else if (const Function *F = dyn_cast<Function>(C))
625 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
626 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
627 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
628 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000629 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000630 break;
631 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000632 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000633 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000634 }
635 return Result;
636}
637
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000638/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
639/// with the integer held in IntVal.
640static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
641 unsigned StoreBytes) {
642 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
643 uint8_t *Src = (uint8_t *)IntVal.getRawData();
644
645 if (sys::littleEndianHost())
646 // Little-endian host - the source is ordered from LSB to MSB. Order the
647 // destination from LSB to MSB: Do a straight copy.
648 memcpy(Dst, Src, StoreBytes);
649 else {
650 // Big-endian host - the source is an array of 64 bit words ordered from
651 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
652 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
653 while (StoreBytes > sizeof(uint64_t)) {
654 StoreBytes -= sizeof(uint64_t);
655 // May not be aligned so use memcpy.
656 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
657 Src += sizeof(uint64_t);
658 }
659
660 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
661 }
662}
663
Nate Begeman37efe672006-04-22 18:53:45 +0000664/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
665/// is the address of the memory at which to store Val, cast to GenericValue *.
666/// It is not a pointer to a GenericValue containing the address at which to
667/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000668void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000669 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000670 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
671
Reid Spencer8fb0f192007-03-06 03:04:04 +0000672 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000673 case Type::IntegerTyID:
674 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000675 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000676 case Type::FloatTyID:
677 *((float*)Ptr) = Val.FloatVal;
678 break;
679 case Type::DoubleTyID:
680 *((double*)Ptr) = Val.DoubleVal;
681 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000682 case Type::X86_FP80TyID: {
683 uint16_t *Dest = (uint16_t*)Ptr;
684 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
685 // This is endian dependent, but it will only work on x86 anyway.
686 Dest[0] = Src[4];
687 Dest[1] = Src[0];
688 Dest[2] = Src[1];
689 Dest[3] = Src[2];
690 Dest[4] = Src[3];
691 break;
692 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000693 case Type::PointerTyID:
694 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
695 if (StoreBytes != sizeof(PointerTy))
696 memset(Ptr, 0, StoreBytes);
697
Reid Spencer8fb0f192007-03-06 03:04:04 +0000698 *((PointerTy*)Ptr) = Val.PointerVal;
699 break;
700 default:
701 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000702 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000703
704 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
705 // Host and target are different endian - reverse the stored bytes.
706 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
707}
708
709/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
710/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
711static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
712 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
713 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
714
715 if (sys::littleEndianHost())
716 // Little-endian host - the destination must be ordered from LSB to MSB.
717 // The source is ordered from LSB to MSB: Do a straight copy.
718 memcpy(Dst, Src, LoadBytes);
719 else {
720 // Big-endian - the destination is an array of 64 bit words ordered from
721 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
722 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
723 // a word.
724 while (LoadBytes > sizeof(uint64_t)) {
725 LoadBytes -= sizeof(uint64_t);
726 // May not be aligned so use memcpy.
727 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
728 Dst += sizeof(uint64_t);
729 }
730
731 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
732 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000733}
734
Misha Brukman4afac182003-10-10 17:45:12 +0000735/// FIXME: document
736///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000737void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Reid Spencerf0f09a92007-03-03 08:36:29 +0000738 GenericValue *Ptr,
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000739 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000740 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000741
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000742 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
743 // Host and target are different endian - reverse copy the stored
744 // bytes into a buffer, and load from that.
745 uint8_t *Src = (uint8_t*)Ptr;
746 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
747 std::reverse_copy(Src, Src + LoadBytes, Buf);
748 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000749 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000750
751 switch (Ty->getTypeID()) {
752 case Type::IntegerTyID:
753 // An APInt with all words initially zero.
754 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
755 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
756 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000757 case Type::FloatTyID:
758 Result.FloatVal = *((float*)Ptr);
759 break;
760 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000761 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000762 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000763 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000764 Result.PointerVal = *((PointerTy*)Ptr);
765 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000766 case Type::X86_FP80TyID: {
767 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000768 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000769 uint16_t *p = (uint16_t*)Ptr;
770 union {
771 uint16_t x[8];
772 uint64_t y[2];
773 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000774 x[0] = p[1];
775 x[1] = p[2];
776 x[2] = p[3];
777 x[3] = p[4];
778 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000779 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000780 break;
781 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000782 default:
783 cerr << "Cannot load value of type " << *Ty << "!\n";
784 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000785 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000786}
787
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000788// InitializeMemory - Recursive function to apply a Constant value into the
789// specified memory location...
790//
791void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000792 if (isa<UndefValue>(Init)) {
793 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000794 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000795 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000796 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000797 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
798 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
799 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000800 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000801 GenericValue Val = getConstantValue(Init);
802 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
803 return;
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000804 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands514ab342007-11-01 20:53:16 +0000805 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000806 return;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000807 }
808
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000809 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000810 case Type::ArrayTyID: {
811 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000812 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000813 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000814 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
815 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000816 return;
817 }
818
819 case Type::StructTyID: {
820 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
821 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000822 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000823 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000824 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000825 return;
826 }
827
828 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000829 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000830 assert(0 && "Unknown constant type to initialize memory with!");
831 }
832}
833
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000834/// EmitGlobals - Emit all of the global variables to memory, storing their
835/// addresses into GlobalAddress. This must make sure to copy the contents of
836/// their initializers into the memory.
837///
838void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000839 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000840
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000841 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000842 // to hold them. If there is more than one module, do a prepass over globals
843 // to figure out how the different modules should link together.
844 //
845 std::map<std::pair<std::string, const Type*>,
846 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000847
Chris Lattnerfe854032006-08-16 01:24:12 +0000848 if (Modules.size() != 1) {
849 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
850 Module &M = *Modules[m]->getModule();
851 for (Module::const_global_iterator I = M.global_begin(),
852 E = M.global_end(); I != E; ++I) {
853 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000854 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000855 GV->hasAppendingLinkage() || !GV->hasName())
856 continue;// Ignore external globals and globals with internal linkage.
857
858 const GlobalValue *&GVEntry =
859 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
860
861 // If this is the first time we've seen this global, it is the canonical
862 // version.
863 if (!GVEntry) {
864 GVEntry = GV;
865 continue;
866 }
867
868 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000869 if (GVEntry->hasExternalLinkage() ||
870 GVEntry->hasDLLImportLinkage() ||
871 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000872 continue;
873
874 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
875 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000876 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000877 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000878 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000879 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000880 }
881
882 std::vector<const GlobalValue*> NonCanonicalGlobals;
883 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
884 Module &M = *Modules[m]->getModule();
885 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
886 I != E; ++I) {
887 // In the multi-module case, see what this global maps to.
888 if (!LinkedGlobalsMap.empty()) {
889 if (const GlobalValue *GVEntry =
890 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
891 // If something else is the canonical global, ignore this one.
892 if (GVEntry != &*I) {
893 NonCanonicalGlobals.push_back(I);
894 continue;
895 }
896 }
897 }
898
Reid Spencer5cbf9852007-01-30 20:08:39 +0000899 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000900 // Get the type of the global.
901 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000902
Chris Lattnerfe854032006-08-16 01:24:12 +0000903 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000904 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000905 addGlobalMapping(I, new char[Size]);
906 } else {
907 // External variable reference. Try to use the dynamic loader to
908 // get a pointer to it.
909 if (void *SymAddr =
910 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
911 addGlobalMapping(I, SymAddr);
912 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000913 cerr << "Could not resolve external global address: "
914 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000915 abort();
916 }
917 }
918 }
919
920 // If there are multiple modules, map the non-canonical globals to their
921 // canonical location.
922 if (!NonCanonicalGlobals.empty()) {
923 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
924 const GlobalValue *GV = NonCanonicalGlobals[i];
925 const GlobalValue *CGV =
926 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
927 void *Ptr = getPointerToGlobalIfAvailable(CGV);
928 assert(Ptr && "Canonical global wasn't codegen'd!");
929 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
930 }
931 }
932
Reid Spencera54b7cb2007-01-12 07:05:14 +0000933 // Now that all of the globals are set up in memory, loop through them all
934 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000935 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
936 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000937 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000938 if (!LinkedGlobalsMap.empty()) {
939 if (const GlobalValue *GVEntry =
940 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
941 if (GVEntry != &*I) // Not the canonical variable.
942 continue;
943 }
944 EmitGlobalVariable(I);
945 }
946 }
947 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000948}
949
950// EmitGlobalVariable - This method emits the specified global variable to the
951// address specified in GlobalAddresses, or allocates new memory if it's not
952// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000953void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000954 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000955 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000956
Chris Lattnerc07ed132003-12-20 03:36:47 +0000957 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000958 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000959 if (GA == 0) {
960 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000961 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000962 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000963 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000964
Chris Lattner24b0a182003-12-20 02:45:37 +0000965 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000966 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000967 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000968}