blob: 6db3ef963ac62ce5d7ad0c3287ac75611e03c5f2 [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 Yasskin46882612010-02-05 16:19:36 +000038ExecutionEngine *(*ExecutionEngine::JITCtor)(
39 Module *M,
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
42 CodeGenOpt::Level OptLevel,
43 bool GVsWithCode,
44 CodeModel::Model CMM,
45 StringRef MArch,
46 StringRef MCPU,
47 const SmallVectorImpl<std::string>& MAttrs) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000048ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000049 std::string *ErrorStr) = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000050ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
51
Chris Lattner2fe4bb02006-03-22 06:07:50 +000052
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000053ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000054 : EEState(*this),
55 LazyFunctionCreator(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000056 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000057 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000058 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000059 Modules.push_back(M);
60 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000061}
62
Brian Gaeke8e539482003-09-04 22:57:27 +000063ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000064 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000065 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
66 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000067}
68
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000069char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +000071 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000072 return new char[GVSize];
73}
74
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000075/// removeModule - Remove a Module from the list of modules.
76bool ExecutionEngine::removeModule(Module *M) {
77 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +000078 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000079 Module *Found = *I;
80 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +000081 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000082 clearGlobalMappingsFromModule(M);
83 return true;
Devang Patel73d0e212007-10-15 19:56:32 +000084 }
85 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000086 return false;
Nate Begeman60789e42009-01-23 19:27:28 +000087}
88
Chris Lattnerfe854032006-08-16 01:24:12 +000089/// FindFunctionNamed - Search all of the active modules to find the one that
90/// defines FnName. This is very slow operation and shouldn't be used for
91/// general code.
92Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
93 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000094 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000095 return F;
96 }
97 return 0;
98}
99
100
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000101void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000104 void *OldVal;
105 if (I == GlobalAddressMap.end())
106 OldVal = 0;
107 else {
108 OldVal = I->second;
109 GlobalAddressMap.erase(I);
110 }
111
112 GlobalAddressReverseMap.erase(OldVal);
113 return OldVal;
114}
115
Chris Lattnere7fd5532006-05-08 22:00:52 +0000116/// addGlobalMapping - Tell the execution engine that the specified global is
117/// at the specified location. This is used internally as functions are JIT'd
118/// and as global variables are laid out in memory. It can and should also be
119/// used by clients of the EE that want to have an LLVM global overlay
120/// existing data in memory.
121void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
122 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000123
David Greeneae7c59a2010-01-05 01:27:39 +0000124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000125 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000127 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
128 CurVal = Addr;
129
130 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000133 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000134 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 V = GV;
136 }
137}
138
139/// clearAllGlobalMappings - Clear all global mappings and start over again
140/// use in dynamic compilation scenarios when you want to move globals
141void ExecutionEngine::clearAllGlobalMappings() {
142 MutexGuard locked(lock);
143
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000146}
147
Nate Begemanf049e072008-05-21 16:34:48 +0000148/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
149/// particular module, because it has been removed from the JIT.
150void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
151 MutexGuard locked(lock);
152
153 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, FI);
Nate Begemanf049e072008-05-21 16:34:48 +0000155 }
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
157 GI != GE; ++GI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000158 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000159 }
160}
161
Chris Lattnere7fd5532006-05-08 22:00:52 +0000162/// updateGlobalMapping - Replace an existing mapping for GV with a new
163/// address. This updates both maps as required. If "Addr" is null, the
164/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000165void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000166 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000167
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000168 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000169 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000170
Chris Lattnere7fd5532006-05-08 22:00:52 +0000171 // Deleting from the mapping?
172 if (Addr == 0) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000173 return EEState.RemoveMapping(locked, GV);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000174 }
175
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000176 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000177 void *OldVal = CurVal;
178
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000181 CurVal = Addr;
182
183 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000185 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000186 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188 V = GV;
189 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000190 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000191}
192
193/// getPointerToGlobalIfAvailable - This returns the address of the specified
194/// global value if it is has already been codegen'd, otherwise it returns null.
195///
196void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
198
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000202}
203
Chris Lattner55d86482003-12-31 20:21:04 +0000204/// getGlobalValueAtAddress - Return the LLVM global value object that starts
205/// at the specified address.
206///
207const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000208 MutexGuard locked(lock);
209
Chris Lattner55d86482003-12-31 20:21:04 +0000210 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000213 I = EEState.getGlobalAddressMap(locked).begin(),
214 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
215 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
Chris Lattnere7fd5532006-05-08 22:00:52 +0000216 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000217 }
218
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000222}
Chris Lattner87f03102003-12-26 06:50:30 +0000223
224// CreateArgv - Turn a vector of strings into a nice argv style array of
225// pointers to null terminated strings.
226//
Owen Anderson1d0be152009-08-13 21:58:54 +0000227static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Chris Lattner87f03102003-12-26 06:50:30 +0000228 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000229 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000230 char *Result = new char[(InputArgv.size()+1)*PtrSize];
231
David Greeneae7c59a2010-01-05 01:27:39 +0000232 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000233 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000234
235 for (unsigned i = 0; i != InputArgv.size(); ++i) {
236 unsigned Size = InputArgv[i].size()+1;
237 char *Dest = new char[Size];
David Greeneae7c59a2010-01-05 01:27:39 +0000238 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000239
Chris Lattner87f03102003-12-26 06:50:30 +0000240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
241 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000242
Chris Lattner87f03102003-12-26 06:50:30 +0000243 // Endian safe: Result[i] = (PointerTy)Dest;
244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245 SBytePtr);
246 }
247
248 // Null terminate it
249 EE->StoreValueToMemory(PTOGV(0),
250 (GenericValue*)(Result+InputArgv.size()*PtrSize),
251 SBytePtr);
252 return Result;
253}
254
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000255
256/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000257/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000258/// value of isDtors.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000259void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
260 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000261 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000262
Chris Lattnerfe854032006-08-16 01:24:12 +0000263 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000264
Evan Cheng18314dc2008-09-30 15:51:21 +0000265 GlobalVariable *GV = module->getNamedGlobal(Name);
266
267 // If this global has internal linkage, or if it has a use, then it must be
268 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
269 // this is the case, don't execute any of the global ctors, __main will do
270 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000271 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000272
273 // Should be an array of '{ int, void ()* }' structs. The first value is
274 // the init priority, which we ignore.
275 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
276 if (!InitList) return;
277 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
278 if (ConstantStruct *CS =
279 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
280 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
281
282 Constant *FP = CS->getOperand(1);
283 if (FP->isNullValue())
284 break; // Found a null terminator, exit.
285
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
287 if (CE->isCast())
288 FP = CE->getOperand(0);
289 if (Function *F = dyn_cast<Function>(FP)) {
290 // Execute the ctor/dtor function!
291 runFunction(F, std::vector<GenericValue>());
292 }
293 }
294}
295
296/// runStaticConstructorsDestructors - This method is used to execute all of
297/// the static constructors or destructors for a program, depending on the
298/// value of isDtors.
299void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
300 // Execute global ctors/dtors for each module in the program.
301 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000302 runStaticConstructorsDestructors(Modules[m], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000303}
304
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000305#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000306/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
307static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
308 unsigned PtrSize = EE->getTargetData()->getPointerSize();
309 for (unsigned i = 0; i < PtrSize; ++i)
310 if (*(i + (uint8_t*)Loc))
311 return false;
312 return true;
313}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000314#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000315
Chris Lattner87f03102003-12-26 06:50:30 +0000316/// runFunctionAsMain - This is a helper function which wraps runFunction to
317/// handle the common task of starting up main with the specified argc, argv,
318/// and envp parameters.
319int ExecutionEngine::runFunctionAsMain(Function *Fn,
320 const std::vector<std::string> &argv,
321 const char * const * envp) {
322 std::vector<GenericValue> GVArgs;
323 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000324 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000325
326 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000327 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000328 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000329 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000330 switch (NumArgs) {
331 case 3:
332 if (FTy->getParamType(2) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000333 llvm_report_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000334 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000335 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000336 case 2:
337 if (FTy->getParamType(1) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000338 llvm_report_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000339 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000340 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000341 case 1:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000342 if (!FTy->getParamType(0)->isIntegerTy(32)) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000343 llvm_report_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000344 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000345 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000346 case 0:
Chris Lattner45f36832009-02-04 17:48:18 +0000347 if (!isa<IntegerType>(FTy->getReturnType()) &&
Benjamin Kramerf0127052010-01-05 13:12:22 +0000348 !FTy->getReturnType()->isVoidTy()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000349 llvm_report_error("Invalid return type of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000350 }
351 break;
352 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000353 llvm_report_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000354 }
355
Chris Lattnerf24d0992004-08-16 01:05:35 +0000356 if (NumArgs) {
357 GVArgs.push_back(GVArgc); // Arg #0 = argc.
358 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000359 // Arg #1 = argv.
360 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000361 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000362 "argv[0] was null after CreateArgv");
363 if (NumArgs > 2) {
364 std::vector<std::string> EnvVars;
365 for (unsigned i = 0; envp[i]; ++i)
366 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000367 // Arg #2 = envp.
368 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000369 }
370 }
371 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000372 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000373}
374
Misha Brukman19684162003-10-16 21:18:05 +0000375/// If possible, create a JIT, unless the caller specifically requests an
376/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000377/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000378///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000379ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000380 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000381 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000382 CodeGenOpt::Level OptLevel,
383 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000384 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000385 .setEngineKind(ForceInterpreter
386 ? EngineKind::Interpreter
387 : EngineKind::JIT)
388 .setErrorStr(ErrorStr)
389 .setOptLevel(OptLevel)
390 .setAllocateGVsWithCode(GVsWithCode)
391 .create();
392}
Brian Gaeke82d82772003-09-03 20:34:19 +0000393
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,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000419 AllocateGVsWithCode, CMModel,
420 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000421 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000422 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000423 }
424
425 // If we can't make a JIT and we didn't request one specifically, try making
426 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000427 if (WhichEngine & EngineKind::Interpreter) {
428 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000429 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000430 if (ErrorStr)
431 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000432 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000433 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000434
435 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
436 if (ErrorStr)
437 *ErrorStr = "JIT has not been linked in.";
438 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000439 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000440}
441
Misha Brukman4afac182003-10-10 17:45:12 +0000442/// getPointerToGlobal - This returns the address of the specified global
443/// value. This may involve code generation if it's a function.
444///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000445void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000446 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000447 return getPointerToFunction(F);
448
Reid Spenceree448632005-07-12 15:51:55 +0000449 MutexGuard locked(lock);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000450 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen68835dd2006-02-07 05:11:57 +0000451 if (p)
452 return p;
453
454 // Global variable might have been added since interpreter started.
455 if (GlobalVariable *GVar =
456 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
457 EmitGlobalVariable(GVar);
458 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000459 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000460 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000461}
462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463/// This function converts a Constant* into a GenericValue. The interesting
464/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000465/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000466GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000468 if (isa<UndefValue>(C)) {
469 GenericValue Result;
470 switch (C->getType()->getTypeID()) {
471 case Type::IntegerTyID:
472 case Type::X86_FP80TyID:
473 case Type::FP128TyID:
474 case Type::PPC_FP128TyID:
475 // Although the value is undefined, we still have to construct an APInt
476 // with the correct bit width.
477 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
478 break;
479 default:
480 break;
481 }
482 return Result;
483 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000484
Reid Spencer3da59db2006-11-27 01:05:10 +0000485 // If the value is a ConstantExpr
486 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000487 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000488 switch (CE->getOpcode()) {
489 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000490 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000491 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000492 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000493 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000494 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000495
Reid Spencer8fb0f192007-03-06 03:04:04 +0000496 char* tmp = (char*) Result.PointerVal;
497 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000498 return Result;
499 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000500 case Instruction::Trunc: {
501 GenericValue GV = getConstantValue(Op0);
502 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
503 GV.IntVal = GV.IntVal.trunc(BitWidth);
504 return GV;
505 }
506 case Instruction::ZExt: {
507 GenericValue GV = getConstantValue(Op0);
508 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
509 GV.IntVal = GV.IntVal.zext(BitWidth);
510 return GV;
511 }
512 case Instruction::SExt: {
513 GenericValue GV = getConstantValue(Op0);
514 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
515 GV.IntVal = GV.IntVal.sext(BitWidth);
516 return GV;
517 }
518 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000519 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000520 GenericValue GV = getConstantValue(Op0);
521 GV.FloatVal = float(GV.DoubleVal);
522 return GV;
523 }
524 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000525 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000526 GenericValue GV = getConstantValue(Op0);
527 GV.DoubleVal = double(GV.FloatVal);
528 return GV;
529 }
530 case Instruction::UIToFP: {
531 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000532 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000533 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000534 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000535 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000536 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000537 const uint64_t zero[] = {0, 0};
538 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000539 (void)apf.convertFromAPInt(GV.IntVal,
540 false,
541 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000542 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000543 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000544 return GV;
545 }
546 case Instruction::SIToFP: {
547 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000548 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000549 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000550 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000551 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000552 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000553 const uint64_t zero[] = { 0, 0};
554 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000555 (void)apf.convertFromAPInt(GV.IntVal,
556 true,
557 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000558 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000559 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000560 return GV;
561 }
562 case Instruction::FPToUI: // double->APInt conversion handles sign
563 case Instruction::FPToSI: {
564 GenericValue GV = getConstantValue(Op0);
565 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000566 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000567 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000568 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000569 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000570 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000571 APFloat apf = APFloat(GV.IntVal);
572 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000573 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000574 (void)apf.convertToInteger(&v, BitWidth,
575 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000576 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000577 GV.IntVal = v; // endian?
578 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000579 return GV;
580 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000581 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000582 GenericValue GV = getConstantValue(Op0);
583 uint32_t PtrWidth = TD->getPointerSizeInBits();
584 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
585 return GV;
586 }
587 case Instruction::IntToPtr: {
588 GenericValue GV = getConstantValue(Op0);
589 uint32_t PtrWidth = TD->getPointerSizeInBits();
590 if (PtrWidth != GV.IntVal.getBitWidth())
591 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
592 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
593 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000594 return GV;
595 }
596 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000597 GenericValue GV = getConstantValue(Op0);
598 const Type* DestTy = CE->getType();
599 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000600 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000602 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000603 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000604 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000605 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000606 GV.DoubleVal = GV.IntVal.bitsToDouble();
607 break;
608 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000609 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000610 GV.IntVal.floatToBits(GV.FloatVal);
611 break;
612 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000613 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000614 GV.IntVal.doubleToBits(GV.DoubleVal);
615 break;
616 case Type::PointerTyID:
617 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
618 break; // getConstantValue(Op0) above already converted it
619 }
620 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000621 }
Chris Lattner9a231222003-05-14 17:51:49 +0000622 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000623 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000624 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000625 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000627 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000628 case Instruction::UDiv:
629 case Instruction::SDiv:
630 case Instruction::URem:
631 case Instruction::SRem:
632 case Instruction::And:
633 case Instruction::Or:
634 case Instruction::Xor: {
635 GenericValue LHS = getConstantValue(Op0);
636 GenericValue RHS = getConstantValue(CE->getOperand(1));
637 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000638 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000639 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000640 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000641 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000642 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
644 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
645 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
646 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
647 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
648 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
649 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
650 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
651 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
652 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
653 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000654 break;
655 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000657 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000658 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000659 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000660 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000661 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000662 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
664 case Instruction::FDiv:
665 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
666 case Instruction::FRem:
667 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
668 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000669 break;
670 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000672 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000673 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000674 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000675 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000676 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000677 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000678 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
679 case Instruction::FDiv:
680 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
681 case Instruction::FRem:
682 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
683 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000684 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000685 case Type::X86_FP80TyID:
686 case Type::PPC_FP128TyID:
687 case Type::FP128TyID: {
688 APFloat apfLHS = APFloat(LHS.IntVal);
689 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000690 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000691 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000692 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000693 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000694 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000695 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000696 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000697 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000698 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000699 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000700 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000701 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000702 break;
703 case Instruction::FDiv:
704 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000705 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000706 break;
707 case Instruction::FRem:
708 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000709 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000710 break;
711 }
712 }
713 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000714 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000715 return GV;
716 }
Chris Lattner9a231222003-05-14 17:51:49 +0000717 default:
718 break;
719 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000720 std::string msg;
721 raw_string_ostream Msg(msg);
722 Msg << "ConstantExpr not handled: " << *CE;
723 llvm_report_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000724 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000725
Reid Spencerbce30f12007-03-06 22:23:15 +0000726 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000727 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000728 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000729 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000730 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000731 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000732 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000733 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000734 case Type::X86_FP80TyID:
735 case Type::FP128TyID:
736 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000737 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000738 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000739 case Type::IntegerTyID:
740 Result.IntVal = cast<ConstantInt>(C)->getValue();
741 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000742 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000743 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000744 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000745 else if (const Function *F = dyn_cast<Function>(C))
746 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000747 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000748 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000749 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
750 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
751 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000752 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000753 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000754 break;
755 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000756 std::string msg;
757 raw_string_ostream Msg(msg);
758 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
759 llvm_report_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000760 }
761 return Result;
762}
763
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000764/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
765/// with the integer held in IntVal.
766static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
767 unsigned StoreBytes) {
768 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
769 uint8_t *Src = (uint8_t *)IntVal.getRawData();
770
Chris Lattnerb67c9582009-01-22 19:53:00 +0000771 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000772 // Little-endian host - the source is ordered from LSB to MSB. Order the
773 // destination from LSB to MSB: Do a straight copy.
774 memcpy(Dst, Src, StoreBytes);
775 else {
776 // Big-endian host - the source is an array of 64 bit words ordered from
777 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
778 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
779 while (StoreBytes > sizeof(uint64_t)) {
780 StoreBytes -= sizeof(uint64_t);
781 // May not be aligned so use memcpy.
782 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
783 Src += sizeof(uint64_t);
784 }
785
786 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
787 }
788}
789
Nate Begeman37efe672006-04-22 18:53:45 +0000790/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
791/// is the address of the memory at which to store Val, cast to GenericValue *.
792/// It is not a pointer to a GenericValue containing the address at which to
793/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000794void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
795 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000796 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
797
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000799 case Type::IntegerTyID:
800 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000801 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000802 case Type::FloatTyID:
803 *((float*)Ptr) = Val.FloatVal;
804 break;
805 case Type::DoubleTyID:
806 *((double*)Ptr) = Val.DoubleVal;
807 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000808 case Type::X86_FP80TyID:
809 memcpy(Ptr, Val.IntVal.getRawData(), 10);
810 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000811 case Type::PointerTyID:
812 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
813 if (StoreBytes != sizeof(PointerTy))
814 memset(Ptr, 0, StoreBytes);
815
Reid Spencer8fb0f192007-03-06 03:04:04 +0000816 *((PointerTy*)Ptr) = Val.PointerVal;
817 break;
818 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000819 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000820 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000821
Chris Lattnerb67c9582009-01-22 19:53:00 +0000822 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000823 // Host and target are different endian - reverse the stored bytes.
824 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
825}
826
827/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
828/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
829static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
830 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
831 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
832
Chris Lattnerb67c9582009-01-22 19:53:00 +0000833 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000834 // Little-endian host - the destination must be ordered from LSB to MSB.
835 // The source is ordered from LSB to MSB: Do a straight copy.
836 memcpy(Dst, Src, LoadBytes);
837 else {
838 // Big-endian - the destination is an array of 64 bit words ordered from
839 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
840 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
841 // a word.
842 while (LoadBytes > sizeof(uint64_t)) {
843 LoadBytes -= sizeof(uint64_t);
844 // May not be aligned so use memcpy.
845 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
846 Dst += sizeof(uint64_t);
847 }
848
849 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
850 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000851}
852
Misha Brukman4afac182003-10-10 17:45:12 +0000853/// FIXME: document
854///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000855void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000856 GenericValue *Ptr,
857 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000858 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000859
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000860 switch (Ty->getTypeID()) {
861 case Type::IntegerTyID:
862 // An APInt with all words initially zero.
863 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
864 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
865 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000866 case Type::FloatTyID:
867 Result.FloatVal = *((float*)Ptr);
868 break;
869 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000870 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000871 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000872 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000873 Result.PointerVal = *((PointerTy*)Ptr);
874 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000875 case Type::X86_FP80TyID: {
876 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000877 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000878 uint64_t y[2];
879 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000880 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000881 break;
882 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000883 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000884 std::string msg;
885 raw_string_ostream Msg(msg);
886 Msg << "Cannot load value of type " << *Ty << "!";
887 llvm_report_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000888 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000889}
890
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000891// InitializeMemory - Recursive function to apply a Constant value into the
892// specified memory location...
893//
894void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000895 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000896 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000897 if (isa<UndefValue>(Init)) {
898 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000899 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000900 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000901 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000902 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
903 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
904 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000905 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000906 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000907 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000908 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
909 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000910 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000911 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
912 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
913 return;
914 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
915 const StructLayout *SL =
916 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
917 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
918 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
919 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000920 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000921 GenericValue Val = getConstantValue(Init);
922 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
923 return;
924 }
925
David Greeneae7c59a2010-01-05 01:27:39 +0000926 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000927 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000928}
929
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000930/// EmitGlobals - Emit all of the global variables to memory, storing their
931/// addresses into GlobalAddress. This must make sure to copy the contents of
932/// their initializers into the memory.
933///
934void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000935
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000936 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000937 // to hold them. If there is more than one module, do a prepass over globals
938 // to figure out how the different modules should link together.
939 //
940 std::map<std::pair<std::string, const Type*>,
941 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000942
Chris Lattnerfe854032006-08-16 01:24:12 +0000943 if (Modules.size() != 1) {
944 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000945 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000946 for (Module::const_global_iterator I = M.global_begin(),
947 E = M.global_end(); I != E; ++I) {
948 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000949 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000950 GV->hasAppendingLinkage() || !GV->hasName())
951 continue;// Ignore external globals and globals with internal linkage.
952
953 const GlobalValue *&GVEntry =
954 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
955
956 // If this is the first time we've seen this global, it is the canonical
957 // version.
958 if (!GVEntry) {
959 GVEntry = GV;
960 continue;
961 }
962
963 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000964 if (GVEntry->hasExternalLinkage() ||
965 GVEntry->hasDLLImportLinkage() ||
966 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000967 continue;
968
969 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000970 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000971 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000972 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000973 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000974 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000975 }
976
977 std::vector<const GlobalValue*> NonCanonicalGlobals;
978 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000979 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000980 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
981 I != E; ++I) {
982 // In the multi-module case, see what this global maps to.
983 if (!LinkedGlobalsMap.empty()) {
984 if (const GlobalValue *GVEntry =
985 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
986 // If something else is the canonical global, ignore this one.
987 if (GVEntry != &*I) {
988 NonCanonicalGlobals.push_back(I);
989 continue;
990 }
991 }
992 }
993
Reid Spencer5cbf9852007-01-30 20:08:39 +0000994 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000995 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +0000996 } else {
997 // External variable reference. Try to use the dynamic loader to
998 // get a pointer to it.
999 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001000 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001001 addGlobalMapping(I, SymAddr);
1002 else {
Torok Edwin31e24662009-07-07 17:32:34 +00001003 llvm_report_error("Could not resolve external global address: "
1004 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001005 }
1006 }
1007 }
1008
1009 // If there are multiple modules, map the non-canonical globals to their
1010 // canonical location.
1011 if (!NonCanonicalGlobals.empty()) {
1012 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1013 const GlobalValue *GV = NonCanonicalGlobals[i];
1014 const GlobalValue *CGV =
1015 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1016 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1017 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001018 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001019 }
1020 }
1021
Reid Spencera54b7cb2007-01-12 07:05:14 +00001022 // Now that all of the globals are set up in memory, loop through them all
1023 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001024 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1025 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001026 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001027 if (!LinkedGlobalsMap.empty()) {
1028 if (const GlobalValue *GVEntry =
1029 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1030 if (GVEntry != &*I) // Not the canonical variable.
1031 continue;
1032 }
1033 EmitGlobalVariable(I);
1034 }
1035 }
1036 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001037}
1038
1039// EmitGlobalVariable - This method emits the specified global variable to the
1040// address specified in GlobalAddresses, or allocates new memory if it's not
1041// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001042void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001043 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001044
Chris Lattner24b0a182003-12-20 02:45:37 +00001045 if (GA == 0) {
1046 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001047 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001048 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001049 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001050
1051 // Don't initialize if it's thread local, let the client do it.
1052 if (!GV->isThreadLocal())
1053 InitializeMemory(GV->getInitializer(), GA);
1054
1055 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001056 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001057 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001058 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001059}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001060
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001061ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1062 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001063}
1064
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001065sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1066 ExecutionEngineState *EES) {
1067 return &EES->EE.lock;
1068}
1069void ExecutionEngineState::AddressMapConfig::onDelete(
1070 ExecutionEngineState *EES, const GlobalValue *Old) {
1071 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1072 EES->GlobalAddressReverseMap.erase(OldVal);
1073}
1074
1075void ExecutionEngineState::AddressMapConfig::onRAUW(
1076 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001077 assert(false && "The ExecutionEngine doesn't know how to handle a"
1078 " RAUW on a value it has a global mapping for.");
1079}