1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/IntrinsicLowering.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetData.h"
31 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
32 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
35 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
39 CurMod(*P->getModule()), MP(P) {
40 assert(P && "ModuleProvider is null?");
43 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
44 assert(M && "Module is null?");
47 ExecutionEngine::~ExecutionEngine() {
51 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
52 /// at the specified address.
54 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
55 MutexGuard locked(lock);
57 // If we haven't computed the reverse mapping yet, do so first.
58 if (state.getGlobalAddressReverseMap(locked).empty()) {
59 for (std::map<const GlobalValue*, void *>::iterator I =
60 state.getGlobalAddressMap(locked).begin(), E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
61 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, I->first));
64 std::map<void *, const GlobalValue*>::iterator I =
65 state.getGlobalAddressReverseMap(locked).find(Addr);
66 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
69 // CreateArgv - Turn a vector of strings into a nice argv style array of
70 // pointers to null terminated strings.
72 static void *CreateArgv(ExecutionEngine *EE,
73 const std::vector<std::string> &InputArgv) {
74 unsigned PtrSize = EE->getTargetData().getPointerSize();
75 char *Result = new char[(InputArgv.size()+1)*PtrSize];
77 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
78 const Type *SBytePtr = PointerType::get(Type::SByteTy);
80 for (unsigned i = 0; i != InputArgv.size(); ++i) {
81 unsigned Size = InputArgv[i].size()+1;
82 char *Dest = new char[Size];
83 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
85 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
88 // Endian safe: Result[i] = (PointerTy)Dest;
89 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
94 EE->StoreValueToMemory(PTOGV(0),
95 (GenericValue*)(Result+InputArgv.size()*PtrSize),
101 /// runStaticConstructorsDestructors - This method is used to execute all of
102 /// the static constructors or destructors for a module, depending on the
103 /// value of isDtors.
104 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
105 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
106 GlobalVariable *GV = CurMod.getNamedGlobal(Name);
107 if (!GV || GV->isExternal() || !GV->hasInternalLinkage()) return;
109 // Should be an array of '{ int, void ()* }' structs. The first value is the
110 // init priority, which we ignore.
111 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
112 if (!InitList) return;
113 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
114 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
115 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
117 Constant *FP = CS->getOperand(1);
118 if (FP->isNullValue())
119 return; // Found a null terminator, exit.
121 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
122 if (CE->getOpcode() == Instruction::Cast)
123 FP = CE->getOperand(0);
124 if (Function *F = dyn_cast<Function>(FP)) {
125 // Execute the ctor/dtor function!
126 runFunction(F, std::vector<GenericValue>());
131 /// runFunctionAsMain - This is a helper function which wraps runFunction to
132 /// handle the common task of starting up main with the specified argc, argv,
133 /// and envp parameters.
134 int ExecutionEngine::runFunctionAsMain(Function *Fn,
135 const std::vector<std::string> &argv,
136 const char * const * envp) {
137 std::vector<GenericValue> GVArgs;
139 GVArgc.IntVal = argv.size();
140 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
142 GVArgs.push_back(GVArgc); // Arg #0 = argc.
144 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
145 assert(((char **)GVTOP(GVArgs[1]))[0] &&
146 "argv[0] was null after CreateArgv");
148 std::vector<std::string> EnvVars;
149 for (unsigned i = 0; envp[i]; ++i)
150 EnvVars.push_back(envp[i]);
151 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
155 return runFunction(Fn, GVArgs).IntVal;
158 /// If possible, create a JIT, unless the caller specifically requests an
159 /// Interpreter or there's an error. If even an Interpreter cannot be created,
160 /// NULL is returned.
162 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
163 bool ForceInterpreter,
164 IntrinsicLowering *IL) {
165 ExecutionEngine *EE = 0;
167 // Unless the interpreter was explicitly selected, try making a JIT.
168 if (!ForceInterpreter && JITCtor)
169 EE = JITCtor(MP, IL);
171 // If we can't make a JIT, make an interpreter instead.
172 if (EE == 0 && InterpCtor)
173 EE = InterpCtor(MP, IL);
178 // Make sure we can resolve symbols in the program as well. The zero arg
179 // to the function tells DynamicLibrary to load the program, not a library.
180 sys::DynamicLibrary::LoadLibraryPermanently(0);
185 /// getPointerToGlobal - This returns the address of the specified global
186 /// value. This may involve code generation if it's a function.
188 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
189 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
190 return getPointerToFunction(F);
192 MutexGuard locked(lock);
193 void *p = state.getGlobalAddressMap(locked)[GV];
197 // Global variable might have been added since interpreter started.
198 if (GlobalVariable *GVar =
199 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
200 EmitGlobalVariable(GVar);
202 assert("Global hasn't had an address allocated yet!");
203 return state.getGlobalAddressMap(locked)[GV];
208 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
210 if (isa<UndefValue>(C)) return Result;
212 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
213 switch (CE->getOpcode()) {
214 case Instruction::GetElementPtr: {
215 Result = getConstantValue(CE->getOperand(0));
216 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
218 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
220 if (getTargetData().getPointerSize() == 4)
221 Result.IntVal += Offset;
223 Result.LongVal += Offset;
226 case Instruction::Cast: {
227 // We only need to handle a few cases here. Almost all casts will
228 // automatically fold, just the ones involving pointers won't.
230 Constant *Op = CE->getOperand(0);
231 GenericValue GV = getConstantValue(Op);
233 // Handle cast of pointer to pointer...
234 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
237 // Handle a cast of pointer to any integral type...
238 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
241 // Handle cast of integer to a pointer...
242 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
243 switch (Op->getType()->getTypeID()) {
244 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
245 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
246 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
247 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
248 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
249 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
250 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
251 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
252 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
253 default: assert(0 && "Unknown integral type!");
258 case Instruction::Add:
259 switch (CE->getOperand(0)->getType()->getTypeID()) {
260 default: assert(0 && "Bad add type!"); abort();
262 case Type::ULongTyID:
263 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
264 getConstantValue(CE->getOperand(1)).LongVal;
268 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
269 getConstantValue(CE->getOperand(1)).IntVal;
271 case Type::ShortTyID:
272 case Type::UShortTyID:
273 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
274 getConstantValue(CE->getOperand(1)).ShortVal;
276 case Type::SByteTyID:
277 case Type::UByteTyID:
278 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
279 getConstantValue(CE->getOperand(1)).SByteVal;
281 case Type::FloatTyID:
282 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
283 getConstantValue(CE->getOperand(1)).FloatVal;
285 case Type::DoubleTyID:
286 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
287 getConstantValue(CE->getOperand(1)).DoubleVal;
294 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
298 switch (C->getType()->getTypeID()) {
299 #define GET_CONST_VAL(TY, CTY, CLASS) \
300 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
301 GET_CONST_VAL(Bool , bool , ConstantBool);
302 GET_CONST_VAL(UByte , unsigned char , ConstantUInt);
303 GET_CONST_VAL(SByte , signed char , ConstantSInt);
304 GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
305 GET_CONST_VAL(Short , signed short , ConstantSInt);
306 GET_CONST_VAL(UInt , unsigned int , ConstantUInt);
307 GET_CONST_VAL(Int , signed int , ConstantSInt);
308 GET_CONST_VAL(ULong , uint64_t , ConstantUInt);
309 GET_CONST_VAL(Long , int64_t , ConstantSInt);
310 GET_CONST_VAL(Float , float , ConstantFP);
311 GET_CONST_VAL(Double , double , ConstantFP);
313 case Type::PointerTyID:
314 if (isa<ConstantPointerNull>(C))
315 Result.PointerVal = 0;
316 else if (const Function *F = dyn_cast<Function>(C))
317 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
318 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
319 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
321 assert(0 && "Unknown constant pointer type!");
324 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
332 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
334 if (getTargetData().isLittleEndian()) {
335 switch (Ty->getTypeID()) {
337 case Type::UByteTyID:
338 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
339 case Type::UShortTyID:
340 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
341 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
343 Store4BytesLittleEndian:
344 case Type::FloatTyID:
346 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
347 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
348 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
349 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
351 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
352 goto Store4BytesLittleEndian;
353 case Type::DoubleTyID:
354 case Type::ULongTyID:
356 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
357 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
358 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
359 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
360 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
361 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
362 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
363 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
366 std::cout << "Cannot store value of type " << *Ty << "!\n";
369 switch (Ty->getTypeID()) {
371 case Type::UByteTyID:
372 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
373 case Type::UShortTyID:
374 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
375 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
377 Store4BytesBigEndian:
378 case Type::FloatTyID:
380 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
381 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
382 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
383 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
385 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
386 goto Store4BytesBigEndian;
387 case Type::DoubleTyID:
388 case Type::ULongTyID:
390 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
391 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
392 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
393 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
394 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
395 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
396 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
397 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
400 std::cout << "Cannot store value of type " << *Ty << "!\n";
407 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
410 if (getTargetData().isLittleEndian()) {
411 switch (Ty->getTypeID()) {
413 case Type::UByteTyID:
414 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
415 case Type::UShortTyID:
416 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
417 ((unsigned)Ptr->Untyped[1] << 8);
419 Load4BytesLittleEndian:
420 case Type::FloatTyID:
422 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
423 ((unsigned)Ptr->Untyped[1] << 8) |
424 ((unsigned)Ptr->Untyped[2] << 16) |
425 ((unsigned)Ptr->Untyped[3] << 24);
427 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
428 goto Load4BytesLittleEndian;
429 case Type::DoubleTyID:
430 case Type::ULongTyID:
431 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
432 ((uint64_t)Ptr->Untyped[1] << 8) |
433 ((uint64_t)Ptr->Untyped[2] << 16) |
434 ((uint64_t)Ptr->Untyped[3] << 24) |
435 ((uint64_t)Ptr->Untyped[4] << 32) |
436 ((uint64_t)Ptr->Untyped[5] << 40) |
437 ((uint64_t)Ptr->Untyped[6] << 48) |
438 ((uint64_t)Ptr->Untyped[7] << 56);
441 std::cout << "Cannot load value of type " << *Ty << "!\n";
445 switch (Ty->getTypeID()) {
447 case Type::UByteTyID:
448 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
449 case Type::UShortTyID:
450 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
451 ((unsigned)Ptr->Untyped[0] << 8);
454 case Type::FloatTyID:
456 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
457 ((unsigned)Ptr->Untyped[2] << 8) |
458 ((unsigned)Ptr->Untyped[1] << 16) |
459 ((unsigned)Ptr->Untyped[0] << 24);
461 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
462 goto Load4BytesBigEndian;
463 case Type::DoubleTyID:
464 case Type::ULongTyID:
465 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
466 ((uint64_t)Ptr->Untyped[6] << 8) |
467 ((uint64_t)Ptr->Untyped[5] << 16) |
468 ((uint64_t)Ptr->Untyped[4] << 24) |
469 ((uint64_t)Ptr->Untyped[3] << 32) |
470 ((uint64_t)Ptr->Untyped[2] << 40) |
471 ((uint64_t)Ptr->Untyped[1] << 48) |
472 ((uint64_t)Ptr->Untyped[0] << 56);
475 std::cout << "Cannot load value of type " << *Ty << "!\n";
482 // InitializeMemory - Recursive function to apply a Constant value into the
483 // specified memory location...
485 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
486 if (isa<UndefValue>(Init)) {
488 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
489 unsigned ElementSize =
490 getTargetData().getTypeSize(CP->getType()->getElementType());
491 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
492 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
494 } else if (Init->getType()->isFirstClassType()) {
495 GenericValue Val = getConstantValue(Init);
496 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
498 } else if (isa<ConstantAggregateZero>(Init)) {
499 memset(Addr, 0, (size_t)getTargetData().getTypeSize(Init->getType()));
503 switch (Init->getType()->getTypeID()) {
504 case Type::ArrayTyID: {
505 const ConstantArray *CPA = cast<ConstantArray>(Init);
506 unsigned ElementSize =
507 getTargetData().getTypeSize(CPA->getType()->getElementType());
508 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
509 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
513 case Type::StructTyID: {
514 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
515 const StructLayout *SL =
516 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
517 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
518 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
523 std::cerr << "Bad Type: " << *Init->getType() << "\n";
524 assert(0 && "Unknown constant type to initialize memory with!");
528 /// EmitGlobals - Emit all of the global variables to memory, storing their
529 /// addresses into GlobalAddress. This must make sure to copy the contents of
530 /// their initializers into the memory.
532 void ExecutionEngine::emitGlobals() {
533 const TargetData &TD = getTargetData();
535 // Loop over all of the global variables in the program, allocating the memory
537 Module &M = getModule();
538 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
540 if (!I->isExternal()) {
541 // Get the type of the global...
542 const Type *Ty = I->getType()->getElementType();
544 // Allocate some memory for it!
545 unsigned Size = TD.getTypeSize(Ty);
546 addGlobalMapping(I, new char[Size]);
548 // External variable reference. Try to use the dynamic loader to
549 // get a pointer to it.
550 if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
551 I->getName().c_str()))
552 addGlobalMapping(I, SymAddr);
554 std::cerr << "Could not resolve external global address: "
555 << I->getName() << "\n";
560 // Now that all of the globals are set up in memory, loop through them all and
561 // initialize their contents.
562 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
564 if (!I->isExternal())
565 EmitGlobalVariable(I);
568 // EmitGlobalVariable - This method emits the specified global variable to the
569 // address specified in GlobalAddresses, or allocates new memory if it's not
570 // already in the map.
571 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
572 void *GA = getPointerToGlobalIfAvailable(GV);
573 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
575 const Type *ElTy = GV->getType()->getElementType();
576 size_t GVSize = (size_t)getTargetData().getTypeSize(ElTy);
578 // If it's not already specified, allocate memory for the global.
579 GA = new char[GVSize];
580 addGlobalMapping(GV, GA);
583 InitializeMemory(GV->getInitializer(), GA);
584 NumInitBytes += (unsigned)GVSize;