blob: d4af85997317529b4e204e8c81341ccae370a340 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Module.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner5ea5b5c2009-08-23 22:49:13 +000022#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Support/Debug.h"
Edwin Törökf7cbfea2009-07-07 17:32:34 +000024#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +000026#include "llvm/Support/ValueHandle.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000027#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/System/DynamicLibrary.h"
Duncan Sands2e6d3422007-12-12 23:03:45 +000029#include "llvm/System/Host.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Target/TargetData.h"
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000031#include <cmath>
32#include <cstring>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033using namespace llvm;
34
35STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36STATISTIC(NumGlobals , "Number of global vars initialized");
37
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000038ExecutionEngine *(*ExecutionEngine::JITCtor)(Module *M,
Reid Klecknerfa3585b2009-07-18 00:42:18 +000039 std::string *ErrorStr,
40 JITMemoryManager *JMM,
41 CodeGenOpt::Level OptLevel,
Eric Christopherb064d5e2009-11-17 21:58:16 +000042 bool GVsWithCode,
43 CodeModel::Model CMM) = 0;
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000044ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Klecknerfa3585b2009-07-18 00:42:18 +000045 std::string *ErrorStr) = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000046ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
47
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000049ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin2be24032009-10-13 17:42:08 +000050 : EEState(*this),
51 LazyFunctionCreator(0) {
Jeffrey Yasskin4f6ac2f2009-10-27 20:30:28 +000052 CompilingLazily = false;
Evan Cheng9b8bc832008-09-24 16:25:55 +000053 GVCompilationDisabled = false;
Evan Cheng5c62a692008-06-17 16:49:02 +000054 SymbolSearchingDisabled = false;
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000055 Modules.push_back(M);
56 assert(M && "Module is null?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057}
58
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059ExecutionEngine::~ExecutionEngine() {
60 clearAllGlobalMappings();
61 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
62 delete Modules[i];
63}
64
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000065char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
66 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +000067 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000068 return new char[GVSize];
69}
70
Jeffrey Yasskin62de4e72010-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 Patel5d0d0d02007-10-15 19:56:32 +000074 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000075 Module *Found = *I;
76 if (Found == M) {
Devang Patel5d0d0d02007-10-15 19:56:32 +000077 Modules.erase(I);
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000078 clearGlobalMappingsFromModule(M);
79 return true;
Devang Patel5d0d0d02007-10-15 19:56:32 +000080 }
81 }
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000082 return false;
Nate Begemanb34045e2009-01-23 19:27:28 +000083}
84
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin62de4e72010-01-27 20:34:15 +000090 if (Function *F = Modules[i]->getFunction(FnName))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091 return F;
92 }
93 return 0;
94}
95
96
Jeffrey Yasskin43304d32009-10-09 22:10:27 +000097void *ExecutionEngineState::RemoveMapping(
98 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +000099 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin43304d32009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Chengb83f6972008-09-18 07:54:21 +0000119
David Greene7050bcc2010-01-05 01:27:39 +0000120 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000121 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000122 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin2be24032009-10-13 17:42:08 +0000127 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000128 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000129 EEState.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin2be24032009-10-13 17:42:08 +0000140 EEState.getGlobalAddressMap(locked).clear();
141 EEState.getGlobalAddressReverseMap(locked).clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142}
143
Nate Begemanf7113d92008-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 Yasskin2be24032009-10-13 17:42:08 +0000150 EEState.RemoveMapping(locked, FI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000151 }
152 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
153 GI != GE; ++GI) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, GI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000155 }
156}
157
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerfb3f0f82008-04-04 04:47:41 +0000161void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 MutexGuard locked(lock);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000163
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000164 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000165 EEState.getGlobalAddressMap(locked);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000166
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 // Deleting from the mapping?
168 if (Addr == 0) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000169 return EEState.RemoveMapping(locked, GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 }
171
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000172 void *&CurVal = Map[GV];
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000173 void *OldVal = CurVal;
174
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000175 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
176 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 CurVal = Addr;
178
179 // If we are using the reverse mapping, add it too
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000180 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000181 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000182 EEState.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
184 V = GV;
185 }
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000186 return OldVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin6ddfe5c2009-10-23 22:37:43 +0000195 ExecutionEngineState::GlobalAddressMapTy::iterator I =
196 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000197 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198}
199
200/// getGlobalValueAtAddress - Return the LLVM global value object that starts
201/// at the specified address.
202///
203const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
204 MutexGuard locked(lock);
205
206 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000207 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000208 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin2be24032009-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,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 I->first));
213 }
214
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000215 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000216 EEState.getGlobalAddressReverseMap(locked).find(Addr);
217 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218}
219
220// CreateArgv - Turn a vector of strings into a nice argv style array of
221// pointers to null terminated strings.
222//
Owen Anderson35b47072009-08-13 21:58:54 +0000223static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 const std::vector<std::string> &InputArgv) {
225 unsigned PtrSize = EE->getTargetData()->getPointerSize();
226 char *Result = new char[(InputArgv.size()+1)*PtrSize];
227
David Greene7050bcc2010-01-05 01:27:39 +0000228 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sandsf2519d62009-10-06 15:40:36 +0000229 const Type *SBytePtr = Type::getInt8PtrTy(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
231 for (unsigned i = 0; i != InputArgv.size(); ++i) {
232 unsigned Size = InputArgv[i].size()+1;
233 char *Dest = new char[Size];
David Greene7050bcc2010-01-05 01:27:39 +0000234 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235
236 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
237 Dest[Size-1] = 0;
238
239 // 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
251
252/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng50a58822008-09-30 15:51:21 +0000253/// the static constructors or destructors for a module, depending on the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254/// value of isDtors.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000255void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
256 bool isDtors) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
258
259 // Execute global ctors/dtors for each module in the program.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260
Evan Cheng50a58822008-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 Espindolaa168fc92009-01-15 20:18:42 +0000267 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng50a58822008-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 Yasskin62de4e72010-01-27 20:34:15 +0000298 runStaticConstructorsDestructors(Modules[m], isDtors);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299}
300
Dan Gohmanc7e1ad02008-08-26 01:38:29 +0000301#ifndef NDEBUG
Duncan Sandse0a2b302007-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 Gohmanc7e1ad02008-08-26 01:38:29 +0000310#endif
Duncan Sandse0a2b302007-12-14 19:38:31 +0000311
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
320 GVArgc.IntVal = APInt(32, argv.size());
321
322 // Check main() type
323 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
324 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf2052d52010-01-05 13:12:22 +0000325 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 switch (NumArgs) {
327 case 3:
328 if (FTy->getParamType(2) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000329 llvm_report_error("Invalid type for third argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 }
331 // FALLS THROUGH
332 case 2:
333 if (FTy->getParamType(1) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000334 llvm_report_error("Invalid type for second argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 }
336 // FALLS THROUGH
337 case 1:
Benjamin Kramerf0e83d22010-01-05 21:05:54 +0000338 if (!FTy->getParamType(0)->isInteger(32)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000339 llvm_report_error("Invalid type for first argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 }
341 // FALLS THROUGH
342 case 0:
Chris Lattner39bc61c2009-02-04 17:48:18 +0000343 if (!isa<IntegerType>(FTy->getReturnType()) &&
Benjamin Kramerf2052d52010-01-05 13:12:22 +0000344 !FTy->getReturnType()->isVoidTy()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000345 llvm_report_error("Invalid return type of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 }
347 break;
348 default:
Edwin Törökced9ff82009-07-11 13:10:19 +0000349 llvm_report_error("Invalid number of arguments of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 }
351
352 if (NumArgs) {
353 GVArgs.push_back(GVArgc); // Arg #0 = argc.
354 if (NumArgs > 1) {
Owen Anderson35b47072009-08-13 21:58:54 +0000355 // Arg #1 = argv.
356 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sandse0a2b302007-12-14 19:38:31 +0000357 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Anderson35b47072009-08-13 21:58:54 +0000363 // Arg #2 = envp.
364 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366 }
367 }
368 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
369}
370
371/// 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,
373/// NULL is returned.
374///
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000375ExecutionEngine *ExecutionEngine::create(Module *M,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 bool ForceInterpreter,
Evan Chenga6394fc2008-08-08 08:11:34 +0000377 std::string *ErrorStr,
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000378 CodeGenOpt::Level OptLevel,
379 bool GVsWithCode) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000380 return EngineBuilder(M)
Reid Klecknerfa3585b2009-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}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000390ExecutionEngine *ExecutionEngine::create(Module *M) {
391 return EngineBuilder(M).create();
392}
393
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000394ExecutionEngine *EngineBuilder::create() {
Nick Lewyckybaa3a032008-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 Klecknerfa3585b2009-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 Lattnercd0d9372009-09-23 01:46:04 +0000404 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000405 WhichEngine = EngineKind::JIT;
Chris Lattnercd0d9372009-09-23 01:46:04 +0000406 else {
Chris Lattner03344a22009-09-23 02:03:49 +0000407 if (ErrorStr)
408 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnercd0d9372009-09-23 01:46:04 +0000409 return 0;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000410 }
411 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000413 // Unless the interpreter was explicitly selected or the JIT is not linked,
414 // try making a JIT.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000415 if (WhichEngine & EngineKind::JIT) {
416 if (ExecutionEngine::JITCtor) {
417 ExecutionEngine *EE =
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000418 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Eric Christopherb064d5e2009-11-17 21:58:16 +0000419 AllocateGVsWithCode, CMModel);
Chris Lattnercd0d9372009-09-23 01:46:04 +0000420 if (EE) return EE;
Chris Lattnercd0d9372009-09-23 01:46:04 +0000421 }
Reid Klecknerfa3585b2009-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 Lattnercd0d9372009-09-23 01:46:04 +0000426 if (WhichEngine & EngineKind::Interpreter) {
427 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000428 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattner03344a22009-09-23 02:03:49 +0000429 if (ErrorStr)
430 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnercd0d9372009-09-23 01:46:04 +0000431 return 0;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000432 }
Chris Lattner03344a22009-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 Lattnercd0d9372009-09-23 01:46:04 +0000438 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439}
440
441/// getPointerToGlobal - This returns the address of the specified global
442/// value. This may involve code generation if it's a function.
443///
444void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
445 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
446 return getPointerToFunction(F);
447
448 MutexGuard locked(lock);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000449 void *p = EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
Edwin Törökbd448e32009-07-14 16:55:14 +0000458 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000459 return EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460}
461
462/// This function converts a Constant* into a GenericValue. The interesting
463/// part is if C is a ConstantExpr.
Reid Spencer10ffdf12007-08-11 15:57:56 +0000464/// @brief Get a GenericValue for a Constant*
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
466 // If its undefined, return the garbage.
Jay Foad1c91e672010-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483
484 // If the value is a ConstantExpr
485 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
486 Constant *Op0 = CE->getOperand(0);
487 switch (CE->getOpcode()) {
488 case Instruction::GetElementPtr: {
489 // Compute the index
490 GenericValue Result = getConstantValue(Op0);
491 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
492 uint64_t Offset =
493 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
494
495 char* tmp = (char*) Result.PointerVal;
496 Result = PTOGV(tmp + Offset);
497 return Result;
498 }
499 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 Johannesenc560da62007-09-17 18:44:13 +0000518 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 GenericValue GV = getConstantValue(Op0);
520 GV.FloatVal = float(GV.DoubleVal);
521 return GV;
522 }
523 case Instruction::FPExt:{
Dale Johannesenc560da62007-09-17 18:44:13 +0000524 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner82cdc062009-10-05 05:54:46 +0000531 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000533 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000535 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000536 const uint64_t zero[] = {0, 0};
537 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000538 (void)apf.convertFromAPInt(GV.IntVal,
539 false,
540 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000541 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000542 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 return GV;
544 }
545 case Instruction::SIToFP: {
546 GenericValue GV = getConstantValue(Op0);
Chris Lattner82cdc062009-10-05 05:54:46 +0000547 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000549 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000551 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000552 const uint64_t zero[] = { 0, 0};
553 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000554 (void)apf.convertFromAPInt(GV.IntVal,
555 true,
556 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000557 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000558 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner82cdc062009-10-05 05:54:46 +0000565 if (Op0->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000567 else if (Op0->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000569 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000570 APFloat apf = APFloat(GV.IntVal);
571 uint64_t v;
Dale Johannesen6e547b42008-10-09 23:00:39 +0000572 bool ignored;
Dale Johannesenc560da62007-09-17 18:44:13 +0000573 (void)apf.convertToInteger(&v, BitWidth,
574 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen6e547b42008-10-09 23:00:39 +0000575 APFloat::rmTowardZero, &ignored);
Dale Johannesenc560da62007-09-17 18:44:13 +0000576 GV.IntVal = v; // endian?
577 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 return GV;
579 }
580 case Instruction::PtrToInt: {
581 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()));
593 return GV;
594 }
595 case Instruction::BitCast: {
596 GenericValue GV = getConstantValue(Op0);
597 const Type* DestTy = CE->getType();
598 switch (Op0->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000599 default: llvm_unreachable("Invalid bitcast operand");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 case Type::IntegerTyID:
601 assert(DestTy->isFloatingPoint() && "invalid bitcast");
Chris Lattner82cdc062009-10-05 05:54:46 +0000602 if (DestTy->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattner82cdc062009-10-05 05:54:46 +0000604 else if (DestTy->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 GV.DoubleVal = GV.IntVal.bitsToDouble();
606 break;
607 case Type::FloatTyID:
Benjamin Kramerf0e83d22010-01-05 21:05:54 +0000608 assert(DestTy->isInteger(32) && "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 GV.IntVal.floatToBits(GV.FloatVal);
610 break;
611 case Type::DoubleTyID:
Benjamin Kramerf0e83d22010-01-05 21:05:54 +0000612 assert(DestTy->isInteger(64) && "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
620 }
621 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000622 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000624 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000626 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
637 switch (CE->getOperand(0)->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000638 default: llvm_unreachable("Bad add type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 case Type::IntegerTyID:
640 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000641 default: llvm_unreachable("Invalid integer opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
653 break;
654 case Type::FloatTyID:
655 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000656 default: llvm_unreachable("Invalid float opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000657 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000659 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000661 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
668 break;
669 case Type::DoubleTyID:
670 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000671 default: llvm_unreachable("Invalid double opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000672 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000674 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000676 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
683 break;
Dale Johannesenc560da62007-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()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000689 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000690 case Instruction::FAdd:
Dale Johannesenc560da62007-09-17 18:44:13 +0000691 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000692 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000693 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000694 case Instruction::FSub:
Dale Johannesenc560da62007-09-17 18:44:13 +0000695 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000696 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000697 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000698 case Instruction::FMul:
Dale Johannesenc560da62007-09-17 18:44:13 +0000699 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000700 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000701 break;
702 case Instruction::FDiv:
703 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000704 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000705 break;
706 case Instruction::FRem:
707 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000708 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000709 break;
710 }
711 }
712 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 }
714 return GV;
715 }
716 default:
717 break;
718 }
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 }
724
725 GenericValue Result;
726 switch (C->getType()->getTypeID()) {
727 case Type::FloatTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000728 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 break;
730 case Type::DoubleTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000731 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000733 case Type::X86_FP80TyID:
734 case Type::FP128TyID:
735 case Type::PPC_FP128TyID:
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000736 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000737 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 case Type::IntegerTyID:
739 Result.IntVal = cast<ConstantInt>(C)->getValue();
740 break;
741 case Type::PointerTyID:
742 if (isa<ConstantPointerNull>(C))
743 Result.PointerVal = 0;
744 else if (const Function *F = dyn_cast<Function>(C))
745 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerbfa6b852009-10-29 05:26:09 +0000746 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerbfa6b852009-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())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000752 llvm_unreachable("Unknown constant pointer type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 break;
754 default:
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 }
760 return Result;
761}
762
Duncan Sandse0a2b302007-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 Lattnerfcaa7f82009-01-22 19:53:00 +0000770 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Chengd0e5e982008-11-04 06:10:31 +0000793void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
794 GenericValue *Ptr, const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000795 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
796
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 switch (Ty->getTypeID()) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000798 case Type::IntegerTyID:
799 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801 case Type::FloatTyID:
802 *((float*)Ptr) = Val.FloatVal;
803 break;
804 case Type::DoubleTyID:
805 *((double*)Ptr) = Val.DoubleVal;
806 break;
Dale Johannesen2f294562009-03-24 18:16:17 +0000807 case Type::X86_FP80TyID:
808 memcpy(Ptr, Val.IntVal.getRawData(), 10);
809 break;
Duncan Sandse0a2b302007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 *((PointerTy*)Ptr) = Val.PointerVal;
816 break;
817 default:
David Greene7050bcc2010-01-05 01:27:39 +0000818 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 }
Duncan Sandse0a2b302007-12-14 19:38:31 +0000820
Chris Lattnerfcaa7f82009-01-22 19:53:00 +0000821 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sandse0a2b302007-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 Lattnerfcaa7f82009-01-22 19:53:00 +0000832 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850}
851
852/// FIXME: document
853///
Duncan Sandse0a2b302007-12-14 19:38:31 +0000854void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandsf06c7a62008-03-10 16:38:37 +0000855 GenericValue *Ptr,
856 const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000857 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands7feee8f2007-12-10 17:43:13 +0000858
Duncan Sandse0a2b302007-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 case Type::FloatTyID:
866 Result.FloatVal = *((float*)Ptr);
867 break;
868 case Type::DoubleTyID:
Duncan Sandse0a2b302007-12-14 19:38:31 +0000869 Result.DoubleVal = *((double*)Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 break;
Duncan Sandse0a2b302007-12-14 19:38:31 +0000871 case Type::PointerTyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 Result.PointerVal = *((PointerTy*)Ptr);
873 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000874 case Type::X86_FP80TyID: {
875 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands1d641aa2007-12-15 17:37:40 +0000876 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen2f294562009-03-24 18:16:17 +0000877 uint64_t y[2];
878 memcpy(y, Ptr, 10);
Duncan Sands8d00dd02007-11-28 10:36:19 +0000879 Result.IntVal = APInt(80, 2, y);
Dale Johannesenc560da62007-09-17 18:44:13 +0000880 break;
881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882 default:
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 }
888}
889
890// InitializeMemory - Recursive function to apply a Constant value into the
891// specified memory location...
892//
893void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene7050bcc2010-01-05 01:27:39 +0000894 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000895 DEBUG(Init->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 if (isa<UndefValue>(Init)) {
897 return;
898 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
899 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000900 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
902 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
903 return;
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000904 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000905 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000906 return;
Dan Gohman61dbdbd2008-05-20 03:20:09 +0000907 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
908 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000909 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman61dbdbd2008-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 } else if (Init->getType()->isFirstClassType()) {
920 GenericValue Val = getConstantValue(Init);
921 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
922 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 }
924
David Greene7050bcc2010-01-05 01:27:39 +0000925 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000926 llvm_unreachable("Unknown constant type to initialize memory with!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927}
928
929/// 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() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 // Loop over all of the global variables in the program, allocating the memory
936 // 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;
941
942 if (Modules.size() != 1) {
943 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000944 Module &M = *Modules[m];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 for (Module::const_global_iterator I = M.global_begin(),
946 E = M.global_end(); I != E; ++I) {
947 const GlobalValue *GV = I;
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000948 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +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.
963 if (GVEntry->hasExternalLinkage() ||
964 GVEntry->hasDLLImportLinkage() ||
965 GVEntry->hasDLLExportLinkage())
966 continue;
967
968 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesen49c44122008-05-14 20:12:51 +0000969 // symbol. FIXME is this right for common?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
971 GVEntry = GV;
972 }
973 }
974 }
975
976 std::vector<const GlobalValue*> NonCanonicalGlobals;
977 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000978 Module &M = *Modules[m];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
993 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000994 addGlobalMapping(I, getMemoryForGV(I));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 } else {
996 // External variable reference. Try to use the dynamic loader to
997 // get a pointer to it.
998 if (void *SymAddr =
Daniel Dunbar9198e932009-07-21 08:54:24 +0000999 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 addGlobalMapping(I, SymAddr);
1001 else {
Edwin Törökf7cbfea2009-07-07 17:32:34 +00001002 llvm_report_error("Could not resolve external global address: "
1003 +I->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lopesec8dccb2008-10-14 10:04:52 +00001017 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019 }
1020
1021 // Now that all of the globals are set up in memory, loop through them all
1022 // and initialize their contents.
1023 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1024 I != E; ++I) {
1025 if (!I->isDeclaration()) {
1026 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 }
1036}
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.
1041void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1042 void *GA = getPointerToGlobalIfAvailable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 if (GA == 0) {
1045 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1532008-10-25 15:41:43 +00001046 GA = getMemoryForGV(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 addGlobalMapping(GV, GA);
1048 }
Nicolas Geoffray46fa1532008-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 Sandsec4f97d2009-05-09 07:06:46 +00001055 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056 NumInitBytes += (unsigned)GVSize;
1057 ++NumGlobals;
1058}
Jeffrey Yasskin2be24032009-10-13 17:42:08 +00001059
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +00001060ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1061 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +00001062}
1063
Jeffrey Yasskin6ddfe5c2009-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 Yasskin2be24032009-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}