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/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/System/DynamicLibrary.h"
25 #include "llvm/Target/TargetData.h"
30 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
31 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
34 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
35 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
37 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
38 CurMod(*P->getModule()), MP(P) {
39 assert(P && "ModuleProvider is null?");
42 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
43 assert(M && "Module is null?");
46 ExecutionEngine::~ExecutionEngine() {
50 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
51 /// at the specified address.
53 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
54 MutexGuard locked(lock);
56 // If we haven't computed the reverse mapping yet, do so first.
57 if (state.getGlobalAddressReverseMap(locked).empty()) {
58 for (std::map<const GlobalValue*, void *>::iterator I =
59 state.getGlobalAddressMap(locked).begin(), E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
60 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, I->first));
63 std::map<void *, const GlobalValue*>::iterator I =
64 state.getGlobalAddressReverseMap(locked).find(Addr);
65 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
68 // CreateArgv - Turn a vector of strings into a nice argv style array of
69 // pointers to null terminated strings.
71 static void *CreateArgv(ExecutionEngine *EE,
72 const std::vector<std::string> &InputArgv) {
73 unsigned PtrSize = EE->getTargetData().getPointerSize();
74 char *Result = new char[(InputArgv.size()+1)*PtrSize];
76 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
77 const Type *SBytePtr = PointerType::get(Type::SByteTy);
79 for (unsigned i = 0; i != InputArgv.size(); ++i) {
80 unsigned Size = InputArgv[i].size()+1;
81 char *Dest = new char[Size];
82 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
84 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
87 // Endian safe: Result[i] = (PointerTy)Dest;
88 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
93 EE->StoreValueToMemory(PTOGV(0),
94 (GenericValue*)(Result+InputArgv.size()*PtrSize),
100 /// runStaticConstructorsDestructors - This method is used to execute all of
101 /// the static constructors or destructors for a module, depending on the
102 /// value of isDtors.
103 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
104 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
105 GlobalVariable *GV = CurMod.getNamedGlobal(Name);
106 if (!GV || GV->isExternal() || !GV->hasInternalLinkage()) return;
108 // Should be an array of '{ int, void ()* }' structs. The first value is the
109 // init priority, which we ignore.
110 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
111 if (!InitList) return;
112 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
113 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
114 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
116 Constant *FP = CS->getOperand(1);
117 if (FP->isNullValue())
118 return; // Found a null terminator, exit.
120 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
121 if (CE->getOpcode() == Instruction::Cast)
122 FP = CE->getOperand(0);
123 if (Function *F = dyn_cast<Function>(FP)) {
124 // Execute the ctor/dtor function!
125 runFunction(F, std::vector<GenericValue>());
130 /// runFunctionAsMain - This is a helper function which wraps runFunction to
131 /// handle the common task of starting up main with the specified argc, argv,
132 /// and envp parameters.
133 int ExecutionEngine::runFunctionAsMain(Function *Fn,
134 const std::vector<std::string> &argv,
135 const char * const * envp) {
136 std::vector<GenericValue> GVArgs;
138 GVArgc.IntVal = argv.size();
139 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
141 GVArgs.push_back(GVArgc); // Arg #0 = argc.
143 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
144 assert(((char **)GVTOP(GVArgs[1]))[0] &&
145 "argv[0] was null after CreateArgv");
147 std::vector<std::string> EnvVars;
148 for (unsigned i = 0; envp[i]; ++i)
149 EnvVars.push_back(envp[i]);
150 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
154 return runFunction(Fn, GVArgs).IntVal;
157 /// If possible, create a JIT, unless the caller specifically requests an
158 /// Interpreter or there's an error. If even an Interpreter cannot be created,
159 /// NULL is returned.
161 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
162 bool ForceInterpreter) {
163 ExecutionEngine *EE = 0;
165 // Unless the interpreter was explicitly selected, try making a JIT.
166 if (!ForceInterpreter && JITCtor)
169 // If we can't make a JIT, make an interpreter instead.
170 if (EE == 0 && InterpCtor)
174 // Make sure we can resolve symbols in the program as well. The zero arg
175 // to the function tells DynamicLibrary to load the program, not a library.
176 sys::DynamicLibrary::LoadLibraryPermanently(0);
182 /// getPointerToGlobal - This returns the address of the specified global
183 /// value. This may involve code generation if it's a function.
185 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
186 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
187 return getPointerToFunction(F);
189 MutexGuard locked(lock);
190 void *p = state.getGlobalAddressMap(locked)[GV];
194 // Global variable might have been added since interpreter started.
195 if (GlobalVariable *GVar =
196 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
197 EmitGlobalVariable(GVar);
199 assert("Global hasn't had an address allocated yet!");
200 return state.getGlobalAddressMap(locked)[GV];
205 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
207 if (isa<UndefValue>(C)) return Result;
209 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
210 switch (CE->getOpcode()) {
211 case Instruction::GetElementPtr: {
212 Result = getConstantValue(CE->getOperand(0));
213 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
215 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
217 if (getTargetData().getPointerSize() == 4)
218 Result.IntVal += Offset;
220 Result.LongVal += Offset;
223 case Instruction::Cast: {
224 // We only need to handle a few cases here. Almost all casts will
225 // automatically fold, just the ones involving pointers won't.
227 Constant *Op = CE->getOperand(0);
228 GenericValue GV = getConstantValue(Op);
230 // Handle cast of pointer to pointer...
231 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
234 // Handle a cast of pointer to any integral type...
235 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
238 // Handle cast of integer to a pointer...
239 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
240 switch (Op->getType()->getTypeID()) {
241 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
242 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
243 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
244 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
245 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
246 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
247 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
248 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
249 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
250 default: assert(0 && "Unknown integral type!");
255 case Instruction::Add:
256 switch (CE->getOperand(0)->getType()->getTypeID()) {
257 default: assert(0 && "Bad add type!"); abort();
259 case Type::ULongTyID:
260 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
261 getConstantValue(CE->getOperand(1)).LongVal;
265 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
266 getConstantValue(CE->getOperand(1)).IntVal;
268 case Type::ShortTyID:
269 case Type::UShortTyID:
270 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
271 getConstantValue(CE->getOperand(1)).ShortVal;
273 case Type::SByteTyID:
274 case Type::UByteTyID:
275 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
276 getConstantValue(CE->getOperand(1)).SByteVal;
278 case Type::FloatTyID:
279 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
280 getConstantValue(CE->getOperand(1)).FloatVal;
282 case Type::DoubleTyID:
283 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
284 getConstantValue(CE->getOperand(1)).DoubleVal;
291 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
295 switch (C->getType()->getTypeID()) {
296 #define GET_CONST_VAL(TY, CTY, CLASS) \
297 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
298 GET_CONST_VAL(Bool , bool , ConstantBool);
299 GET_CONST_VAL(UByte , unsigned char , ConstantUInt);
300 GET_CONST_VAL(SByte , signed char , ConstantSInt);
301 GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
302 GET_CONST_VAL(Short , signed short , ConstantSInt);
303 GET_CONST_VAL(UInt , unsigned int , ConstantUInt);
304 GET_CONST_VAL(Int , signed int , ConstantSInt);
305 GET_CONST_VAL(ULong , uint64_t , ConstantUInt);
306 GET_CONST_VAL(Long , int64_t , ConstantSInt);
307 GET_CONST_VAL(Float , float , ConstantFP);
308 GET_CONST_VAL(Double , double , ConstantFP);
310 case Type::PointerTyID:
311 if (isa<ConstantPointerNull>(C))
312 Result.PointerVal = 0;
313 else if (const Function *F = dyn_cast<Function>(C))
314 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
315 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
316 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
318 assert(0 && "Unknown constant pointer type!");
321 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
329 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
331 if (getTargetData().isLittleEndian()) {
332 switch (Ty->getTypeID()) {
334 case Type::UByteTyID:
335 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
336 case Type::UShortTyID:
337 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
338 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
340 Store4BytesLittleEndian:
341 case Type::FloatTyID:
343 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
344 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
345 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
346 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
348 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
349 goto Store4BytesLittleEndian;
350 case Type::DoubleTyID:
351 case Type::ULongTyID:
353 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
354 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
355 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
356 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
357 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
358 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
359 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
360 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
363 std::cout << "Cannot store value of type " << *Ty << "!\n";
366 switch (Ty->getTypeID()) {
368 case Type::UByteTyID:
369 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
370 case Type::UShortTyID:
371 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
372 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
374 Store4BytesBigEndian:
375 case Type::FloatTyID:
377 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
378 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
379 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
380 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
382 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
383 goto Store4BytesBigEndian;
384 case Type::DoubleTyID:
385 case Type::ULongTyID:
387 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
388 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
389 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
390 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
391 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
392 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
393 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
394 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
397 std::cout << "Cannot store value of type " << *Ty << "!\n";
404 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
407 if (getTargetData().isLittleEndian()) {
408 switch (Ty->getTypeID()) {
410 case Type::UByteTyID:
411 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
412 case Type::UShortTyID:
413 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
414 ((unsigned)Ptr->Untyped[1] << 8);
416 Load4BytesLittleEndian:
417 case Type::FloatTyID:
419 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
420 ((unsigned)Ptr->Untyped[1] << 8) |
421 ((unsigned)Ptr->Untyped[2] << 16) |
422 ((unsigned)Ptr->Untyped[3] << 24);
424 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
425 goto Load4BytesLittleEndian;
426 case Type::DoubleTyID:
427 case Type::ULongTyID:
428 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
429 ((uint64_t)Ptr->Untyped[1] << 8) |
430 ((uint64_t)Ptr->Untyped[2] << 16) |
431 ((uint64_t)Ptr->Untyped[3] << 24) |
432 ((uint64_t)Ptr->Untyped[4] << 32) |
433 ((uint64_t)Ptr->Untyped[5] << 40) |
434 ((uint64_t)Ptr->Untyped[6] << 48) |
435 ((uint64_t)Ptr->Untyped[7] << 56);
438 std::cout << "Cannot load value of type " << *Ty << "!\n";
442 switch (Ty->getTypeID()) {
444 case Type::UByteTyID:
445 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
446 case Type::UShortTyID:
447 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
448 ((unsigned)Ptr->Untyped[0] << 8);
451 case Type::FloatTyID:
453 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
454 ((unsigned)Ptr->Untyped[2] << 8) |
455 ((unsigned)Ptr->Untyped[1] << 16) |
456 ((unsigned)Ptr->Untyped[0] << 24);
458 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
459 goto Load4BytesBigEndian;
460 case Type::DoubleTyID:
461 case Type::ULongTyID:
462 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
463 ((uint64_t)Ptr->Untyped[6] << 8) |
464 ((uint64_t)Ptr->Untyped[5] << 16) |
465 ((uint64_t)Ptr->Untyped[4] << 24) |
466 ((uint64_t)Ptr->Untyped[3] << 32) |
467 ((uint64_t)Ptr->Untyped[2] << 40) |
468 ((uint64_t)Ptr->Untyped[1] << 48) |
469 ((uint64_t)Ptr->Untyped[0] << 56);
472 std::cout << "Cannot load value of type " << *Ty << "!\n";
479 // InitializeMemory - Recursive function to apply a Constant value into the
480 // specified memory location...
482 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
483 if (isa<UndefValue>(Init)) {
485 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
486 unsigned ElementSize =
487 getTargetData().getTypeSize(CP->getType()->getElementType());
488 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
489 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
491 } else if (Init->getType()->isFirstClassType()) {
492 GenericValue Val = getConstantValue(Init);
493 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
495 } else if (isa<ConstantAggregateZero>(Init)) {
496 memset(Addr, 0, (size_t)getTargetData().getTypeSize(Init->getType()));
500 switch (Init->getType()->getTypeID()) {
501 case Type::ArrayTyID: {
502 const ConstantArray *CPA = cast<ConstantArray>(Init);
503 unsigned ElementSize =
504 getTargetData().getTypeSize(CPA->getType()->getElementType());
505 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
506 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
510 case Type::StructTyID: {
511 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
512 const StructLayout *SL =
513 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
514 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
515 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
520 std::cerr << "Bad Type: " << *Init->getType() << "\n";
521 assert(0 && "Unknown constant type to initialize memory with!");
525 /// EmitGlobals - Emit all of the global variables to memory, storing their
526 /// addresses into GlobalAddress. This must make sure to copy the contents of
527 /// their initializers into the memory.
529 void ExecutionEngine::emitGlobals() {
530 const TargetData &TD = getTargetData();
532 // Loop over all of the global variables in the program, allocating the memory
534 Module &M = getModule();
535 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
537 if (!I->isExternal()) {
538 // Get the type of the global...
539 const Type *Ty = I->getType()->getElementType();
541 // Allocate some memory for it!
542 unsigned Size = TD.getTypeSize(Ty);
543 addGlobalMapping(I, new char[Size]);
545 // External variable reference. Try to use the dynamic loader to
546 // get a pointer to it.
547 if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
548 I->getName().c_str()))
549 addGlobalMapping(I, SymAddr);
551 std::cerr << "Could not resolve external global address: "
552 << I->getName() << "\n";
557 // Now that all of the globals are set up in memory, loop through them all and
558 // initialize their contents.
559 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
561 if (!I->isExternal())
562 EmitGlobalVariable(I);
565 // EmitGlobalVariable - This method emits the specified global variable to the
566 // address specified in GlobalAddresses, or allocates new memory if it's not
567 // already in the map.
568 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
569 void *GA = getPointerToGlobalIfAvailable(GV);
570 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
572 const Type *ElTy = GV->getType()->getElementType();
573 size_t GVSize = (size_t)getTargetData().getTypeSize(ElTy);
575 // If it's not already specified, allocate memory for the global.
576 GA = new char[GVSize];
577 addGlobalMapping(GV, GA);
580 InitializeMemory(GV->getInitializer(), GA);
581 NumInitBytes += (unsigned)GVSize;