blob: d4af85997317529b4e204e8c81341ccae370a340 [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 *ExecutionEngine::create(Module *M) {
391 return EngineBuilder(M).create();
392}
393
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000394ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000395 // Make sure we can resolve symbols in the program as well. The zero arg
396 // to the function tells DynamicLibrary to load the program, not a library.
397 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
398 return 0;
399
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000400 // If the user specified a memory manager but didn't specify which engine to
401 // create, we assume they only want the JIT, and we fail if they only want
402 // the interpreter.
403 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000404 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000405 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000406 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000407 if (ErrorStr)
408 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000409 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000410 }
411 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000412
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000413 // Unless the interpreter was explicitly selected or the JIT is not linked,
414 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000415 if (WhichEngine & EngineKind::JIT) {
416 if (ExecutionEngine::JITCtor) {
417 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000418 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Eric Christopher88b5aca2009-11-17 21:58:16 +0000419 AllocateGVsWithCode, CMModel);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000420 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000421 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000422 }
423
424 // If we can't make a JIT and we didn't request one specifically, try making
425 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000426 if (WhichEngine & EngineKind::Interpreter) {
427 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000428 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000429 if (ErrorStr)
430 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000431 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000432 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000433
434 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
435 if (ErrorStr)
436 *ErrorStr = "JIT has not been linked in.";
437 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000438 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000439}
440
Misha Brukman4afac182003-10-10 17:45:12 +0000441/// getPointerToGlobal - This returns the address of the specified global
442/// value. This may involve code generation if it's a function.
443///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000444void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000445 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000446 return getPointerToFunction(F);
447
Reid Spenceree448632005-07-12 15:51:55 +0000448 MutexGuard locked(lock);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000449 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen68835dd2006-02-07 05:11:57 +0000450 if (p)
451 return p;
452
453 // Global variable might have been added since interpreter started.
454 if (GlobalVariable *GVar =
455 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
456 EmitGlobalVariable(GVar);
457 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000458 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000459 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000460}
461
Reid Spencer3da59db2006-11-27 01:05:10 +0000462/// This function converts a Constant* into a GenericValue. The interesting
463/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000464/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000465GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000467 if (isa<UndefValue>(C)) {
468 GenericValue Result;
469 switch (C->getType()->getTypeID()) {
470 case Type::IntegerTyID:
471 case Type::X86_FP80TyID:
472 case Type::FP128TyID:
473 case Type::PPC_FP128TyID:
474 // Although the value is undefined, we still have to construct an APInt
475 // with the correct bit width.
476 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
477 break;
478 default:
479 break;
480 }
481 return Result;
482 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000483
Reid Spencer3da59db2006-11-27 01:05:10 +0000484 // If the value is a ConstantExpr
485 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000486 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000487 switch (CE->getOpcode()) {
488 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000489 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000490 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000491 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000492 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000493 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000494
Reid Spencer8fb0f192007-03-06 03:04:04 +0000495 char* tmp = (char*) Result.PointerVal;
496 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000497 return Result;
498 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000499 case Instruction::Trunc: {
500 GenericValue GV = getConstantValue(Op0);
501 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
502 GV.IntVal = GV.IntVal.trunc(BitWidth);
503 return GV;
504 }
505 case Instruction::ZExt: {
506 GenericValue GV = getConstantValue(Op0);
507 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
508 GV.IntVal = GV.IntVal.zext(BitWidth);
509 return GV;
510 }
511 case Instruction::SExt: {
512 GenericValue GV = getConstantValue(Op0);
513 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
514 GV.IntVal = GV.IntVal.sext(BitWidth);
515 return GV;
516 }
517 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000518 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000519 GenericValue GV = getConstantValue(Op0);
520 GV.FloatVal = float(GV.DoubleVal);
521 return GV;
522 }
523 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000524 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000525 GenericValue GV = getConstantValue(Op0);
526 GV.DoubleVal = double(GV.FloatVal);
527 return GV;
528 }
529 case Instruction::UIToFP: {
530 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000531 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000532 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000533 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000534 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000535 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000536 const uint64_t zero[] = {0, 0};
537 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000538 (void)apf.convertFromAPInt(GV.IntVal,
539 false,
540 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000541 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000542 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000543 return GV;
544 }
545 case Instruction::SIToFP: {
546 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000547 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000548 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000549 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000550 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000551 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000552 const uint64_t zero[] = { 0, 0};
553 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000554 (void)apf.convertFromAPInt(GV.IntVal,
555 true,
556 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000557 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000558 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000559 return GV;
560 }
561 case Instruction::FPToUI: // double->APInt conversion handles sign
562 case Instruction::FPToSI: {
563 GenericValue GV = getConstantValue(Op0);
564 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000565 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000566 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000567 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000568 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000569 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000570 APFloat apf = APFloat(GV.IntVal);
571 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000572 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000573 (void)apf.convertToInteger(&v, BitWidth,
574 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000575 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000576 GV.IntVal = v; // endian?
577 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000578 return GV;
579 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000580 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000581 GenericValue GV = getConstantValue(Op0);
582 uint32_t PtrWidth = TD->getPointerSizeInBits();
583 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
584 return GV;
585 }
586 case Instruction::IntToPtr: {
587 GenericValue GV = getConstantValue(Op0);
588 uint32_t PtrWidth = TD->getPointerSizeInBits();
589 if (PtrWidth != GV.IntVal.getBitWidth())
590 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
591 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
592 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000593 return GV;
594 }
595 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000596 GenericValue GV = getConstantValue(Op0);
597 const Type* DestTy = CE->getType();
598 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000599 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000600 case Type::IntegerTyID:
601 assert(DestTy->isFloatingPoint() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000602 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000603 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000604 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 GV.DoubleVal = GV.IntVal.bitsToDouble();
606 break;
607 case Type::FloatTyID:
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000608 assert(DestTy->isInteger(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 GV.IntVal.floatToBits(GV.FloatVal);
610 break;
611 case Type::DoubleTyID:
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000612 assert(DestTy->isInteger(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000613 GV.IntVal.doubleToBits(GV.DoubleVal);
614 break;
615 case Type::PointerTyID:
616 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
617 break; // getConstantValue(Op0) above already converted it
618 }
619 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000620 }
Chris Lattner9a231222003-05-14 17:51:49 +0000621 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000622 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000623 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000624 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000626 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000627 case Instruction::UDiv:
628 case Instruction::SDiv:
629 case Instruction::URem:
630 case Instruction::SRem:
631 case Instruction::And:
632 case Instruction::Or:
633 case Instruction::Xor: {
634 GenericValue LHS = getConstantValue(Op0);
635 GenericValue RHS = getConstantValue(CE->getOperand(1));
636 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000637 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000638 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000639 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000641 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000642 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
643 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
644 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
645 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
646 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
647 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
648 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
649 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
650 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
651 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
652 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000653 break;
654 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000655 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000656 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000657 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000658 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000659 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000660 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000661 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000662 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
663 case Instruction::FDiv:
664 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
665 case Instruction::FRem:
666 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
667 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000668 break;
669 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000670 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000671 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000672 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000674 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000675 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000676 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000677 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
678 case Instruction::FDiv:
679 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
680 case Instruction::FRem:
681 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
682 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000683 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000684 case Type::X86_FP80TyID:
685 case Type::PPC_FP128TyID:
686 case Type::FP128TyID: {
687 APFloat apfLHS = APFloat(LHS.IntVal);
688 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000689 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000690 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000691 apfLHS.add(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::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000695 apfLHS.subtract(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;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000698 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000699 apfLHS.multiply(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::FDiv:
703 apfLHS.divide(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 case Instruction::FRem:
707 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000708 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000709 break;
710 }
711 }
712 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000713 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000714 return GV;
715 }
Chris Lattner9a231222003-05-14 17:51:49 +0000716 default:
717 break;
718 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000719 std::string msg;
720 raw_string_ostream Msg(msg);
721 Msg << "ConstantExpr not handled: " << *CE;
722 llvm_report_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000723 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000724
Reid Spencerbce30f12007-03-06 22:23:15 +0000725 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000726 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000727 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000728 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000729 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000730 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000731 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000732 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000733 case Type::X86_FP80TyID:
734 case Type::FP128TyID:
735 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000736 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000737 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000738 case Type::IntegerTyID:
739 Result.IntVal = cast<ConstantInt>(C)->getValue();
740 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000741 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000742 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000743 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000744 else if (const Function *F = dyn_cast<Function>(C))
745 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000746 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000747 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000748 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
749 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
750 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000751 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000752 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000753 break;
754 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000755 std::string msg;
756 raw_string_ostream Msg(msg);
757 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
758 llvm_report_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000759 }
760 return Result;
761}
762
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000763/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
764/// with the integer held in IntVal.
765static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
766 unsigned StoreBytes) {
767 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
768 uint8_t *Src = (uint8_t *)IntVal.getRawData();
769
Chris Lattnerb67c9582009-01-22 19:53:00 +0000770 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000771 // Little-endian host - the source is ordered from LSB to MSB. Order the
772 // destination from LSB to MSB: Do a straight copy.
773 memcpy(Dst, Src, StoreBytes);
774 else {
775 // Big-endian host - the source is an array of 64 bit words ordered from
776 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
777 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
778 while (StoreBytes > sizeof(uint64_t)) {
779 StoreBytes -= sizeof(uint64_t);
780 // May not be aligned so use memcpy.
781 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
782 Src += sizeof(uint64_t);
783 }
784
785 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
786 }
787}
788
Nate Begeman37efe672006-04-22 18:53:45 +0000789/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
790/// is the address of the memory at which to store Val, cast to GenericValue *.
791/// It is not a pointer to a GenericValue containing the address at which to
792/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000793void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
794 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000795 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
796
Reid Spencer8fb0f192007-03-06 03:04:04 +0000797 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000798 case Type::IntegerTyID:
799 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000800 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000801 case Type::FloatTyID:
802 *((float*)Ptr) = Val.FloatVal;
803 break;
804 case Type::DoubleTyID:
805 *((double*)Ptr) = Val.DoubleVal;
806 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000807 case Type::X86_FP80TyID:
808 memcpy(Ptr, Val.IntVal.getRawData(), 10);
809 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000810 case Type::PointerTyID:
811 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
812 if (StoreBytes != sizeof(PointerTy))
813 memset(Ptr, 0, StoreBytes);
814
Reid Spencer8fb0f192007-03-06 03:04:04 +0000815 *((PointerTy*)Ptr) = Val.PointerVal;
816 break;
817 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000818 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000819 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000820
Chris Lattnerb67c9582009-01-22 19:53:00 +0000821 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000822 // Host and target are different endian - reverse the stored bytes.
823 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
824}
825
826/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
827/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
828static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
829 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
830 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
831
Chris Lattnerb67c9582009-01-22 19:53:00 +0000832 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000833 // Little-endian host - the destination must be ordered from LSB to MSB.
834 // The source is ordered from LSB to MSB: Do a straight copy.
835 memcpy(Dst, Src, LoadBytes);
836 else {
837 // Big-endian - the destination is an array of 64 bit words ordered from
838 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
839 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
840 // a word.
841 while (LoadBytes > sizeof(uint64_t)) {
842 LoadBytes -= sizeof(uint64_t);
843 // May not be aligned so use memcpy.
844 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
845 Dst += sizeof(uint64_t);
846 }
847
848 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
849 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000850}
851
Misha Brukman4afac182003-10-10 17:45:12 +0000852/// FIXME: document
853///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000854void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000855 GenericValue *Ptr,
856 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000857 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000858
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000859 switch (Ty->getTypeID()) {
860 case Type::IntegerTyID:
861 // An APInt with all words initially zero.
862 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
863 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
864 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000865 case Type::FloatTyID:
866 Result.FloatVal = *((float*)Ptr);
867 break;
868 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000869 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000870 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000871 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000872 Result.PointerVal = *((PointerTy*)Ptr);
873 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000874 case Type::X86_FP80TyID: {
875 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000876 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000877 uint64_t y[2];
878 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000879 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000880 break;
881 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000882 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000883 std::string msg;
884 raw_string_ostream Msg(msg);
885 Msg << "Cannot load value of type " << *Ty << "!";
886 llvm_report_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000887 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000888}
889
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000890// InitializeMemory - Recursive function to apply a Constant value into the
891// specified memory location...
892//
893void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000894 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000895 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000896 if (isa<UndefValue>(Init)) {
897 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000898 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000899 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000900 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000901 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
902 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
903 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000904 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000905 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000906 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000907 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
908 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000909 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000910 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
911 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
912 return;
913 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
914 const StructLayout *SL =
915 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
916 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
917 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
918 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000919 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000920 GenericValue Val = getConstantValue(Init);
921 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
922 return;
923 }
924
David Greeneae7c59a2010-01-05 01:27:39 +0000925 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000926 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000927}
928
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000929/// EmitGlobals - Emit all of the global variables to memory, storing their
930/// addresses into GlobalAddress. This must make sure to copy the contents of
931/// their initializers into the memory.
932///
933void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000934
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000935 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000936 // to hold them. If there is more than one module, do a prepass over globals
937 // to figure out how the different modules should link together.
938 //
939 std::map<std::pair<std::string, const Type*>,
940 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000941
Chris Lattnerfe854032006-08-16 01:24:12 +0000942 if (Modules.size() != 1) {
943 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000944 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000945 for (Module::const_global_iterator I = M.global_begin(),
946 E = M.global_end(); I != E; ++I) {
947 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000948 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000949 GV->hasAppendingLinkage() || !GV->hasName())
950 continue;// Ignore external globals and globals with internal linkage.
951
952 const GlobalValue *&GVEntry =
953 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
954
955 // If this is the first time we've seen this global, it is the canonical
956 // version.
957 if (!GVEntry) {
958 GVEntry = GV;
959 continue;
960 }
961
962 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000963 if (GVEntry->hasExternalLinkage() ||
964 GVEntry->hasDLLImportLinkage() ||
965 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000966 continue;
967
968 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000969 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000970 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000971 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000972 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000973 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000974 }
975
976 std::vector<const GlobalValue*> NonCanonicalGlobals;
977 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000978 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000979 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
980 I != E; ++I) {
981 // In the multi-module case, see what this global maps to.
982 if (!LinkedGlobalsMap.empty()) {
983 if (const GlobalValue *GVEntry =
984 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
985 // If something else is the canonical global, ignore this one.
986 if (GVEntry != &*I) {
987 NonCanonicalGlobals.push_back(I);
988 continue;
989 }
990 }
991 }
992
Reid Spencer5cbf9852007-01-30 20:08:39 +0000993 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000994 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +0000995 } else {
996 // External variable reference. Try to use the dynamic loader to
997 // get a pointer to it.
998 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +0000999 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001000 addGlobalMapping(I, SymAddr);
1001 else {
Torok Edwin31e24662009-07-07 17:32:34 +00001002 llvm_report_error("Could not resolve external global address: "
1003 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001004 }
1005 }
1006 }
1007
1008 // If there are multiple modules, map the non-canonical globals to their
1009 // canonical location.
1010 if (!NonCanonicalGlobals.empty()) {
1011 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1012 const GlobalValue *GV = NonCanonicalGlobals[i];
1013 const GlobalValue *CGV =
1014 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1015 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1016 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001017 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001018 }
1019 }
1020
Reid Spencera54b7cb2007-01-12 07:05:14 +00001021 // Now that all of the globals are set up in memory, loop through them all
1022 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001023 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1024 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001025 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001026 if (!LinkedGlobalsMap.empty()) {
1027 if (const GlobalValue *GVEntry =
1028 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1029 if (GVEntry != &*I) // Not the canonical variable.
1030 continue;
1031 }
1032 EmitGlobalVariable(I);
1033 }
1034 }
1035 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001036}
1037
1038// EmitGlobalVariable - This method emits the specified global variable to the
1039// address specified in GlobalAddresses, or allocates new memory if it's not
1040// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001041void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001042 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001043
Chris Lattner24b0a182003-12-20 02:45:37 +00001044 if (GA == 0) {
1045 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001046 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001047 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001048 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001049
1050 // Don't initialize if it's thread local, let the client do it.
1051 if (!GV->isThreadLocal())
1052 InitializeMemory(GV->getInitializer(), GA);
1053
1054 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001055 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001056 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001057 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001058}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001059
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001060ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1061 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001062}
1063
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001064sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1065 ExecutionEngineState *EES) {
1066 return &EES->EE.lock;
1067}
1068void ExecutionEngineState::AddressMapConfig::onDelete(
1069 ExecutionEngineState *EES, const GlobalValue *Old) {
1070 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1071 EES->GlobalAddressReverseMap.erase(OldVal);
1072}
1073
1074void ExecutionEngineState::AddressMapConfig::onRAUW(
1075 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001076 assert(false && "The ExecutionEngine doesn't know how to handle a"
1077 " RAUW on a value it has a global mapping for.");
1078}