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 "Interpreter/Interpreter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/IntrinsicLowering.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/DynamicLinker.h"
32 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
33 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
37 CurMod(*P->getModule()), MP(P) {
38 assert(P && "ModuleProvider is null?");
41 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
42 assert(M && "Module is null?");
45 ExecutionEngine::~ExecutionEngine() {
49 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
50 /// at the specified address.
52 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
53 // If we haven't computed the reverse mapping yet, do so first.
54 if (GlobalAddressReverseMap.empty()) {
55 for (std::map<const GlobalValue*, void *>::iterator I =
56 GlobalAddressMap.begin(), E = GlobalAddressMap.end(); I != E; ++I)
57 GlobalAddressReverseMap.insert(std::make_pair(I->second, I->first));
60 std::map<void *, const GlobalValue*>::iterator I =
61 GlobalAddressReverseMap.find(Addr);
62 return I != GlobalAddressReverseMap.end() ? I->second : 0;
65 // CreateArgv - Turn a vector of strings into a nice argv style array of
66 // pointers to null terminated strings.
68 static void *CreateArgv(ExecutionEngine *EE,
69 const std::vector<std::string> &InputArgv) {
70 unsigned PtrSize = EE->getTargetData().getPointerSize();
71 char *Result = new char[(InputArgv.size()+1)*PtrSize];
73 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
74 const Type *SBytePtr = PointerType::get(Type::SByteTy);
76 for (unsigned i = 0; i != InputArgv.size(); ++i) {
77 unsigned Size = InputArgv[i].size()+1;
78 char *Dest = new char[Size];
79 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
81 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
84 // Endian safe: Result[i] = (PointerTy)Dest;
85 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
90 EE->StoreValueToMemory(PTOGV(0),
91 (GenericValue*)(Result+InputArgv.size()*PtrSize),
96 /// runFunctionAsMain - This is a helper function which wraps runFunction to
97 /// handle the common task of starting up main with the specified argc, argv,
98 /// and envp parameters.
99 int ExecutionEngine::runFunctionAsMain(Function *Fn,
100 const std::vector<std::string> &argv,
101 const char * const * envp) {
102 std::vector<GenericValue> GVArgs;
104 GVArgc.IntVal = argv.size();
105 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
107 GVArgs.push_back(GVArgc); // Arg #0 = argc.
109 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
110 assert(((char **)GVTOP(GVArgs[1]))[0] &&
111 "argv[0] was null after CreateArgv");
113 std::vector<std::string> EnvVars;
114 for (unsigned i = 0; envp[i]; ++i)
115 EnvVars.push_back(envp[i]);
116 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
120 return runFunction(Fn, GVArgs).IntVal;
125 /// If possible, create a JIT, unless the caller specifically requests an
126 /// Interpreter or there's an error. If even an Interpreter cannot be created,
127 /// NULL is returned.
129 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
130 bool ForceInterpreter,
131 IntrinsicLowering *IL) {
132 ExecutionEngine *EE = 0;
134 // Unless the interpreter was explicitly selected, try making a JIT.
135 if (!ForceInterpreter)
136 EE = JIT::create(MP, IL);
138 // If we can't make a JIT, make an interpreter instead.
141 Module *M = MP->materializeModule();
143 EE = Interpreter::create(M, IL);
145 std::cerr << "Error creating the interpreter!\n";
147 } catch (std::string& errmsg) {
148 std::cerr << "Error reading the bytecode file: " << errmsg << "\n";
150 std::cerr << "Error reading the bytecode file!\n";
154 if (EE == 0) delete IL;
158 /// getPointerToGlobal - This returns the address of the specified global
159 /// value. This may involve code generation if it's a function.
161 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
162 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
163 return getPointerToFunction(F);
165 assert(GlobalAddressMap[GV] && "Global hasn't had an address allocated yet?");
166 return GlobalAddressMap[GV];
171 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
173 if (isa<UndefValue>(C)) return Result;
175 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
176 switch (CE->getOpcode()) {
177 case Instruction::GetElementPtr: {
178 Result = getConstantValue(CE->getOperand(0));
179 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
181 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
183 Result.LongVal += Offset;
186 case Instruction::Cast: {
187 // We only need to handle a few cases here. Almost all casts will
188 // automatically fold, just the ones involving pointers won't.
190 Constant *Op = CE->getOperand(0);
191 GenericValue GV = getConstantValue(Op);
193 // Handle cast of pointer to pointer...
194 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
197 // Handle a cast of pointer to any integral type...
198 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
201 // Handle cast of integer to a pointer...
202 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
203 switch (Op->getType()->getTypeID()) {
204 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
205 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
206 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
207 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
208 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
209 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
210 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
211 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
212 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
213 default: assert(0 && "Unknown integral type!");
218 case Instruction::Add:
219 switch (CE->getOperand(0)->getType()->getTypeID()) {
220 default: assert(0 && "Bad add type!"); abort();
222 case Type::ULongTyID:
223 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
224 getConstantValue(CE->getOperand(1)).LongVal;
228 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
229 getConstantValue(CE->getOperand(1)).IntVal;
231 case Type::ShortTyID:
232 case Type::UShortTyID:
233 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
234 getConstantValue(CE->getOperand(1)).ShortVal;
236 case Type::SByteTyID:
237 case Type::UByteTyID:
238 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
239 getConstantValue(CE->getOperand(1)).SByteVal;
241 case Type::FloatTyID:
242 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
243 getConstantValue(CE->getOperand(1)).FloatVal;
245 case Type::DoubleTyID:
246 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
247 getConstantValue(CE->getOperand(1)).DoubleVal;
254 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
258 switch (C->getType()->getTypeID()) {
259 #define GET_CONST_VAL(TY, CLASS) \
260 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
261 GET_CONST_VAL(Bool , ConstantBool);
262 GET_CONST_VAL(UByte , ConstantUInt);
263 GET_CONST_VAL(SByte , ConstantSInt);
264 GET_CONST_VAL(UShort , ConstantUInt);
265 GET_CONST_VAL(Short , ConstantSInt);
266 GET_CONST_VAL(UInt , ConstantUInt);
267 GET_CONST_VAL(Int , ConstantSInt);
268 GET_CONST_VAL(ULong , ConstantUInt);
269 GET_CONST_VAL(Long , ConstantSInt);
270 GET_CONST_VAL(Float , ConstantFP);
271 GET_CONST_VAL(Double , ConstantFP);
273 case Type::PointerTyID:
274 if (isa<ConstantPointerNull>(C))
275 Result.PointerVal = 0;
276 else if (const Function *F = dyn_cast<Function>(C))
277 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
278 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
279 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
281 assert(0 && "Unknown constant pointer type!");
284 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
292 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
294 if (getTargetData().isLittleEndian()) {
295 switch (Ty->getTypeID()) {
297 case Type::UByteTyID:
298 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
299 case Type::UShortTyID:
300 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
301 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
303 Store4BytesLittleEndian:
304 case Type::FloatTyID:
306 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
307 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
308 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
309 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
311 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
312 goto Store4BytesLittleEndian;
313 case Type::DoubleTyID:
314 case Type::ULongTyID:
315 case Type::LongTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
316 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
317 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
318 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
319 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
320 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
321 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
322 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
325 std::cout << "Cannot store value of type " << *Ty << "!\n";
328 switch (Ty->getTypeID()) {
330 case Type::UByteTyID:
331 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
332 case Type::UShortTyID:
333 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
334 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
336 Store4BytesBigEndian:
337 case Type::FloatTyID:
339 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
340 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
341 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
342 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
344 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
345 goto Store4BytesBigEndian;
346 case Type::DoubleTyID:
347 case Type::ULongTyID:
348 case Type::LongTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
349 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
350 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
351 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
352 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
353 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
354 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
355 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
358 std::cout << "Cannot store value of type " << *Ty << "!\n";
365 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
368 if (getTargetData().isLittleEndian()) {
369 switch (Ty->getTypeID()) {
371 case Type::UByteTyID:
372 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
373 case Type::UShortTyID:
374 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
375 ((unsigned)Ptr->Untyped[1] << 8);
377 Load4BytesLittleEndian:
378 case Type::FloatTyID:
380 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
381 ((unsigned)Ptr->Untyped[1] << 8) |
382 ((unsigned)Ptr->Untyped[2] << 16) |
383 ((unsigned)Ptr->Untyped[3] << 24);
385 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
386 goto Load4BytesLittleEndian;
387 case Type::DoubleTyID:
388 case Type::ULongTyID:
389 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
390 ((uint64_t)Ptr->Untyped[1] << 8) |
391 ((uint64_t)Ptr->Untyped[2] << 16) |
392 ((uint64_t)Ptr->Untyped[3] << 24) |
393 ((uint64_t)Ptr->Untyped[4] << 32) |
394 ((uint64_t)Ptr->Untyped[5] << 40) |
395 ((uint64_t)Ptr->Untyped[6] << 48) |
396 ((uint64_t)Ptr->Untyped[7] << 56);
399 std::cout << "Cannot load value of type " << *Ty << "!\n";
403 switch (Ty->getTypeID()) {
405 case Type::UByteTyID:
406 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
407 case Type::UShortTyID:
408 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
409 ((unsigned)Ptr->Untyped[0] << 8);
412 case Type::FloatTyID:
414 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
415 ((unsigned)Ptr->Untyped[2] << 8) |
416 ((unsigned)Ptr->Untyped[1] << 16) |
417 ((unsigned)Ptr->Untyped[0] << 24);
419 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
420 goto Load4BytesBigEndian;
421 case Type::DoubleTyID:
422 case Type::ULongTyID:
423 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
424 ((uint64_t)Ptr->Untyped[6] << 8) |
425 ((uint64_t)Ptr->Untyped[5] << 16) |
426 ((uint64_t)Ptr->Untyped[4] << 24) |
427 ((uint64_t)Ptr->Untyped[3] << 32) |
428 ((uint64_t)Ptr->Untyped[2] << 40) |
429 ((uint64_t)Ptr->Untyped[1] << 48) |
430 ((uint64_t)Ptr->Untyped[0] << 56);
433 std::cout << "Cannot load value of type " << *Ty << "!\n";
440 // InitializeMemory - Recursive function to apply a Constant value into the
441 // specified memory location...
443 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
444 if (isa<UndefValue>(Init)) {
445 // FIXME: THIS SHOULD NOT BE NEEDED.
446 unsigned Size = getTargetData().getTypeSize(Init->getType());
447 memset(Addr, 0, Size);
449 } else if (Init->getType()->isFirstClassType()) {
450 GenericValue Val = getConstantValue(Init);
451 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
453 } else if (isa<ConstantAggregateZero>(Init)) {
454 unsigned Size = getTargetData().getTypeSize(Init->getType());
455 memset(Addr, 0, Size);
459 switch (Init->getType()->getTypeID()) {
460 case Type::ArrayTyID: {
461 const ConstantArray *CPA = cast<ConstantArray>(Init);
462 unsigned ElementSize =
463 getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
464 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
465 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
469 case Type::StructTyID: {
470 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
471 const StructLayout *SL =
472 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
473 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
474 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
479 std::cerr << "Bad Type: " << *Init->getType() << "\n";
480 assert(0 && "Unknown constant type to initialize memory with!");
484 /// EmitGlobals - Emit all of the global variables to memory, storing their
485 /// addresses into GlobalAddress. This must make sure to copy the contents of
486 /// their initializers into the memory.
488 void ExecutionEngine::emitGlobals() {
489 const TargetData &TD = getTargetData();
491 // Loop over all of the global variables in the program, allocating the memory
493 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
495 if (!I->isExternal()) {
496 // Get the type of the global...
497 const Type *Ty = I->getType()->getElementType();
499 // Allocate some memory for it!
500 unsigned Size = TD.getTypeSize(Ty);
501 addGlobalMapping(I, new char[Size]);
503 // External variable reference. Try to use the dynamic loader to
504 // get a pointer to it.
505 if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
506 addGlobalMapping(I, SymAddr);
508 std::cerr << "Could not resolve external global address: "
509 << I->getName() << "\n";
514 // Now that all of the globals are set up in memory, loop through them all and
515 // initialize their contents.
516 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
518 if (!I->isExternal())
519 EmitGlobalVariable(I);
522 // EmitGlobalVariable - This method emits the specified global variable to the
523 // address specified in GlobalAddresses, or allocates new memory if it's not
524 // already in the map.
525 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
526 void *GA = getPointerToGlobalIfAvailable(GV);
527 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
529 const Type *ElTy = GV->getType()->getElementType();
530 unsigned GVSize = getTargetData().getTypeSize(ElTy);
532 // If it's not already specified, allocate memory for the global.
533 GA = new char[GVSize];
534 addGlobalMapping(GV, GA);
537 InitializeMemory(GV->getInitializer(), GA);
538 NumInitBytes += GVSize;