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/IntrinsicLowering.h"
21 #include "llvm/Module.h"
22 #include "llvm/ModuleProvider.h"
23 #include "llvm/ExecutionEngine/ExecutionEngine.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/Target/TargetData.h"
26 #include "Support/Debug.h"
27 #include "Support/Statistic.h"
28 #include "Support/DynamicLinker.h"
29 #include "Config/dlfcn.h"
33 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
34 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
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() {
51 // CreateArgv - Turn a vector of strings into a nice argv style array of
52 // pointers to null terminated strings.
54 static void *CreateArgv(ExecutionEngine *EE,
55 const std::vector<std::string> &InputArgv) {
56 unsigned PtrSize = EE->getTargetData().getPointerSize();
57 char *Result = new char[(InputArgv.size()+1)*PtrSize];
59 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
60 const Type *SBytePtr = PointerType::get(Type::SByteTy);
62 for (unsigned i = 0; i != InputArgv.size(); ++i) {
63 unsigned Size = InputArgv[i].size()+1;
64 char *Dest = new char[Size];
65 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
67 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
70 // Endian safe: Result[i] = (PointerTy)Dest;
71 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
76 EE->StoreValueToMemory(PTOGV(0),
77 (GenericValue*)(Result+InputArgv.size()*PtrSize),
82 /// runFunctionAsMain - This is a helper function which wraps runFunction to
83 /// handle the common task of starting up main with the specified argc, argv,
84 /// and envp parameters.
85 int ExecutionEngine::runFunctionAsMain(Function *Fn,
86 const std::vector<std::string> &argv,
87 const char * const * envp) {
88 std::vector<GenericValue> GVArgs;
90 GVArgc.IntVal = argv.size();
91 GVArgs.push_back(GVArgc); // Arg #0 = argc.
92 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
93 assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv");
95 std::vector<std::string> EnvVars;
96 for (unsigned i = 0; envp[i]; ++i)
97 EnvVars.push_back(envp[i]);
98 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
99 return runFunction(Fn, GVArgs).IntVal;
104 /// If possible, create a JIT, unless the caller specifically requests an
105 /// Interpreter or there's an error. If even an Interpreter cannot be created,
106 /// NULL is returned.
108 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
109 bool ForceInterpreter,
110 IntrinsicLowering *IL) {
111 ExecutionEngine *EE = 0;
113 // Unless the interpreter was explicitly selected, try making a JIT.
114 if (!ForceInterpreter)
115 EE = JIT::create(MP, IL);
117 // If we can't make a JIT, make an interpreter instead.
120 EE = Interpreter::create(MP->materializeModule(), IL);
125 if (EE == 0) delete IL;
129 /// getPointerToGlobal - This returns the address of the specified global
130 /// value. This may involve code generation if it's a function.
132 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
133 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
134 return getPointerToFunction(F);
136 assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
137 return GlobalAddress[GV];
142 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
145 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
146 switch (CE->getOpcode()) {
147 case Instruction::GetElementPtr: {
148 Result = getConstantValue(CE->getOperand(0));
149 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
151 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
153 Result.LongVal += Offset;
156 case Instruction::Cast: {
157 // We only need to handle a few cases here. Almost all casts will
158 // automatically fold, just the ones involving pointers won't.
160 Constant *Op = CE->getOperand(0);
162 // Handle cast of pointer to pointer...
163 if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
164 return getConstantValue(Op);
166 // Handle a cast of pointer to any integral type...
167 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
168 return getConstantValue(Op);
170 // Handle cast of long to pointer...
171 if (isa<PointerType>(C->getType()) && (Op->getType() == Type::LongTy ||
172 Op->getType() == Type::ULongTy))
173 return getConstantValue(Op);
177 case Instruction::Add:
178 if (CE->getOperand(0)->getType() == Type::LongTy ||
179 CE->getOperand(0)->getType() == Type::ULongTy)
180 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
181 getConstantValue(CE->getOperand(1)).LongVal;
189 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
193 switch (C->getType()->getPrimitiveID()) {
194 #define GET_CONST_VAL(TY, CLASS) \
195 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
196 GET_CONST_VAL(Bool , ConstantBool);
197 GET_CONST_VAL(UByte , ConstantUInt);
198 GET_CONST_VAL(SByte , ConstantSInt);
199 GET_CONST_VAL(UShort , ConstantUInt);
200 GET_CONST_VAL(Short , ConstantSInt);
201 GET_CONST_VAL(UInt , ConstantUInt);
202 GET_CONST_VAL(Int , ConstantSInt);
203 GET_CONST_VAL(ULong , ConstantUInt);
204 GET_CONST_VAL(Long , ConstantSInt);
205 GET_CONST_VAL(Float , ConstantFP);
206 GET_CONST_VAL(Double , ConstantFP);
208 case Type::PointerTyID:
209 if (isa<ConstantPointerNull>(C)) {
210 Result.PointerVal = 0;
211 } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
213 const_cast<Function*>(dyn_cast<Function>(CPR->getValue())))
214 Result = PTOGV(getPointerToFunctionOrStub(F));
216 Result = PTOGV(getOrEmitGlobalVariable(
217 cast<GlobalVariable>(CPR->getValue())));
220 assert(0 && "Unknown constant pointer type!");
224 std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
232 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
234 if (getTargetData().isLittleEndian()) {
235 switch (Ty->getPrimitiveID()) {
237 case Type::UByteTyID:
238 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
239 case Type::UShortTyID:
240 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
241 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
243 Store4BytesLittleEndian:
244 case Type::FloatTyID:
246 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
247 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
248 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
249 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
251 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
252 goto Store4BytesLittleEndian;
253 case Type::DoubleTyID:
254 case Type::ULongTyID:
255 case Type::LongTyID: Ptr->Untyped[0] = Val.ULongVal & 255;
256 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255;
257 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
258 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
259 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
260 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
261 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
262 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
265 std::cout << "Cannot store value of type " << Ty << "!\n";
268 switch (Ty->getPrimitiveID()) {
270 case Type::UByteTyID:
271 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
272 case Type::UShortTyID:
273 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
274 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
276 Store4BytesBigEndian:
277 case Type::FloatTyID:
279 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
280 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
281 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
282 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
284 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
285 goto Store4BytesBigEndian;
286 case Type::DoubleTyID:
287 case Type::ULongTyID:
288 case Type::LongTyID: Ptr->Untyped[7] = Val.ULongVal & 255;
289 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255;
290 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
291 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
292 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
293 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
294 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
295 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
298 std::cout << "Cannot store value of type " << Ty << "!\n";
305 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
308 if (getTargetData().isLittleEndian()) {
309 switch (Ty->getPrimitiveID()) {
311 case Type::UByteTyID:
312 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
313 case Type::UShortTyID:
314 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
315 ((unsigned)Ptr->Untyped[1] << 8);
317 Load4BytesLittleEndian:
318 case Type::FloatTyID:
320 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
321 ((unsigned)Ptr->Untyped[1] << 8) |
322 ((unsigned)Ptr->Untyped[2] << 16) |
323 ((unsigned)Ptr->Untyped[3] << 24);
325 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
326 goto Load4BytesLittleEndian;
327 case Type::DoubleTyID:
328 case Type::ULongTyID:
329 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
330 ((uint64_t)Ptr->Untyped[1] << 8) |
331 ((uint64_t)Ptr->Untyped[2] << 16) |
332 ((uint64_t)Ptr->Untyped[3] << 24) |
333 ((uint64_t)Ptr->Untyped[4] << 32) |
334 ((uint64_t)Ptr->Untyped[5] << 40) |
335 ((uint64_t)Ptr->Untyped[6] << 48) |
336 ((uint64_t)Ptr->Untyped[7] << 56);
339 std::cout << "Cannot load value of type " << *Ty << "!\n";
343 switch (Ty->getPrimitiveID()) {
345 case Type::UByteTyID:
346 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
347 case Type::UShortTyID:
348 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
349 ((unsigned)Ptr->Untyped[0] << 8);
352 case Type::FloatTyID:
354 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
355 ((unsigned)Ptr->Untyped[2] << 8) |
356 ((unsigned)Ptr->Untyped[1] << 16) |
357 ((unsigned)Ptr->Untyped[0] << 24);
359 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
360 goto Load4BytesBigEndian;
361 case Type::DoubleTyID:
362 case Type::ULongTyID:
363 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
364 ((uint64_t)Ptr->Untyped[6] << 8) |
365 ((uint64_t)Ptr->Untyped[5] << 16) |
366 ((uint64_t)Ptr->Untyped[4] << 24) |
367 ((uint64_t)Ptr->Untyped[3] << 32) |
368 ((uint64_t)Ptr->Untyped[2] << 40) |
369 ((uint64_t)Ptr->Untyped[1] << 48) |
370 ((uint64_t)Ptr->Untyped[0] << 56);
373 std::cout << "Cannot load value of type " << *Ty << "!\n";
380 // InitializeMemory - Recursive function to apply a Constant value into the
381 // specified memory location...
383 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
384 if (Init->getType()->isFirstClassType()) {
385 GenericValue Val = getConstantValue(Init);
386 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
390 switch (Init->getType()->getPrimitiveID()) {
391 case Type::ArrayTyID: {
392 const ConstantArray *CPA = cast<ConstantArray>(Init);
393 const std::vector<Use> &Val = CPA->getValues();
394 unsigned ElementSize =
395 getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
396 for (unsigned i = 0; i < Val.size(); ++i)
397 InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
401 case Type::StructTyID: {
402 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
403 const StructLayout *SL =
404 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
405 const std::vector<Use> &Val = CPS->getValues();
406 for (unsigned i = 0; i < Val.size(); ++i)
407 InitializeMemory(cast<Constant>(Val[i].get()),
408 (char*)Addr+SL->MemberOffsets[i]);
413 std::cerr << "Bad Type: " << Init->getType() << "\n";
414 assert(0 && "Unknown constant type to initialize memory with!");
418 /// EmitGlobals - Emit all of the global variables to memory, storing their
419 /// addresses into GlobalAddress. This must make sure to copy the contents of
420 /// their initializers into the memory.
422 void ExecutionEngine::emitGlobals() {
423 const TargetData &TD = getTargetData();
425 // Loop over all of the global variables in the program, allocating the memory
427 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
429 if (!I->isExternal()) {
430 // Get the type of the global...
431 const Type *Ty = I->getType()->getElementType();
433 // Allocate some memory for it!
434 unsigned Size = TD.getTypeSize(Ty);
435 addGlobalMapping(I, new char[Size]);
437 DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
438 << (void*)GlobalAddress[I] << "\n");
440 // External variable reference. Try to use the dynamic loader to
441 // get a pointer to it.
442 if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
443 GlobalAddress[I] = SymAddr;
445 std::cerr << "Could not resolve external global address: "
446 << I->getName() << "\n";
451 // Now that all of the globals are set up in memory, loop through them all and
452 // initialize their contents.
453 for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
455 if (!I->isExternal())
456 EmitGlobalVariable(I);
459 // EmitGlobalVariable - This method emits the specified global variable to the
460 // address specified in GlobalAddresses, or allocates new memory if it's not
461 // already in the map.
462 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
463 void *&GA = GlobalAddress[GV];
464 const Type *ElTy = GV->getType()->getElementType();
466 // If it's not already specified, allocate memory for the global.
467 GA = new char[getTargetData().getTypeSize(ElTy)];
470 InitializeMemory(GV->getInitializer(), GA);
471 NumInitBytes += getTargetData().getTypeSize(ElTy);