Factor code out of LLI
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
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"
16 #include "Interpreter/Interpreter.h"
17 #include "JIT/JIT.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Target/TargetData.h"
25 #include "Support/Debug.h"
26 #include "Support/Statistic.h"
27 #include "Support/DynamicLinker.h"
28 #include "Config/dlfcn.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
33   Statistic<> NumGlobals  ("lli", "Number of global vars initialized");
34 }
35
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : 
37   CurMod(*P->getModule()), MP(P) {
38   assert(P && "ModuleProvider is null?");
39 }
40
41 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
42   assert(M && "Module is null?");
43 }
44
45 ExecutionEngine::~ExecutionEngine() {
46   delete MP;
47 }
48
49
50 // CreateArgv - Turn a vector of strings into a nice argv style array of
51 // pointers to null terminated strings.
52 //
53 static void *CreateArgv(ExecutionEngine *EE,
54                         const std::vector<std::string> &InputArgv) {
55   unsigned PtrSize = EE->getTargetData().getPointerSize();
56   char *Result = new char[(InputArgv.size()+1)*PtrSize];
57
58   DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
59   const Type *SBytePtr = PointerType::get(Type::SByteTy);
60
61   for (unsigned i = 0; i != InputArgv.size(); ++i) {
62     unsigned Size = InputArgv[i].size()+1;
63     char *Dest = new char[Size];
64     DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
65       
66     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
67     Dest[Size-1] = 0;
68       
69     // Endian safe: Result[i] = (PointerTy)Dest;
70     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
71                            SBytePtr);
72   }
73
74   // Null terminate it
75   EE->StoreValueToMemory(PTOGV(0),
76                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
77                          SBytePtr);
78   return Result;
79 }
80
81 /// runFunctionAsMain - This is a helper function which wraps runFunction to
82 /// handle the common task of starting up main with the specified argc, argv,
83 /// and envp parameters.
84 int ExecutionEngine::runFunctionAsMain(Function *Fn,
85                                        const std::vector<std::string> &argv,
86                                        const char * const * envp) {
87   std::vector<GenericValue> GVArgs;
88   GenericValue GVArgc;
89   GVArgc.IntVal = argv.size();
90   GVArgs.push_back(GVArgc); // Arg #0 = argc.
91   GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
92   assert(((char **)GVTOP(GVArgs[1]))[0] && "argv[0] was null after CreateArgv");
93
94   std::vector<std::string> EnvVars;
95   for (unsigned i = 0; envp[i]; ++i)
96     EnvVars.push_back(envp[i]);
97   GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
98   return runFunction(Fn, GVArgs).IntVal;
99 }
100
101
102
103 /// If possible, create a JIT, unless the caller specifically requests an
104 /// Interpreter or there's an error. If even an Interpreter cannot be created,
105 /// NULL is returned. 
106 ///
107 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 
108                                          bool ForceInterpreter) {
109   ExecutionEngine *EE = 0;
110
111   // Unless the interpreter was explicitly selected, make a JIT.
112   if (!ForceInterpreter)
113     EE = JIT::create(MP);
114
115   // If we can't make a JIT, make an interpreter instead.
116   try {
117     if (EE == 0)
118       EE = Interpreter::create(MP->materializeModule());
119   } catch (...) {
120     EE = 0;
121   }
122   return EE;
123 }
124
125 /// getPointerToGlobal - This returns the address of the specified global
126 /// value.  This may involve code generation if it's a function.
127 ///
128 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
129   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
130     return getPointerToFunction(F);
131
132   assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
133   return GlobalAddress[GV];
134 }
135
136 /// FIXME: document
137 /// 
138 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
139   GenericValue Result;
140
141   if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
142     switch (CE->getOpcode()) {
143     case Instruction::GetElementPtr: {
144       Result = getConstantValue(CE->getOperand(0));
145       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
146       uint64_t Offset =
147         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
148                              
149       Result.LongVal += Offset;
150       return Result;
151     }
152     case Instruction::Cast: {
153       // We only need to handle a few cases here.  Almost all casts will
154       // automatically fold, just the ones involving pointers won't.
155       //
156       Constant *Op = CE->getOperand(0);
157
158       // Handle cast of pointer to pointer...
159       if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
160         return getConstantValue(Op);
161
162       // Handle a cast of pointer to any integral type...
163       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
164         return getConstantValue(Op);
165         
166       // Handle cast of long to pointer...
167       if (isa<PointerType>(C->getType()) && (Op->getType() == Type::LongTy ||
168                                              Op->getType() == Type::ULongTy))
169         return getConstantValue(Op);
170       break;
171     }
172
173     case Instruction::Add:
174       if (CE->getOperand(0)->getType() == Type::LongTy ||
175           CE->getOperand(0)->getType() == Type::ULongTy)
176         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
177                          getConstantValue(CE->getOperand(1)).LongVal;
178       else
179         break;
180       return Result;
181
182     default:
183       break;
184     }
185     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
186     abort();
187   }
188   
189   switch (C->getType()->getPrimitiveID()) {
190 #define GET_CONST_VAL(TY, CLASS) \
191   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
192     GET_CONST_VAL(Bool   , ConstantBool);
193     GET_CONST_VAL(UByte  , ConstantUInt);
194     GET_CONST_VAL(SByte  , ConstantSInt);
195     GET_CONST_VAL(UShort , ConstantUInt);
196     GET_CONST_VAL(Short  , ConstantSInt);
197     GET_CONST_VAL(UInt   , ConstantUInt);
198     GET_CONST_VAL(Int    , ConstantSInt);
199     GET_CONST_VAL(ULong  , ConstantUInt);
200     GET_CONST_VAL(Long   , ConstantSInt);
201     GET_CONST_VAL(Float  , ConstantFP);
202     GET_CONST_VAL(Double , ConstantFP);
203 #undef GET_CONST_VAL
204   case Type::PointerTyID:
205     if (isa<ConstantPointerNull>(C)) {
206       Result.PointerVal = 0;
207     } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
208       if (Function *F =
209           const_cast<Function*>(dyn_cast<Function>(CPR->getValue())))
210         Result = PTOGV(getPointerToFunctionOrStub(F));
211       else 
212         Result = PTOGV(getOrEmitGlobalVariable(
213                            cast<GlobalVariable>(CPR->getValue())));
214
215     } else {
216       assert(0 && "Unknown constant pointer type!");
217     }
218     break;
219   default:
220     std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
221     abort();
222   }
223   return Result;
224 }
225
226 /// FIXME: document
227 ///
228 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
229                                          const Type *Ty) {
230   if (getTargetData().isLittleEndian()) {
231     switch (Ty->getPrimitiveID()) {
232     case Type::BoolTyID:
233     case Type::UByteTyID:
234     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
235     case Type::UShortTyID:
236     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
237                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
238                             break;
239     Store4BytesLittleEndian:
240     case Type::FloatTyID:
241     case Type::UIntTyID:
242     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
243                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
244                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
245                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
246                             break;
247     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
248                               goto Store4BytesLittleEndian;
249     case Type::DoubleTyID:
250     case Type::ULongTyID:
251     case Type::LongTyID:    Ptr->Untyped[0] =  Val.ULongVal        & 255;
252                             Ptr->Untyped[1] = (Val.ULongVal >>  8) & 255;
253                             Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
254                             Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
255                             Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
256                             Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
257                             Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
258                             Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
259                             break;
260     default:
261       std::cout << "Cannot store value of type " << Ty << "!\n";
262     }
263   } else {
264     switch (Ty->getPrimitiveID()) {
265     case Type::BoolTyID:
266     case Type::UByteTyID:
267     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
268     case Type::UShortTyID:
269     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
270                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
271                             break;
272     Store4BytesBigEndian:
273     case Type::FloatTyID:
274     case Type::UIntTyID:
275     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
276                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
277                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
278                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
279                             break;
280     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
281                               goto Store4BytesBigEndian;
282     case Type::DoubleTyID:
283     case Type::ULongTyID:
284     case Type::LongTyID:    Ptr->Untyped[7] =  Val.ULongVal        & 255;
285                             Ptr->Untyped[6] = (Val.ULongVal >>  8) & 255;
286                             Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
287                             Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
288                             Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
289                             Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
290                             Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
291                             Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
292                             break;
293     default:
294       std::cout << "Cannot store value of type " << Ty << "!\n";
295     }
296   }
297 }
298
299 /// FIXME: document
300 ///
301 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
302                                                   const Type *Ty) {
303   GenericValue Result;
304   if (getTargetData().isLittleEndian()) {
305     switch (Ty->getPrimitiveID()) {
306     case Type::BoolTyID:
307     case Type::UByteTyID:
308     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
309     case Type::UShortTyID:
310     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
311                                               ((unsigned)Ptr->Untyped[1] << 8);
312                             break;
313     Load4BytesLittleEndian:                            
314     case Type::FloatTyID:
315     case Type::UIntTyID:
316     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
317                                             ((unsigned)Ptr->Untyped[1] <<  8) |
318                                             ((unsigned)Ptr->Untyped[2] << 16) |
319                                             ((unsigned)Ptr->Untyped[3] << 24);
320                             break;
321     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
322                               goto Load4BytesLittleEndian;
323     case Type::DoubleTyID:
324     case Type::ULongTyID:
325     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
326                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
327                                              ((uint64_t)Ptr->Untyped[2] << 16) |
328                                              ((uint64_t)Ptr->Untyped[3] << 24) |
329                                              ((uint64_t)Ptr->Untyped[4] << 32) |
330                                              ((uint64_t)Ptr->Untyped[5] << 40) |
331                                              ((uint64_t)Ptr->Untyped[6] << 48) |
332                                              ((uint64_t)Ptr->Untyped[7] << 56);
333                             break;
334     default:
335       std::cout << "Cannot load value of type " << *Ty << "!\n";
336       abort();
337     }
338   } else {
339     switch (Ty->getPrimitiveID()) {
340     case Type::BoolTyID:
341     case Type::UByteTyID:
342     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
343     case Type::UShortTyID:
344     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
345                                               ((unsigned)Ptr->Untyped[0] << 8);
346                             break;
347     Load4BytesBigEndian:
348     case Type::FloatTyID:
349     case Type::UIntTyID:
350     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
351                                             ((unsigned)Ptr->Untyped[2] <<  8) |
352                                             ((unsigned)Ptr->Untyped[1] << 16) |
353                                             ((unsigned)Ptr->Untyped[0] << 24);
354                             break;
355     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
356                               goto Load4BytesBigEndian;
357     case Type::DoubleTyID:
358     case Type::ULongTyID:
359     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
360                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
361                                              ((uint64_t)Ptr->Untyped[5] << 16) |
362                                              ((uint64_t)Ptr->Untyped[4] << 24) |
363                                              ((uint64_t)Ptr->Untyped[3] << 32) |
364                                              ((uint64_t)Ptr->Untyped[2] << 40) |
365                                              ((uint64_t)Ptr->Untyped[1] << 48) |
366                                              ((uint64_t)Ptr->Untyped[0] << 56);
367                             break;
368     default:
369       std::cout << "Cannot load value of type " << *Ty << "!\n";
370       abort();
371     }
372   }
373   return Result;
374 }
375
376 // InitializeMemory - Recursive function to apply a Constant value into the
377 // specified memory location...
378 //
379 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
380   if (Init->getType()->isFirstClassType()) {
381     GenericValue Val = getConstantValue(Init);
382     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
383     return;
384   }
385
386   switch (Init->getType()->getPrimitiveID()) {
387   case Type::ArrayTyID: {
388     const ConstantArray *CPA = cast<ConstantArray>(Init);
389     const std::vector<Use> &Val = CPA->getValues();
390     unsigned ElementSize = 
391       getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
392     for (unsigned i = 0; i < Val.size(); ++i)
393       InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
394     return;
395   }
396
397   case Type::StructTyID: {
398     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
399     const StructLayout *SL =
400       getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
401     const std::vector<Use> &Val = CPS->getValues();
402     for (unsigned i = 0; i < Val.size(); ++i)
403       InitializeMemory(cast<Constant>(Val[i].get()),
404                        (char*)Addr+SL->MemberOffsets[i]);
405     return;
406   }
407
408   default:
409     std::cerr << "Bad Type: " << Init->getType() << "\n";
410     assert(0 && "Unknown constant type to initialize memory with!");
411   }
412 }
413
414 /// EmitGlobals - Emit all of the global variables to memory, storing their
415 /// addresses into GlobalAddress.  This must make sure to copy the contents of
416 /// their initializers into the memory.
417 ///
418 void ExecutionEngine::emitGlobals() {
419   const TargetData &TD = getTargetData();
420   
421   // Loop over all of the global variables in the program, allocating the memory
422   // to hold them.
423   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
424        I != E; ++I)
425     if (!I->isExternal()) {
426       // Get the type of the global...
427       const Type *Ty = I->getType()->getElementType();
428       
429       // Allocate some memory for it!
430       unsigned Size = TD.getTypeSize(Ty);
431       addGlobalMapping(I, new char[Size]);
432
433       DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
434                       << (void*)GlobalAddress[I] << "\n");
435     } else {
436       // External variable reference. Try to use the dynamic loader to
437       // get a pointer to it.
438       if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
439         GlobalAddress[I] = SymAddr;
440       else {
441         std::cerr << "Could not resolve external global address: "
442                   << I->getName() << "\n";
443         abort();
444       }
445     }
446   
447   // Now that all of the globals are set up in memory, loop through them all and
448   // initialize their contents.
449   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
450        I != E; ++I)
451     if (!I->isExternal())
452       EmitGlobalVariable(I);
453 }
454
455 // EmitGlobalVariable - This method emits the specified global variable to the
456 // address specified in GlobalAddresses, or allocates new memory if it's not
457 // already in the map.
458 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
459   void *&GA = GlobalAddress[GV];
460   const Type *ElTy = GV->getType()->getElementType();
461   if (GA == 0) {
462     // If it's not already specified, allocate memory for the global.
463     GA = new char[getTargetData().getTypeSize(ElTy)];
464   }
465
466   InitializeMemory(GV->getInitializer(), GA);
467   NumInitBytes += getTargetData().getTypeSize(ElTy);
468   ++NumGlobals;
469 }