blob: 981ef107a5ec2c307dd86b8b49a8d835c770c141 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Misha Brukman19684162003-10-16 21:18:05 +000021#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000024#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
26#include "llvm/Target/TargetData.h"
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000027using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000028
Chris Lattner36343732006-12-19 22:43:32 +000029STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000031
Chris Lattner2fe4bb02006-03-22 06:07:50 +000032ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
33ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
34
Chris Lattnerfe854032006-08-16 01:24:12 +000035ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000036 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000037 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000038 assert(P && "ModuleProvider is null?");
39}
40
Chris Lattnerfe854032006-08-16 01:24:12 +000041ExecutionEngine::ExecutionEngine(Module *M) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000042 LazyCompilationDisabled = false;
Misha Brukman05701572003-10-17 18:31:59 +000043 assert(M && "Module is null?");
Chris Lattnerfe854032006-08-16 01:24:12 +000044 Modules.push_back(new ExistingModuleProvider(M));
Misha Brukman19684162003-10-16 21:18:05 +000045}
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
Chris Lattnerfe854032006-08-16 01:24:12 +000053/// FindFunctionNamed - Search all of the active modules to find the one that
54/// defines FnName. This is very slow operation and shouldn't be used for
55/// general code.
56Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
57 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000058 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000059 return F;
60 }
61 return 0;
62}
63
64
Chris Lattnere7fd5532006-05-08 22:00:52 +000065/// addGlobalMapping - Tell the execution engine that the specified global is
66/// at the specified location. This is used internally as functions are JIT'd
67/// and as global variables are laid out in memory. It can and should also be
68/// used by clients of the EE that want to have an LLVM global overlay
69/// existing data in memory.
70void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
71 MutexGuard locked(lock);
72
73 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
74 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
75 CurVal = Addr;
76
77 // If we are using the reverse mapping, add it too
78 if (!state.getGlobalAddressReverseMap(locked).empty()) {
79 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
80 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
81 V = GV;
82 }
83}
84
85/// clearAllGlobalMappings - Clear all global mappings and start over again
86/// use in dynamic compilation scenarios when you want to move globals
87void ExecutionEngine::clearAllGlobalMappings() {
88 MutexGuard locked(lock);
89
90 state.getGlobalAddressMap(locked).clear();
91 state.getGlobalAddressReverseMap(locked).clear();
92}
93
94/// updateGlobalMapping - Replace an existing mapping for GV with a new
95/// address. This updates both maps as required. If "Addr" is null, the
96/// entry for the global is removed from the mappings.
97void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
98 MutexGuard locked(lock);
99
100 // Deleting from the mapping?
101 if (Addr == 0) {
102 state.getGlobalAddressMap(locked).erase(GV);
103 if (!state.getGlobalAddressReverseMap(locked).empty())
104 state.getGlobalAddressReverseMap(locked).erase(Addr);
105 return;
106 }
107
108 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
109 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
110 state.getGlobalAddressReverseMap(locked).erase(CurVal);
111 CurVal = Addr;
112
113 // If we are using the reverse mapping, add it too
114 if (!state.getGlobalAddressReverseMap(locked).empty()) {
115 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
116 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
117 V = GV;
118 }
119}
120
121/// getPointerToGlobalIfAvailable - This returns the address of the specified
122/// global value if it is has already been codegen'd, otherwise it returns null.
123///
124void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
125 MutexGuard locked(lock);
126
127 std::map<const GlobalValue*, void*>::iterator I =
128 state.getGlobalAddressMap(locked).find(GV);
129 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
130}
131
Chris Lattner55d86482003-12-31 20:21:04 +0000132/// getGlobalValueAtAddress - Return the LLVM global value object that starts
133/// at the specified address.
134///
135const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000136 MutexGuard locked(lock);
137
Chris Lattner55d86482003-12-31 20:21:04 +0000138 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000139 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000140 for (std::map<const GlobalValue*, void *>::iterator
141 I = state.getGlobalAddressMap(locked).begin(),
142 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
143 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
144 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000145 }
146
147 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000148 state.getGlobalAddressReverseMap(locked).find(Addr);
149 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000150}
Chris Lattner87f03102003-12-26 06:50:30 +0000151
152// CreateArgv - Turn a vector of strings into a nice argv style array of
153// pointers to null terminated strings.
154//
155static void *CreateArgv(ExecutionEngine *EE,
156 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000157 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000158 char *Result = new char[(InputArgv.size()+1)*PtrSize];
159
Bill Wendling480f0932006-11-27 23:54:50 +0000160 DOUT << "ARGV = " << (void*)Result << "\n";
Reid Spencere49661b2006-12-31 05:51:36 +0000161 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000162
163 for (unsigned i = 0; i != InputArgv.size(); ++i) {
164 unsigned Size = InputArgv[i].size()+1;
165 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000166 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000167
Chris Lattner87f03102003-12-26 06:50:30 +0000168 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
169 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000170
Chris Lattner87f03102003-12-26 06:50:30 +0000171 // Endian safe: Result[i] = (PointerTy)Dest;
172 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
173 SBytePtr);
174 }
175
176 // Null terminate it
177 EE->StoreValueToMemory(PTOGV(0),
178 (GenericValue*)(Result+InputArgv.size()*PtrSize),
179 SBytePtr);
180 return Result;
181}
182
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000183
184/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000185/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000186/// value of isDtors.
187void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
188 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000189
Chris Lattnerfe854032006-08-16 01:24:12 +0000190 // Execute global ctors/dtors for each module in the program.
191 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
192 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
193
194 // If this global has internal linkage, or if it has a use, then it must be
195 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
196 // this is the case, don't execute any of the global ctors, __main will do
197 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000198 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000199
200 // Should be an array of '{ int, void ()* }' structs. The first value is
201 // the init priority, which we ignore.
202 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
203 if (!InitList) continue;
204 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
205 if (ConstantStruct *CS =
206 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
207 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000208
Chris Lattnerfe854032006-08-16 01:24:12 +0000209 Constant *FP = CS->getOperand(1);
210 if (FP->isNullValue())
211 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000212
Chris Lattnerfe854032006-08-16 01:24:12 +0000213 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000214 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000215 FP = CE->getOperand(0);
216 if (Function *F = dyn_cast<Function>(FP)) {
217 // Execute the ctor/dtor function!
218 runFunction(F, std::vector<GenericValue>());
219 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000220 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000221 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000222}
223
Chris Lattner87f03102003-12-26 06:50:30 +0000224/// runFunctionAsMain - This is a helper function which wraps runFunction to
225/// handle the common task of starting up main with the specified argc, argv,
226/// and envp parameters.
227int ExecutionEngine::runFunctionAsMain(Function *Fn,
228 const std::vector<std::string> &argv,
229 const char * const * envp) {
230 std::vector<GenericValue> GVArgs;
231 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000232 GVArgc.IntVal = APInt(32, argv.size());
Chris Lattnerf24d0992004-08-16 01:05:35 +0000233 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
234 if (NumArgs) {
235 GVArgs.push_back(GVArgc); // Arg #0 = argc.
236 if (NumArgs > 1) {
237 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
238 assert(((char **)GVTOP(GVArgs[1]))[0] &&
239 "argv[0] was null after CreateArgv");
240 if (NumArgs > 2) {
241 std::vector<std::string> EnvVars;
242 for (unsigned i = 0; envp[i]; ++i)
243 EnvVars.push_back(envp[i]);
244 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
245 }
246 }
247 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000248 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000249}
250
Misha Brukman19684162003-10-16 21:18:05 +0000251/// If possible, create a JIT, unless the caller specifically requests an
252/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000253/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000254///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000255ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000256 bool ForceInterpreter,
257 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000258 ExecutionEngine *EE = 0;
259
Chris Lattner73011782003-12-28 09:44:37 +0000260 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000261 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000262 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000263
264 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000265 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000266 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000267
Chris Lattner726c1ef2006-03-23 05:22:51 +0000268 if (EE) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000269 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000270 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattner6f3ada52006-05-14 19:01:55 +0000271 try {
272 sys::DynamicLibrary::LoadLibraryPermanently(0);
273 } catch (...) {
274 }
Chris Lattner726c1ef2006-03-23 05:22:51 +0000275 }
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000276
Brian Gaeke82d82772003-09-03 20:34:19 +0000277 return EE;
278}
279
Misha Brukman4afac182003-10-10 17:45:12 +0000280/// getPointerToGlobal - This returns the address of the specified global
281/// value. This may involve code generation if it's a function.
282///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000283void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000284 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000285 return getPointerToFunction(F);
286
Reid Spenceree448632005-07-12 15:51:55 +0000287 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000288 void *p = state.getGlobalAddressMap(locked)[GV];
289 if (p)
290 return p;
291
292 // Global variable might have been added since interpreter started.
293 if (GlobalVariable *GVar =
294 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
295 EmitGlobalVariable(GVar);
296 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000297 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000298 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000299}
300
Reid Spencer3da59db2006-11-27 01:05:10 +0000301/// This function converts a Constant* into a GenericValue. The interesting
302/// part is if C is a ConstantExpr.
303/// @brief Get a GenericValue for a Constnat*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000304GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000305 // Declare the result as garbage.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000306 GenericValue Result;
Reid Spencer3da59db2006-11-27 01:05:10 +0000307
308 // If its undefined, return the garbage.
Chris Lattner6f335f92004-10-26 05:35:14 +0000309 if (isa<UndefValue>(C)) return Result;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000310
Reid Spencer3da59db2006-11-27 01:05:10 +0000311 // If the value is a ConstantExpr
312 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000313 switch (CE->getOpcode()) {
314 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000315 // Compute the index
Chris Lattner9a231222003-05-14 17:51:49 +0000316 Result = getConstantValue(CE->getOperand(0));
Chris Lattner829621c2007-02-10 20:35:22 +0000317 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000318 uint64_t Offset =
Chris Lattner829621c2007-02-10 20:35:22 +0000319 TD->getIndexedOffset(CE->getOperand(0)->getType(),
320 &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000321
Reid Spencer8fb0f192007-03-06 03:04:04 +0000322 char* tmp = (char*) Result.PointerVal;
323 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000324 return Result;
325 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000326 case Instruction::Trunc:
327 case Instruction::ZExt:
328 case Instruction::SExt:
329 case Instruction::FPTrunc:
330 case Instruction::FPExt:
331 case Instruction::UIToFP:
332 case Instruction::SIToFP:
333 case Instruction::FPToUI:
334 case Instruction::FPToSI:
335 break;
336 case Instruction::PtrToInt: {
Chris Lattner9a231222003-05-14 17:51:49 +0000337 Constant *Op = CE->getOperand(0);
Chris Lattner7d1bd332004-03-16 08:38:56 +0000338 GenericValue GV = getConstantValue(Op);
Reid Spencer3da59db2006-11-27 01:05:10 +0000339 return GV;
340 }
341 case Instruction::BitCast: {
342 // Bit casts are no-ops but we can only return the GV of the operand if
343 // they are the same basic type (pointer->pointer, packed->packed, etc.)
344 Constant *Op = CE->getOperand(0);
345 GenericValue GV = getConstantValue(Op);
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000346 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
Chris Lattner7d1bd332004-03-16 08:38:56 +0000347 return GV;
Reid Spencer3da59db2006-11-27 01:05:10 +0000348 break;
349 }
350 case Instruction::IntToPtr: {
351 // IntToPtr casts are just so special. Cast to intptr_t first.
352 Constant *Op = CE->getOperand(0);
353 GenericValue GV = getConstantValue(Op);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000354 return PTOGV((void*)(uintptr_t)GV.IntVal.getZExtValue());
Chris Lattner9a231222003-05-14 17:51:49 +0000355 break;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000356 }
Chris Lattner9a231222003-05-14 17:51:49 +0000357 case Instruction::Add:
Chris Lattner5f90cb82004-07-11 08:01:11 +0000358 switch (CE->getOperand(0)->getType()->getTypeID()) {
359 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000360 case Type::IntegerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000361 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal + \
362 getConstantValue(CE->getOperand(1)).IntVal;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000363 break;
364 case Type::FloatTyID:
365 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
366 getConstantValue(CE->getOperand(1)).FloatVal;
367 break;
368 case Type::DoubleTyID:
369 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
370 getConstantValue(CE->getOperand(1)).DoubleVal;
371 break;
372 }
Chris Lattner9a231222003-05-14 17:51:49 +0000373 return Result;
Chris Lattner9a231222003-05-14 17:51:49 +0000374 default:
375 break;
376 }
Bill Wendlinge8156192006-12-07 01:30:32 +0000377 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000378 abort();
379 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000380
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000381 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000382 case Type::FloatTyID:
383 Result.FloatVal = (float)cast<ConstantFP>(C)->getValue();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000384 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000385 case Type::DoubleTyID:
386 Result.DoubleVal = (double)cast<ConstantFP>(C)->getValue();
387 break;
388 case Type::IntegerTyID:
389 Result.IntVal = cast<ConstantInt>(C)->getValue();
390 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000391 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000392 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000393 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000394 else if (const Function *F = dyn_cast<Function>(C))
395 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
396 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
397 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
398 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000399 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000400 break;
401 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000402 cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000403 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000404 }
405 return Result;
406}
407
Nate Begeman37efe672006-04-22 18:53:45 +0000408/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
409/// is the address of the memory at which to store Val, cast to GenericValue *.
410/// It is not a pointer to a GenericValue containing the address at which to
411/// store Val.
Misha Brukman4afac182003-10-10 17:45:12 +0000412///
Reid Spencer415c1f72007-03-06 05:03:16 +0000413void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000414 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000415 switch (Ty->getTypeID()) {
416 case Type::IntegerTyID: {
417 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
418 GenericValue TmpVal = Val;
419 if (BitWidth <= 8)
420 *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
421 else if (BitWidth <= 16) {
422 *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
423 } else if (BitWidth <= 32) {
424 *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
425 } else if (BitWidth <= 64) {
Reid Spencer415c1f72007-03-06 05:03:16 +0000426 *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
Reid Spencer8fb0f192007-03-06 03:04:04 +0000427 } else {
428 uint64_t *Dest = (uint64_t*)Ptr;
429 const uint64_t *Src = Val.IntVal.getRawData();
430 for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
431 Dest[i] = Src[i];
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000433 break;
434 }
435 case Type::FloatTyID:
436 *((float*)Ptr) = Val.FloatVal;
437 break;
438 case Type::DoubleTyID:
439 *((double*)Ptr) = Val.DoubleVal;
440 break;
441 case Type::PointerTyID:
442 *((PointerTy*)Ptr) = Val.PointerVal;
443 break;
444 default:
445 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000446 }
447}
448
Misha Brukman4afac182003-10-10 17:45:12 +0000449/// FIXME: document
450///
Reid Spencerf0f09a92007-03-03 08:36:29 +0000451void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
452 GenericValue *Ptr,
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000453 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000454 switch (Ty->getTypeID()) {
455 case Type::IntegerTyID: {
456 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
457 if (BitWidth <= 8)
458 Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
459 else if (BitWidth <= 16) {
460 Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
461 } else if (BitWidth <= 32) {
462 Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
463 } else if (BitWidth <= 64) {
464 Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
465 } else
466 Result.IntVal = APInt(BitWidth, BitWidth/64, (uint64_t*)Ptr);
467 break;
468 }
469 case Type::FloatTyID:
470 Result.FloatVal = *((float*)Ptr);
471 break;
472 case Type::DoubleTyID:
473 Result.DoubleVal = *((double*)Ptr);
474 break;
475 case Type::PointerTyID:
476 Result.PointerVal = *((PointerTy*)Ptr);
477 break;
478 default:
479 cerr << "Cannot load value of type " << *Ty << "!\n";
480 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000481 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000482}
483
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000484// InitializeMemory - Recursive function to apply a Constant value into the
485// specified memory location...
486//
487void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000488 if (isa<UndefValue>(Init)) {
489 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000490 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000491 unsigned ElementSize =
Owen Andersona69571c2006-05-03 01:29:57 +0000492 getTargetData()->getTypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000493 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
494 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
495 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000496 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000497 GenericValue Val = getConstantValue(Init);
498 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
499 return;
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000500 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersona69571c2006-05-03 01:29:57 +0000501 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000502 return;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000503 }
504
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000505 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000506 case Type::ArrayTyID: {
507 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000508 unsigned ElementSize =
Owen Andersona69571c2006-05-03 01:29:57 +0000509 getTargetData()->getTypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000510 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
511 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000512 return;
513 }
514
515 case Type::StructTyID: {
516 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
517 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000518 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000519 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000520 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000521 return;
522 }
523
524 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000525 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000526 assert(0 && "Unknown constant type to initialize memory with!");
527 }
528}
529
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000530/// EmitGlobals - Emit all of the global variables to memory, storing their
531/// addresses into GlobalAddress. This must make sure to copy the contents of
532/// their initializers into the memory.
533///
534void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000535 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000536
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000537 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000538 // to hold them. If there is more than one module, do a prepass over globals
539 // to figure out how the different modules should link together.
540 //
541 std::map<std::pair<std::string, const Type*>,
542 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000543
Chris Lattnerfe854032006-08-16 01:24:12 +0000544 if (Modules.size() != 1) {
545 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
546 Module &M = *Modules[m]->getModule();
547 for (Module::const_global_iterator I = M.global_begin(),
548 E = M.global_end(); I != E; ++I) {
549 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000550 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000551 GV->hasAppendingLinkage() || !GV->hasName())
552 continue;// Ignore external globals and globals with internal linkage.
553
554 const GlobalValue *&GVEntry =
555 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
556
557 // If this is the first time we've seen this global, it is the canonical
558 // version.
559 if (!GVEntry) {
560 GVEntry = GV;
561 continue;
562 }
563
564 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000565 if (GVEntry->hasExternalLinkage() ||
566 GVEntry->hasDLLImportLinkage() ||
567 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000568 continue;
569
570 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
571 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000572 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000573 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000574 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000575 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000576 }
577
578 std::vector<const GlobalValue*> NonCanonicalGlobals;
579 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
580 Module &M = *Modules[m]->getModule();
581 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
582 I != E; ++I) {
583 // In the multi-module case, see what this global maps to.
584 if (!LinkedGlobalsMap.empty()) {
585 if (const GlobalValue *GVEntry =
586 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
587 // If something else is the canonical global, ignore this one.
588 if (GVEntry != &*I) {
589 NonCanonicalGlobals.push_back(I);
590 continue;
591 }
592 }
593 }
594
Reid Spencer5cbf9852007-01-30 20:08:39 +0000595 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000596 // Get the type of the global.
597 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000598
Chris Lattnerfe854032006-08-16 01:24:12 +0000599 // Allocate some memory for it!
600 unsigned Size = TD->getTypeSize(Ty);
601 addGlobalMapping(I, new char[Size]);
602 } else {
603 // External variable reference. Try to use the dynamic loader to
604 // get a pointer to it.
605 if (void *SymAddr =
606 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
607 addGlobalMapping(I, SymAddr);
608 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000609 cerr << "Could not resolve external global address: "
610 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000611 abort();
612 }
613 }
614 }
615
616 // If there are multiple modules, map the non-canonical globals to their
617 // canonical location.
618 if (!NonCanonicalGlobals.empty()) {
619 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
620 const GlobalValue *GV = NonCanonicalGlobals[i];
621 const GlobalValue *CGV =
622 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
623 void *Ptr = getPointerToGlobalIfAvailable(CGV);
624 assert(Ptr && "Canonical global wasn't codegen'd!");
625 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
626 }
627 }
628
Reid Spencera54b7cb2007-01-12 07:05:14 +0000629 // Now that all of the globals are set up in memory, loop through them all
630 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000631 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
632 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000633 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000634 if (!LinkedGlobalsMap.empty()) {
635 if (const GlobalValue *GVEntry =
636 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
637 if (GVEntry != &*I) // Not the canonical variable.
638 continue;
639 }
640 EmitGlobalVariable(I);
641 }
642 }
643 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000644}
645
646// EmitGlobalVariable - This method emits the specified global variable to the
647// address specified in GlobalAddresses, or allocates new memory if it's not
648// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000649void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000650 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000651 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000652
Chris Lattnerc07ed132003-12-20 03:36:47 +0000653 const Type *ElTy = GV->getType()->getElementType();
Owen Andersona69571c2006-05-03 01:29:57 +0000654 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000655 if (GA == 0) {
656 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000657 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000658 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000659 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000660
Chris Lattner24b0a182003-12-20 02:45:37 +0000661 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000662 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000663 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000664}