blob: 6db3ef963ac62ce5d7ad0c3287ac75611e03c5f2 [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 Yasskin403335c2010-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 Yasskin62de4e72010-01-27 20:34:15 +000048ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Klecknerfa3585b2009-07-18 00:42:18 +000049 std::string *ErrorStr) = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000050ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
51
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000053ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin2be24032009-10-13 17:42:08 +000054 : EEState(*this),
55 LazyFunctionCreator(0) {
Jeffrey Yasskin4f6ac2f2009-10-27 20:30:28 +000056 CompilingLazily = false;
Evan Cheng9b8bc832008-09-24 16:25:55 +000057 GVCompilationDisabled = false;
Evan Cheng5c62a692008-06-17 16:49:02 +000058 SymbolSearchingDisabled = false;
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000059 Modules.push_back(M);
60 assert(M && "Module is null?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061}
62
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063ExecutionEngine::~ExecutionEngine() {
64 clearAllGlobalMappings();
65 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
66 delete Modules[i];
67}
68
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000069char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +000071 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000072 return new char[GVSize];
73}
74
Jeffrey Yasskin62de4e72010-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 Patel5d0d0d02007-10-15 19:56:32 +000078 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000079 Module *Found = *I;
80 if (Found == M) {
Devang Patel5d0d0d02007-10-15 19:56:32 +000081 Modules.erase(I);
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000082 clearGlobalMappingsFromModule(M);
83 return true;
Devang Patel5d0d0d02007-10-15 19:56:32 +000084 }
85 }
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +000086 return false;
Nate Begemanb34045e2009-01-23 19:27:28 +000087}
88
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin62de4e72010-01-27 20:34:15 +000094 if (Function *F = Modules[i]->getFunction(FnName))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 return F;
96 }
97 return 0;
98}
99
100
Jeffrey Yasskin43304d32009-10-09 22:10:27 +0000101void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin43304d32009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Chengb83f6972008-09-18 07:54:21 +0000123
David Greene7050bcc2010-01-05 01:27:39 +0000124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000125 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin2be24032009-10-13 17:42:08 +0000131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000133 EEState.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin2be24032009-10-13 17:42:08 +0000144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146}
147
Nate Begemanf7113d92008-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 Yasskin2be24032009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, FI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000155 }
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
157 GI != GE; ++GI) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000158 EEState.RemoveMapping(locked, GI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000159 }
160}
161
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerfb3f0f82008-04-04 04:47:41 +0000165void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 MutexGuard locked(lock);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000167
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000168 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000169 EEState.getGlobalAddressMap(locked);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000170
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 // Deleting from the mapping?
172 if (Addr == 0) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000173 return EEState.RemoveMapping(locked, GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 }
175
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000176 void *&CurVal = Map[GV];
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000177 void *OldVal = CurVal;
178
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 CurVal = Addr;
182
183 // If we are using the reverse mapping, add it too
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000185 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000186 EEState.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188 V = GV;
189 }
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000190 return OldVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin6ddfe5c2009-10-23 22:37:43 +0000199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202}
203
204/// getGlobalValueAtAddress - Return the LLVM global value object that starts
205/// at the specified address.
206///
207const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
208 MutexGuard locked(lock);
209
210 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin2be24032009-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,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 I->first));
217 }
218
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin2be24032009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
224// CreateArgv - Turn a vector of strings into a nice argv style array of
225// pointers to null terminated strings.
226//
Owen Anderson35b47072009-08-13 21:58:54 +0000227static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 const std::vector<std::string> &InputArgv) {
229 unsigned PtrSize = EE->getTargetData()->getPointerSize();
230 char *Result = new char[(InputArgv.size()+1)*PtrSize];
231
David Greene7050bcc2010-01-05 01:27:39 +0000232 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sandsf2519d62009-10-06 15:40:36 +0000233 const Type *SBytePtr = Type::getInt8PtrTy(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234
235 for (unsigned i = 0; i != InputArgv.size(); ++i) {
236 unsigned Size = InputArgv[i].size()+1;
237 char *Dest = new char[Size];
David Greene7050bcc2010-01-05 01:27:39 +0000238 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
241 Dest[Size-1] = 0;
242
243 // 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
255
256/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng50a58822008-09-30 15:51:21 +0000257/// the static constructors or destructors for a module, depending on the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258/// value of isDtors.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000259void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
260 bool isDtors) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
262
263 // Execute global ctors/dtors for each module in the program.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264
Evan Cheng50a58822008-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 Espindolaa168fc92009-01-15 20:18:42 +0000271 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng50a58822008-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 Yasskin62de4e72010-01-27 20:34:15 +0000302 runStaticConstructorsDestructors(Modules[m], isDtors);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303}
304
Dan Gohmanc7e1ad02008-08-26 01:38:29 +0000305#ifndef NDEBUG
Duncan Sandse0a2b302007-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 Gohmanc7e1ad02008-08-26 01:38:29 +0000314#endif
Duncan Sandse0a2b302007-12-14 19:38:31 +0000315
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
324 GVArgc.IntVal = APInt(32, argv.size());
325
326 // Check main() type
327 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
328 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf2052d52010-01-05 13:12:22 +0000329 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 switch (NumArgs) {
331 case 3:
332 if (FTy->getParamType(2) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000333 llvm_report_error("Invalid type for third argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 }
335 // FALLS THROUGH
336 case 2:
337 if (FTy->getParamType(1) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000338 llvm_report_error("Invalid type for second argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 }
340 // FALLS THROUGH
341 case 1:
Duncan Sandse92dee12010-02-15 16:12:20 +0000342 if (!FTy->getParamType(0)->isIntegerTy(32)) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000343 llvm_report_error("Invalid type for first argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 }
345 // FALLS THROUGH
346 case 0:
Chris Lattner39bc61c2009-02-04 17:48:18 +0000347 if (!isa<IntegerType>(FTy->getReturnType()) &&
Benjamin Kramerf2052d52010-01-05 13:12:22 +0000348 !FTy->getReturnType()->isVoidTy()) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000349 llvm_report_error("Invalid return type of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 }
351 break;
352 default:
Edwin Törökced9ff82009-07-11 13:10:19 +0000353 llvm_report_error("Invalid number of arguments of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 }
355
356 if (NumArgs) {
357 GVArgs.push_back(GVArgc); // Arg #0 = argc.
358 if (NumArgs > 1) {
Owen Anderson35b47072009-08-13 21:58:54 +0000359 // Arg #1 = argv.
360 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sandse0a2b302007-12-14 19:38:31 +0000361 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Anderson35b47072009-08-13 21:58:54 +0000367 // Arg #2 = envp.
368 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 }
370 }
371 }
372 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
373}
374
375/// 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,
377/// NULL is returned.
378///
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000379ExecutionEngine *ExecutionEngine::create(Module *M,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 bool ForceInterpreter,
Evan Chenga6394fc2008-08-08 08:11:34 +0000381 std::string *ErrorStr,
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000382 CodeGenOpt::Level OptLevel,
383 bool GVsWithCode) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000384 return EngineBuilder(M)
Reid Klecknerfa3585b2009-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}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
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,
Jeffrey Yasskin403335c2010-02-05 16:19:36 +0000419 AllocateGVsWithCode, CMModel,
420 MArch, MCPU, MAttrs);
Chris Lattnercd0d9372009-09-23 01:46:04 +0000421 if (EE) return EE;
Chris Lattnercd0d9372009-09-23 01:46:04 +0000422 }
Reid Klecknerfa3585b2009-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 Lattnercd0d9372009-09-23 01:46:04 +0000427 if (WhichEngine & EngineKind::Interpreter) {
428 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000429 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattner03344a22009-09-23 02:03:49 +0000430 if (ErrorStr)
431 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnercd0d9372009-09-23 01:46:04 +0000432 return 0;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000433 }
Chris Lattner03344a22009-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 Lattnercd0d9372009-09-23 01:46:04 +0000439 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440}
441
442/// getPointerToGlobal - This returns the address of the specified global
443/// value. This may involve code generation if it's a function.
444///
445void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
446 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
447 return getPointerToFunction(F);
448
449 MutexGuard locked(lock);
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000450 void *p = EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
Edwin Törökbd448e32009-07-14 16:55:14 +0000459 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +0000460 return EEState.getGlobalAddressMap(locked)[GV];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461}
462
463/// This function converts a Constant* into a GenericValue. The interesting
464/// part is if C is a ConstantExpr.
Reid Spencer10ffdf12007-08-11 15:57:56 +0000465/// @brief Get a GenericValue for a Constant*
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
467 // If its undefined, return the garbage.
Jay Foad1c91e672010-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484
485 // If the value is a ConstantExpr
486 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
487 Constant *Op0 = CE->getOperand(0);
488 switch (CE->getOpcode()) {
489 case Instruction::GetElementPtr: {
490 // Compute the index
491 GenericValue Result = getConstantValue(Op0);
492 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
493 uint64_t Offset =
494 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
495
496 char* tmp = (char*) Result.PointerVal;
497 Result = PTOGV(tmp + Offset);
498 return Result;
499 }
500 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 Johannesenc560da62007-09-17 18:44:13 +0000519 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 GenericValue GV = getConstantValue(Op0);
521 GV.FloatVal = float(GV.DoubleVal);
522 return GV;
523 }
524 case Instruction::FPExt:{
Dale Johannesenc560da62007-09-17 18:44:13 +0000525 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner82cdc062009-10-05 05:54:46 +0000532 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000534 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000536 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000537 const uint64_t zero[] = {0, 0};
538 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000539 (void)apf.convertFromAPInt(GV.IntVal,
540 false,
541 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000542 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000543 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 return GV;
545 }
546 case Instruction::SIToFP: {
547 GenericValue GV = getConstantValue(Op0);
Chris Lattner82cdc062009-10-05 05:54:46 +0000548 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000550 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000552 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000553 const uint64_t zero[] = { 0, 0};
554 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000555 (void)apf.convertFromAPInt(GV.IntVal,
556 true,
557 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000558 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000559 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattner82cdc062009-10-05 05:54:46 +0000566 if (Op0->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000568 else if (Op0->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000570 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000571 APFloat apf = APFloat(GV.IntVal);
572 uint64_t v;
Dale Johannesen6e547b42008-10-09 23:00:39 +0000573 bool ignored;
Dale Johannesenc560da62007-09-17 18:44:13 +0000574 (void)apf.convertToInteger(&v, BitWidth,
575 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen6e547b42008-10-09 23:00:39 +0000576 APFloat::rmTowardZero, &ignored);
Dale Johannesenc560da62007-09-17 18:44:13 +0000577 GV.IntVal = v; // endian?
578 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 return GV;
580 }
581 case Instruction::PtrToInt: {
582 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()));
594 return GV;
595 }
596 case Instruction::BitCast: {
597 GenericValue GV = getConstantValue(Op0);
598 const Type* DestTy = CE->getType();
599 switch (Op0->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000600 default: llvm_unreachable("Invalid bitcast operand");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 case Type::IntegerTyID:
Duncan Sandse92dee12010-02-15 16:12:20 +0000602 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattner82cdc062009-10-05 05:54:46 +0000603 if (DestTy->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattner82cdc062009-10-05 05:54:46 +0000605 else if (DestTy->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 GV.DoubleVal = GV.IntVal.bitsToDouble();
607 break;
608 case Type::FloatTyID:
Duncan Sandse92dee12010-02-15 16:12:20 +0000609 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 GV.IntVal.floatToBits(GV.FloatVal);
611 break;
612 case Type::DoubleTyID:
Duncan Sandse92dee12010-02-15 16:12:20 +0000613 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
621 }
622 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000623 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000625 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000627 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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;
638 switch (CE->getOperand(0)->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000639 default: llvm_unreachable("Bad add type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 case Type::IntegerTyID:
641 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000642 default: llvm_unreachable("Invalid integer opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
654 break;
655 case Type::FloatTyID:
656 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000657 default: llvm_unreachable("Invalid float opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000658 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000660 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000662 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
669 break;
670 case Type::DoubleTyID:
671 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000672 default: llvm_unreachable("Invalid double opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000673 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000675 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000677 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 }
684 break;
Dale Johannesenc560da62007-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()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000690 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000691 case Instruction::FAdd:
Dale Johannesenc560da62007-09-17 18:44:13 +0000692 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000693 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000694 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000695 case Instruction::FSub:
Dale Johannesenc560da62007-09-17 18:44:13 +0000696 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000697 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000698 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000699 case Instruction::FMul:
Dale Johannesenc560da62007-09-17 18:44:13 +0000700 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000701 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000702 break;
703 case Instruction::FDiv:
704 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000705 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000706 break;
707 case Instruction::FRem:
708 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000709 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000710 break;
711 }
712 }
713 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 }
715 return GV;
716 }
717 default:
718 break;
719 }
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 }
725
726 GenericValue Result;
727 switch (C->getType()->getTypeID()) {
728 case Type::FloatTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000729 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 break;
731 case Type::DoubleTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000732 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000734 case Type::X86_FP80TyID:
735 case Type::FP128TyID:
736 case Type::PPC_FP128TyID:
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000737 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000738 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 case Type::IntegerTyID:
740 Result.IntVal = cast<ConstantInt>(C)->getValue();
741 break;
742 case Type::PointerTyID:
743 if (isa<ConstantPointerNull>(C))
744 Result.PointerVal = 0;
745 else if (const Function *F = dyn_cast<Function>(C))
746 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerbfa6b852009-10-29 05:26:09 +0000747 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerbfa6b852009-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())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000753 llvm_unreachable("Unknown constant pointer type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 break;
755 default:
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 }
761 return Result;
762}
763
Duncan Sandse0a2b302007-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 Lattnerfcaa7f82009-01-22 19:53:00 +0000771 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Chengd0e5e982008-11-04 06:10:31 +0000794void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
795 GenericValue *Ptr, const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000796 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
797
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 switch (Ty->getTypeID()) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000799 case Type::IntegerTyID:
800 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 case Type::FloatTyID:
803 *((float*)Ptr) = Val.FloatVal;
804 break;
805 case Type::DoubleTyID:
806 *((double*)Ptr) = Val.DoubleVal;
807 break;
Dale Johannesen2f294562009-03-24 18:16:17 +0000808 case Type::X86_FP80TyID:
809 memcpy(Ptr, Val.IntVal.getRawData(), 10);
810 break;
Duncan Sandse0a2b302007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 *((PointerTy*)Ptr) = Val.PointerVal;
817 break;
818 default:
David Greene7050bcc2010-01-05 01:27:39 +0000819 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 }
Duncan Sandse0a2b302007-12-14 19:38:31 +0000821
Chris Lattnerfcaa7f82009-01-22 19:53:00 +0000822 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sandse0a2b302007-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 Lattnerfcaa7f82009-01-22 19:53:00 +0000833 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-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 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851}
852
853/// FIXME: document
854///
Duncan Sandse0a2b302007-12-14 19:38:31 +0000855void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandsf06c7a62008-03-10 16:38:37 +0000856 GenericValue *Ptr,
857 const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000858 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands7feee8f2007-12-10 17:43:13 +0000859
Duncan Sandse0a2b302007-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 case Type::FloatTyID:
867 Result.FloatVal = *((float*)Ptr);
868 break;
869 case Type::DoubleTyID:
Duncan Sandse0a2b302007-12-14 19:38:31 +0000870 Result.DoubleVal = *((double*)Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 break;
Duncan Sandse0a2b302007-12-14 19:38:31 +0000872 case Type::PointerTyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 Result.PointerVal = *((PointerTy*)Ptr);
874 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000875 case Type::X86_FP80TyID: {
876 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands1d641aa2007-12-15 17:37:40 +0000877 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen2f294562009-03-24 18:16:17 +0000878 uint64_t y[2];
879 memcpy(y, Ptr, 10);
Duncan Sands8d00dd02007-11-28 10:36:19 +0000880 Result.IntVal = APInt(80, 2, y);
Dale Johannesenc560da62007-09-17 18:44:13 +0000881 break;
882 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000883 default:
Edwin Törökced9ff82009-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());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 }
889}
890
891// InitializeMemory - Recursive function to apply a Constant value into the
892// specified memory location...
893//
894void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene7050bcc2010-01-05 01:27:39 +0000895 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000896 DEBUG(Init->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 if (isa<UndefValue>(Init)) {
898 return;
899 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
900 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000901 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
903 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
904 return;
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000905 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000906 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000907 return;
Dan Gohman61dbdbd2008-05-20 03:20:09 +0000908 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
909 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000910 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman61dbdbd2008-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 } else if (Init->getType()->isFirstClassType()) {
921 GenericValue Val = getConstantValue(Init);
922 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
923 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 }
925
David Greene7050bcc2010-01-05 01:27:39 +0000926 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000927 llvm_unreachable("Unknown constant type to initialize memory with!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928}
929
930/// 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() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935
936 // Loop over all of the global variables in the program, allocating the memory
937 // 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;
942
943 if (Modules.size() != 1) {
944 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000945 Module &M = *Modules[m];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 for (Module::const_global_iterator I = M.global_begin(),
947 E = M.global_end(); I != E; ++I) {
948 const GlobalValue *GV = I;
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000949 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +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.
964 if (GVEntry->hasExternalLinkage() ||
965 GVEntry->hasDLLImportLinkage() ||
966 GVEntry->hasDLLExportLinkage())
967 continue;
968
969 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesen49c44122008-05-14 20:12:51 +0000970 // symbol. FIXME is this right for common?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
972 GVEntry = GV;
973 }
974 }
975 }
976
977 std::vector<const GlobalValue*> NonCanonicalGlobals;
978 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin62de4e72010-01-27 20:34:15 +0000979 Module &M = *Modules[m];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
994 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000995 addGlobalMapping(I, getMemoryForGV(I));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 } else {
997 // External variable reference. Try to use the dynamic loader to
998 // get a pointer to it.
999 if (void *SymAddr =
Daniel Dunbar9198e932009-07-21 08:54:24 +00001000 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 addGlobalMapping(I, SymAddr);
1002 else {
Edwin Törökf7cbfea2009-07-07 17:32:34 +00001003 llvm_report_error("Could not resolve external global address: "
1004 +I->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lopesec8dccb2008-10-14 10:04:52 +00001018 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 }
1020 }
1021
1022 // Now that all of the globals are set up in memory, loop through them all
1023 // and initialize their contents.
1024 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1025 I != E; ++I) {
1026 if (!I->isDeclaration()) {
1027 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 }
1037}
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.
1042void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1043 void *GA = getPointerToGlobalIfAvailable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 if (GA == 0) {
1046 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1532008-10-25 15:41:43 +00001047 GA = getMemoryForGV(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 addGlobalMapping(GV, GA);
1049 }
Nicolas Geoffray46fa1532008-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 Sandsec4f97d2009-05-09 07:06:46 +00001056 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 NumInitBytes += (unsigned)GVSize;
1058 ++NumGlobals;
1059}
Jeffrey Yasskin2be24032009-10-13 17:42:08 +00001060
Jeffrey Yasskin6ddfe5c2009-10-23 22:37:43 +00001061ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1062 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin2be24032009-10-13 17:42:08 +00001063}
1064
Jeffrey Yasskin6ddfe5c2009-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 Yasskin2be24032009-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}