blob: 7d629af83cba5941a345e8b4128e31827598af27 [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"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000022#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000024#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000026#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/raw_ostream.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000028#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000029#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000030#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000031#include <cmath>
32#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000033using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034
Chris Lattner36343732006-12-19 22:43:32 +000035STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000037
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000038ExecutionEngine *(*ExecutionEngine::JITCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000039 std::string *ErrorStr,
40 JITMemoryManager *JMM,
41 CodeGenOpt::Level OptLevel,
Eric Christopher88b5aca2009-11-17 21:58:16 +000042 bool GVsWithCode,
43 CodeModel::Model CMM) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000044ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000045 std::string *ErrorStr) = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000046ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
47
Chris Lattner2fe4bb02006-03-22 06:07:50 +000048
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000049ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000050 : EEState(*this),
51 LazyFunctionCreator(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000052 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000053 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000054 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000055 Modules.push_back(M);
56 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000057}
58
Brian Gaeke8e539482003-09-04 22:57:27 +000059ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000060 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000061 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
62 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000063}
64
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000065char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
66 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +000067 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000068 return new char[GVSize];
69}
70
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000071/// removeModule - Remove a Module from the list of modules.
72bool ExecutionEngine::removeModule(Module *M) {
73 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +000074 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000075 Module *Found = *I;
76 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +000077 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000078 clearGlobalMappingsFromModule(M);
79 return true;
Devang Patel73d0e212007-10-15 19:56:32 +000080 }
81 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000082 return false;
Nate Begeman60789e42009-01-23 19:27:28 +000083}
84
Chris Lattnerfe854032006-08-16 01:24:12 +000085/// FindFunctionNamed - Search all of the active modules to find the one that
86/// defines FnName. This is very slow operation and shouldn't be used for
87/// general code.
88Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
89 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000090 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000091 return F;
92 }
93 return 0;
94}
95
96
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +000097void *ExecutionEngineState::RemoveMapping(
98 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +000099 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000100 void *OldVal;
101 if (I == GlobalAddressMap.end())
102 OldVal = 0;
103 else {
104 OldVal = I->second;
105 GlobalAddressMap.erase(I);
106 }
107
108 GlobalAddressReverseMap.erase(OldVal);
109 return OldVal;
110}
111
Chris Lattnere7fd5532006-05-08 22:00:52 +0000112/// addGlobalMapping - Tell the execution engine that the specified global is
113/// at the specified location. This is used internally as functions are JIT'd
114/// and as global variables are laid out in memory. It can and should also be
115/// used by clients of the EE that want to have an LLVM global overlay
116/// existing data in memory.
117void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
118 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000119
David Greeneae7c59a2010-01-05 01:27:39 +0000120 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000121 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000122 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000123 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
124 CurVal = Addr;
125
126 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000127 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000128 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000129 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000130 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
131 V = GV;
132 }
133}
134
135/// clearAllGlobalMappings - Clear all global mappings and start over again
136/// use in dynamic compilation scenarios when you want to move globals
137void ExecutionEngine::clearAllGlobalMappings() {
138 MutexGuard locked(lock);
139
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000140 EEState.getGlobalAddressMap(locked).clear();
141 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000142}
143
Nate Begemanf049e072008-05-21 16:34:48 +0000144/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
145/// particular module, because it has been removed from the JIT.
146void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
147 MutexGuard locked(lock);
148
149 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000150 EEState.RemoveMapping(locked, FI);
Nate Begemanf049e072008-05-21 16:34:48 +0000151 }
152 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
153 GI != GE; ++GI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000155 }
156}
157
Chris Lattnere7fd5532006-05-08 22:00:52 +0000158/// updateGlobalMapping - Replace an existing mapping for GV with a new
159/// address. This updates both maps as required. If "Addr" is null, the
160/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000161void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000162 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000163
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000164 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000165 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000166
Chris Lattnere7fd5532006-05-08 22:00:52 +0000167 // Deleting from the mapping?
168 if (Addr == 0) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000169 return EEState.RemoveMapping(locked, GV);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000170 }
171
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000172 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000173 void *OldVal = CurVal;
174
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000175 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
176 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000177 CurVal = Addr;
178
179 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000180 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000181 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000182 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000183 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
184 V = GV;
185 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000186 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187}
188
189/// getPointerToGlobalIfAvailable - This returns the address of the specified
190/// global value if it is has already been codegen'd, otherwise it returns null.
191///
192void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
193 MutexGuard locked(lock);
194
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000195 ExecutionEngineState::GlobalAddressMapTy::iterator I =
196 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000197 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000198}
199
Chris Lattner55d86482003-12-31 20:21:04 +0000200/// getGlobalValueAtAddress - Return the LLVM global value object that starts
201/// at the specified address.
202///
203const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000204 MutexGuard locked(lock);
205
Chris Lattner55d86482003-12-31 20:21:04 +0000206 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000207 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000208 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000209 I = EEState.getGlobalAddressMap(locked).begin(),
210 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
211 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
Chris Lattnere7fd5532006-05-08 22:00:52 +0000212 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000213 }
214
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000215 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000216 EEState.getGlobalAddressReverseMap(locked).find(Addr);
217 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000218}
Chris Lattner87f03102003-12-26 06:50:30 +0000219
220// CreateArgv - Turn a vector of strings into a nice argv style array of
221// pointers to null terminated strings.
222//
Owen Anderson1d0be152009-08-13 21:58:54 +0000223static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Chris Lattner87f03102003-12-26 06:50:30 +0000224 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000225 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000226 char *Result = new char[(InputArgv.size()+1)*PtrSize];
227
David Greeneae7c59a2010-01-05 01:27:39 +0000228 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000229 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000230
231 for (unsigned i = 0; i != InputArgv.size(); ++i) {
232 unsigned Size = InputArgv[i].size()+1;
233 char *Dest = new char[Size];
David Greeneae7c59a2010-01-05 01:27:39 +0000234 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000235
Chris Lattner87f03102003-12-26 06:50:30 +0000236 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
237 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000238
Chris Lattner87f03102003-12-26 06:50:30 +0000239 // Endian safe: Result[i] = (PointerTy)Dest;
240 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
241 SBytePtr);
242 }
243
244 // Null terminate it
245 EE->StoreValueToMemory(PTOGV(0),
246 (GenericValue*)(Result+InputArgv.size()*PtrSize),
247 SBytePtr);
248 return Result;
249}
250
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000251
252/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000253/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000254/// value of isDtors.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000255void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
256 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000257 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000258
Chris Lattnerfe854032006-08-16 01:24:12 +0000259 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000260
Evan Cheng18314dc2008-09-30 15:51:21 +0000261 GlobalVariable *GV = module->getNamedGlobal(Name);
262
263 // If this global has internal linkage, or if it has a use, then it must be
264 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
265 // this is the case, don't execute any of the global ctors, __main will do
266 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000267 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000268
269 // Should be an array of '{ int, void ()* }' structs. The first value is
270 // the init priority, which we ignore.
271 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
272 if (!InitList) return;
273 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
274 if (ConstantStruct *CS =
275 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
276 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
277
278 Constant *FP = CS->getOperand(1);
279 if (FP->isNullValue())
280 break; // Found a null terminator, exit.
281
282 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
283 if (CE->isCast())
284 FP = CE->getOperand(0);
285 if (Function *F = dyn_cast<Function>(FP)) {
286 // Execute the ctor/dtor function!
287 runFunction(F, std::vector<GenericValue>());
288 }
289 }
290}
291
292/// runStaticConstructorsDestructors - This method is used to execute all of
293/// the static constructors or destructors for a program, depending on the
294/// value of isDtors.
295void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
296 // Execute global ctors/dtors for each module in the program.
297 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000298 runStaticConstructorsDestructors(Modules[m], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000299}
300
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000301#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000302/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
303static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
304 unsigned PtrSize = EE->getTargetData()->getPointerSize();
305 for (unsigned i = 0; i < PtrSize; ++i)
306 if (*(i + (uint8_t*)Loc))
307 return false;
308 return true;
309}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000310#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000311
Chris Lattner87f03102003-12-26 06:50:30 +0000312/// runFunctionAsMain - This is a helper function which wraps runFunction to
313/// handle the common task of starting up main with the specified argc, argv,
314/// and envp parameters.
315int ExecutionEngine::runFunctionAsMain(Function *Fn,
316 const std::vector<std::string> &argv,
317 const char * const * envp) {
318 std::vector<GenericValue> GVArgs;
319 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000320 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000321
322 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000323 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000324 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000325 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000326 switch (NumArgs) {
327 case 3:
328 if (FTy->getParamType(2) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000329 llvm_report_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000330 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000331 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000332 case 2:
333 if (FTy->getParamType(1) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000334 llvm_report_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000335 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000336 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000337 case 1:
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000338 if (!FTy->getParamType(0)->isInteger(32)) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000339 llvm_report_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000340 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000341 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000342 case 0:
Chris Lattner45f36832009-02-04 17:48:18 +0000343 if (!isa<IntegerType>(FTy->getReturnType()) &&
Benjamin Kramerf0127052010-01-05 13:12:22 +0000344 !FTy->getReturnType()->isVoidTy()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000345 llvm_report_error("Invalid return type of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000346 }
347 break;
348 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000349 llvm_report_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000350 }
351
Chris Lattnerf24d0992004-08-16 01:05:35 +0000352 if (NumArgs) {
353 GVArgs.push_back(GVArgc); // Arg #0 = argc.
354 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000355 // Arg #1 = argv.
356 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000357 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000358 "argv[0] was null after CreateArgv");
359 if (NumArgs > 2) {
360 std::vector<std::string> EnvVars;
361 for (unsigned i = 0; envp[i]; ++i)
362 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000363 // Arg #2 = envp.
364 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000365 }
366 }
367 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000368 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000369}
370
Misha Brukman19684162003-10-16 21:18:05 +0000371/// If possible, create a JIT, unless the caller specifically requests an
372/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000373/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000374///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000375ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000376 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000377 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000378 CodeGenOpt::Level OptLevel,
379 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000380 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000381 .setEngineKind(ForceInterpreter
382 ? EngineKind::Interpreter
383 : EngineKind::JIT)
384 .setErrorStr(ErrorStr)
385 .setOptLevel(OptLevel)
386 .setAllocateGVsWithCode(GVsWithCode)
387 .create();
388}
Brian Gaeke82d82772003-09-03 20:34:19 +0000389
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000390ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000391 // Make sure we can resolve symbols in the program as well. The zero arg
392 // to the function tells DynamicLibrary to load the program, not a library.
393 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
394 return 0;
395
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000396 // If the user specified a memory manager but didn't specify which engine to
397 // create, we assume they only want the JIT, and we fail if they only want
398 // the interpreter.
399 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000400 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000401 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000402 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000403 if (ErrorStr)
404 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000405 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000406 }
407 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000408
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000409 // Unless the interpreter was explicitly selected or the JIT is not linked,
410 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000411 if (WhichEngine & EngineKind::JIT) {
412 if (ExecutionEngine::JITCtor) {
413 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000414 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Eric Christopher88b5aca2009-11-17 21:58:16 +0000415 AllocateGVsWithCode, CMModel);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000416 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000417 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000418 }
419
420 // If we can't make a JIT and we didn't request one specifically, try making
421 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000422 if (WhichEngine & EngineKind::Interpreter) {
423 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000424 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000425 if (ErrorStr)
426 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000427 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000428 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000429
430 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
431 if (ErrorStr)
432 *ErrorStr = "JIT has not been linked in.";
433 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000434 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000435}
436
Misha Brukman4afac182003-10-10 17:45:12 +0000437/// getPointerToGlobal - This returns the address of the specified global
438/// value. This may involve code generation if it's a function.
439///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000440void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000441 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000442 return getPointerToFunction(F);
443
Reid Spenceree448632005-07-12 15:51:55 +0000444 MutexGuard locked(lock);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000445 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen68835dd2006-02-07 05:11:57 +0000446 if (p)
447 return p;
448
449 // Global variable might have been added since interpreter started.
450 if (GlobalVariable *GVar =
451 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
452 EmitGlobalVariable(GVar);
453 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000454 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000455 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000456}
457
Reid Spencer3da59db2006-11-27 01:05:10 +0000458/// This function converts a Constant* into a GenericValue. The interesting
459/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000460/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000461GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000462 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000463 if (isa<UndefValue>(C)) {
464 GenericValue Result;
465 switch (C->getType()->getTypeID()) {
466 case Type::IntegerTyID:
467 case Type::X86_FP80TyID:
468 case Type::FP128TyID:
469 case Type::PPC_FP128TyID:
470 // Although the value is undefined, we still have to construct an APInt
471 // with the correct bit width.
472 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
473 break;
474 default:
475 break;
476 }
477 return Result;
478 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000479
Reid Spencer3da59db2006-11-27 01:05:10 +0000480 // If the value is a ConstantExpr
481 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000482 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000483 switch (CE->getOpcode()) {
484 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000485 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000486 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000487 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000488 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000489 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000490
Reid Spencer8fb0f192007-03-06 03:04:04 +0000491 char* tmp = (char*) Result.PointerVal;
492 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000493 return Result;
494 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000495 case Instruction::Trunc: {
496 GenericValue GV = getConstantValue(Op0);
497 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
498 GV.IntVal = GV.IntVal.trunc(BitWidth);
499 return GV;
500 }
501 case Instruction::ZExt: {
502 GenericValue GV = getConstantValue(Op0);
503 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
504 GV.IntVal = GV.IntVal.zext(BitWidth);
505 return GV;
506 }
507 case Instruction::SExt: {
508 GenericValue GV = getConstantValue(Op0);
509 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
510 GV.IntVal = GV.IntVal.sext(BitWidth);
511 return GV;
512 }
513 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000514 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000515 GenericValue GV = getConstantValue(Op0);
516 GV.FloatVal = float(GV.DoubleVal);
517 return GV;
518 }
519 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000520 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000521 GenericValue GV = getConstantValue(Op0);
522 GV.DoubleVal = double(GV.FloatVal);
523 return GV;
524 }
525 case Instruction::UIToFP: {
526 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000527 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000528 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000529 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000530 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000531 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000532 const uint64_t zero[] = {0, 0};
533 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000534 (void)apf.convertFromAPInt(GV.IntVal,
535 false,
536 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000537 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000538 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000539 return GV;
540 }
541 case Instruction::SIToFP: {
542 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000543 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000544 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000545 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000546 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000547 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000548 const uint64_t zero[] = { 0, 0};
549 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000550 (void)apf.convertFromAPInt(GV.IntVal,
551 true,
552 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000553 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000554 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000555 return GV;
556 }
557 case Instruction::FPToUI: // double->APInt conversion handles sign
558 case Instruction::FPToSI: {
559 GenericValue GV = getConstantValue(Op0);
560 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000561 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000562 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000563 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000564 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000565 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000566 APFloat apf = APFloat(GV.IntVal);
567 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000568 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000569 (void)apf.convertToInteger(&v, BitWidth,
570 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000571 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000572 GV.IntVal = v; // endian?
573 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000574 return GV;
575 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000576 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000577 GenericValue GV = getConstantValue(Op0);
578 uint32_t PtrWidth = TD->getPointerSizeInBits();
579 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
580 return GV;
581 }
582 case Instruction::IntToPtr: {
583 GenericValue GV = getConstantValue(Op0);
584 uint32_t PtrWidth = TD->getPointerSizeInBits();
585 if (PtrWidth != GV.IntVal.getBitWidth())
586 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
587 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
588 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000589 return GV;
590 }
591 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000592 GenericValue GV = getConstantValue(Op0);
593 const Type* DestTy = CE->getType();
594 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000595 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000596 case Type::IntegerTyID:
597 assert(DestTy->isFloatingPoint() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000598 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000599 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000600 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 GV.DoubleVal = GV.IntVal.bitsToDouble();
602 break;
603 case Type::FloatTyID:
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000604 assert(DestTy->isInteger(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 GV.IntVal.floatToBits(GV.FloatVal);
606 break;
607 case Type::DoubleTyID:
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000608 assert(DestTy->isInteger(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 GV.IntVal.doubleToBits(GV.DoubleVal);
610 break;
611 case Type::PointerTyID:
612 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
613 break; // getConstantValue(Op0) above already converted it
614 }
615 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000616 }
Chris Lattner9a231222003-05-14 17:51:49 +0000617 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000618 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000619 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000620 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000621 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000622 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000623 case Instruction::UDiv:
624 case Instruction::SDiv:
625 case Instruction::URem:
626 case Instruction::SRem:
627 case Instruction::And:
628 case Instruction::Or:
629 case Instruction::Xor: {
630 GenericValue LHS = getConstantValue(Op0);
631 GenericValue RHS = getConstantValue(CE->getOperand(1));
632 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000633 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000634 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000635 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000637 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000638 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
639 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
640 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
641 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
642 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
643 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
644 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
645 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
646 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
647 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
648 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000649 break;
650 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000651 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000652 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000653 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000654 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000655 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000657 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000658 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
659 case Instruction::FDiv:
660 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
661 case Instruction::FRem:
662 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
663 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000664 break;
665 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000666 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000667 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000668 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000670 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000672 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
674 case Instruction::FDiv:
675 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
676 case Instruction::FRem:
677 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
678 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000679 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000680 case Type::X86_FP80TyID:
681 case Type::PPC_FP128TyID:
682 case Type::FP128TyID: {
683 APFloat apfLHS = APFloat(LHS.IntVal);
684 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000685 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000686 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000687 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000688 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000689 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000690 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000691 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000692 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000693 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000694 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000695 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000696 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000697 break;
698 case Instruction::FDiv:
699 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000700 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000701 break;
702 case Instruction::FRem:
703 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000704 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000705 break;
706 }
707 }
708 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000709 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000710 return GV;
711 }
Chris Lattner9a231222003-05-14 17:51:49 +0000712 default:
713 break;
714 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000715 std::string msg;
716 raw_string_ostream Msg(msg);
717 Msg << "ConstantExpr not handled: " << *CE;
718 llvm_report_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000719 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000720
Reid Spencerbce30f12007-03-06 22:23:15 +0000721 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000722 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000723 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000724 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000725 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000726 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000727 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000728 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000729 case Type::X86_FP80TyID:
730 case Type::FP128TyID:
731 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000732 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000733 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000734 case Type::IntegerTyID:
735 Result.IntVal = cast<ConstantInt>(C)->getValue();
736 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000737 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000738 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000739 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000740 else if (const Function *F = dyn_cast<Function>(C))
741 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000742 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000743 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000744 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
745 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
746 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000747 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000748 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000749 break;
750 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000751 std::string msg;
752 raw_string_ostream Msg(msg);
753 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
754 llvm_report_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000755 }
756 return Result;
757}
758
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000759/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
760/// with the integer held in IntVal.
761static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
762 unsigned StoreBytes) {
763 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
764 uint8_t *Src = (uint8_t *)IntVal.getRawData();
765
Chris Lattnerb67c9582009-01-22 19:53:00 +0000766 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000767 // Little-endian host - the source is ordered from LSB to MSB. Order the
768 // destination from LSB to MSB: Do a straight copy.
769 memcpy(Dst, Src, StoreBytes);
770 else {
771 // Big-endian host - the source is an array of 64 bit words ordered from
772 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
773 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
774 while (StoreBytes > sizeof(uint64_t)) {
775 StoreBytes -= sizeof(uint64_t);
776 // May not be aligned so use memcpy.
777 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
778 Src += sizeof(uint64_t);
779 }
780
781 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
782 }
783}
784
Nate Begeman37efe672006-04-22 18:53:45 +0000785/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
786/// is the address of the memory at which to store Val, cast to GenericValue *.
787/// It is not a pointer to a GenericValue containing the address at which to
788/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000789void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
790 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000791 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
792
Reid Spencer8fb0f192007-03-06 03:04:04 +0000793 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000794 case Type::IntegerTyID:
795 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000796 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000797 case Type::FloatTyID:
798 *((float*)Ptr) = Val.FloatVal;
799 break;
800 case Type::DoubleTyID:
801 *((double*)Ptr) = Val.DoubleVal;
802 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000803 case Type::X86_FP80TyID:
804 memcpy(Ptr, Val.IntVal.getRawData(), 10);
805 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000806 case Type::PointerTyID:
807 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
808 if (StoreBytes != sizeof(PointerTy))
809 memset(Ptr, 0, StoreBytes);
810
Reid Spencer8fb0f192007-03-06 03:04:04 +0000811 *((PointerTy*)Ptr) = Val.PointerVal;
812 break;
813 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000814 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000815 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000816
Chris Lattnerb67c9582009-01-22 19:53:00 +0000817 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000818 // Host and target are different endian - reverse the stored bytes.
819 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
820}
821
822/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
823/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
824static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
825 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
826 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
827
Chris Lattnerb67c9582009-01-22 19:53:00 +0000828 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000829 // Little-endian host - the destination must be ordered from LSB to MSB.
830 // The source is ordered from LSB to MSB: Do a straight copy.
831 memcpy(Dst, Src, LoadBytes);
832 else {
833 // Big-endian - the destination is an array of 64 bit words ordered from
834 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
835 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
836 // a word.
837 while (LoadBytes > sizeof(uint64_t)) {
838 LoadBytes -= sizeof(uint64_t);
839 // May not be aligned so use memcpy.
840 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
841 Dst += sizeof(uint64_t);
842 }
843
844 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
845 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000846}
847
Misha Brukman4afac182003-10-10 17:45:12 +0000848/// FIXME: document
849///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000850void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000851 GenericValue *Ptr,
852 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000853 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000854
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000855 switch (Ty->getTypeID()) {
856 case Type::IntegerTyID:
857 // An APInt with all words initially zero.
858 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
859 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
860 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000861 case Type::FloatTyID:
862 Result.FloatVal = *((float*)Ptr);
863 break;
864 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000865 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000866 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000867 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000868 Result.PointerVal = *((PointerTy*)Ptr);
869 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000870 case Type::X86_FP80TyID: {
871 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000872 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000873 uint64_t y[2];
874 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000875 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000876 break;
877 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000878 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000879 std::string msg;
880 raw_string_ostream Msg(msg);
881 Msg << "Cannot load value of type " << *Ty << "!";
882 llvm_report_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000883 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000884}
885
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000886// InitializeMemory - Recursive function to apply a Constant value into the
887// specified memory location...
888//
889void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000890 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000891 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000892 if (isa<UndefValue>(Init)) {
893 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000894 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000895 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000896 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000897 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
898 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
899 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000900 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000901 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000902 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000903 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
904 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000905 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000906 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
907 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
908 return;
909 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
910 const StructLayout *SL =
911 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
912 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
913 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
914 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000915 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000916 GenericValue Val = getConstantValue(Init);
917 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
918 return;
919 }
920
David Greeneae7c59a2010-01-05 01:27:39 +0000921 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000922 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000923}
924
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000925/// EmitGlobals - Emit all of the global variables to memory, storing their
926/// addresses into GlobalAddress. This must make sure to copy the contents of
927/// their initializers into the memory.
928///
929void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000930
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000931 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000932 // to hold them. If there is more than one module, do a prepass over globals
933 // to figure out how the different modules should link together.
934 //
935 std::map<std::pair<std::string, const Type*>,
936 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000937
Chris Lattnerfe854032006-08-16 01:24:12 +0000938 if (Modules.size() != 1) {
939 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000940 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000941 for (Module::const_global_iterator I = M.global_begin(),
942 E = M.global_end(); I != E; ++I) {
943 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000944 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000945 GV->hasAppendingLinkage() || !GV->hasName())
946 continue;// Ignore external globals and globals with internal linkage.
947
948 const GlobalValue *&GVEntry =
949 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
950
951 // If this is the first time we've seen this global, it is the canonical
952 // version.
953 if (!GVEntry) {
954 GVEntry = GV;
955 continue;
956 }
957
958 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000959 if (GVEntry->hasExternalLinkage() ||
960 GVEntry->hasDLLImportLinkage() ||
961 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000962 continue;
963
964 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000965 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000966 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000967 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000968 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000969 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000970 }
971
972 std::vector<const GlobalValue*> NonCanonicalGlobals;
973 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000974 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000975 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
976 I != E; ++I) {
977 // In the multi-module case, see what this global maps to.
978 if (!LinkedGlobalsMap.empty()) {
979 if (const GlobalValue *GVEntry =
980 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
981 // If something else is the canonical global, ignore this one.
982 if (GVEntry != &*I) {
983 NonCanonicalGlobals.push_back(I);
984 continue;
985 }
986 }
987 }
988
Reid Spencer5cbf9852007-01-30 20:08:39 +0000989 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000990 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +0000991 } else {
992 // External variable reference. Try to use the dynamic loader to
993 // get a pointer to it.
994 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +0000995 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +0000996 addGlobalMapping(I, SymAddr);
997 else {
Torok Edwin31e24662009-07-07 17:32:34 +0000998 llvm_report_error("Could not resolve external global address: "
999 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001000 }
1001 }
1002 }
1003
1004 // If there are multiple modules, map the non-canonical globals to their
1005 // canonical location.
1006 if (!NonCanonicalGlobals.empty()) {
1007 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1008 const GlobalValue *GV = NonCanonicalGlobals[i];
1009 const GlobalValue *CGV =
1010 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1011 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1012 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001013 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001014 }
1015 }
1016
Reid Spencera54b7cb2007-01-12 07:05:14 +00001017 // Now that all of the globals are set up in memory, loop through them all
1018 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001019 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1020 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001021 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001022 if (!LinkedGlobalsMap.empty()) {
1023 if (const GlobalValue *GVEntry =
1024 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1025 if (GVEntry != &*I) // Not the canonical variable.
1026 continue;
1027 }
1028 EmitGlobalVariable(I);
1029 }
1030 }
1031 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001032}
1033
1034// EmitGlobalVariable - This method emits the specified global variable to the
1035// address specified in GlobalAddresses, or allocates new memory if it's not
1036// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001037void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001038 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001039
Chris Lattner24b0a182003-12-20 02:45:37 +00001040 if (GA == 0) {
1041 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001042 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001043 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001044 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001045
1046 // Don't initialize if it's thread local, let the client do it.
1047 if (!GV->isThreadLocal())
1048 InitializeMemory(GV->getInitializer(), GA);
1049
1050 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001051 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001052 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001053 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001054}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001055
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001056ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1057 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001058}
1059
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001060sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1061 ExecutionEngineState *EES) {
1062 return &EES->EE.lock;
1063}
1064void ExecutionEngineState::AddressMapConfig::onDelete(
1065 ExecutionEngineState *EES, const GlobalValue *Old) {
1066 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1067 EES->GlobalAddressReverseMap.erase(OldVal);
1068}
1069
1070void ExecutionEngineState::AddressMapConfig::onRAUW(
1071 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001072 assert(false && "The ExecutionEngine doesn't know how to handle a"
1073 " RAUW on a value it has a global mapping for.");
1074}