Pass around IntrinsicLowering instances as appropriate.
[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/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"
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
34   Statistic<> NumGlobals  ("lli", "Number of global vars initialized");
35 }
36
37 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : 
38   CurMod(*P->getModule()), MP(P) {
39   assert(P && "ModuleProvider is null?");
40 }
41
42 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
43   assert(M && "Module is null?");
44 }
45
46 ExecutionEngine::~ExecutionEngine() {
47   delete MP;
48 }
49
50
51 // CreateArgv - Turn a vector of strings into a nice argv style array of
52 // pointers to null terminated strings.
53 //
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];
58
59   DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
60   const Type *SBytePtr = PointerType::get(Type::SByteTy);
61
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");
66       
67     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
68     Dest[Size-1] = 0;
69       
70     // Endian safe: Result[i] = (PointerTy)Dest;
71     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
72                            SBytePtr);
73   }
74
75   // Null terminate it
76   EE->StoreValueToMemory(PTOGV(0),
77                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
78                          SBytePtr);
79   return Result;
80 }
81
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;
89   GenericValue GVArgc;
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");
94
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;
100 }
101
102
103
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. 
107 ///
108 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 
109                                          bool ForceInterpreter,
110                                          IntrinsicLowering *IL) {
111   ExecutionEngine *EE = 0;
112
113   // Unless the interpreter was explicitly selected, try making a JIT.
114   if (!ForceInterpreter)
115     EE = JIT::create(MP, IL);
116
117   // If we can't make a JIT, make an interpreter instead.
118   try {
119     if (EE == 0)
120       EE = Interpreter::create(MP->materializeModule(), IL);
121   } catch (...) {
122     EE = 0;
123   }
124
125   if (EE == 0) delete IL;
126   return EE;
127 }
128
129 /// getPointerToGlobal - This returns the address of the specified global
130 /// value.  This may involve code generation if it's a function.
131 ///
132 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
133   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
134     return getPointerToFunction(F);
135
136   assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
137   return GlobalAddress[GV];
138 }
139
140 /// FIXME: document
141 /// 
142 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
143   GenericValue Result;
144
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());
150       uint64_t Offset =
151         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
152                              
153       Result.LongVal += Offset;
154       return Result;
155     }
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.
159       //
160       Constant *Op = CE->getOperand(0);
161
162       // Handle cast of pointer to pointer...
163       if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
164         return getConstantValue(Op);
165
166       // Handle a cast of pointer to any integral type...
167       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
168         return getConstantValue(Op);
169         
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);
174       break;
175     }
176
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;
182       else
183         break;
184       return Result;
185
186     default:
187       break;
188     }
189     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
190     abort();
191   }
192   
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);
207 #undef GET_CONST_VAL
208   case Type::PointerTyID:
209     if (isa<ConstantPointerNull>(C)) {
210       Result.PointerVal = 0;
211     } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
212       if (Function *F =
213           const_cast<Function*>(dyn_cast<Function>(CPR->getValue())))
214         Result = PTOGV(getPointerToFunctionOrStub(F));
215       else 
216         Result = PTOGV(getOrEmitGlobalVariable(
217                            cast<GlobalVariable>(CPR->getValue())));
218
219     } else {
220       assert(0 && "Unknown constant pointer type!");
221     }
222     break;
223   default:
224     std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
225     abort();
226   }
227   return Result;
228 }
229
230 /// FIXME: document
231 ///
232 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
233                                          const Type *Ty) {
234   if (getTargetData().isLittleEndian()) {
235     switch (Ty->getPrimitiveID()) {
236     case Type::BoolTyID:
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;
242                             break;
243     Store4BytesLittleEndian:
244     case Type::FloatTyID:
245     case Type::UIntTyID:
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;
250                             break;
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;
263                             break;
264     default:
265       std::cout << "Cannot store value of type " << Ty << "!\n";
266     }
267   } else {
268     switch (Ty->getPrimitiveID()) {
269     case Type::BoolTyID:
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;
275                             break;
276     Store4BytesBigEndian:
277     case Type::FloatTyID:
278     case Type::UIntTyID:
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;
283                             break;
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;
296                             break;
297     default:
298       std::cout << "Cannot store value of type " << Ty << "!\n";
299     }
300   }
301 }
302
303 /// FIXME: document
304 ///
305 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
306                                                   const Type *Ty) {
307   GenericValue Result;
308   if (getTargetData().isLittleEndian()) {
309     switch (Ty->getPrimitiveID()) {
310     case Type::BoolTyID:
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);
316                             break;
317     Load4BytesLittleEndian:                            
318     case Type::FloatTyID:
319     case Type::UIntTyID:
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);
324                             break;
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);
337                             break;
338     default:
339       std::cout << "Cannot load value of type " << *Ty << "!\n";
340       abort();
341     }
342   } else {
343     switch (Ty->getPrimitiveID()) {
344     case Type::BoolTyID:
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);
350                             break;
351     Load4BytesBigEndian:
352     case Type::FloatTyID:
353     case Type::UIntTyID:
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);
358                             break;
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);
371                             break;
372     default:
373       std::cout << "Cannot load value of type " << *Ty << "!\n";
374       abort();
375     }
376   }
377   return Result;
378 }
379
380 // InitializeMemory - Recursive function to apply a Constant value into the
381 // specified memory location...
382 //
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());
387     return;
388   }
389
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);
398     return;
399   }
400
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]);
409     return;
410   }
411
412   default:
413     std::cerr << "Bad Type: " << Init->getType() << "\n";
414     assert(0 && "Unknown constant type to initialize memory with!");
415   }
416 }
417
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.
421 ///
422 void ExecutionEngine::emitGlobals() {
423   const TargetData &TD = getTargetData();
424   
425   // Loop over all of the global variables in the program, allocating the memory
426   // to hold them.
427   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
428        I != E; ++I)
429     if (!I->isExternal()) {
430       // Get the type of the global...
431       const Type *Ty = I->getType()->getElementType();
432       
433       // Allocate some memory for it!
434       unsigned Size = TD.getTypeSize(Ty);
435       addGlobalMapping(I, new char[Size]);
436
437       DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
438                       << (void*)GlobalAddress[I] << "\n");
439     } else {
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;
444       else {
445         std::cerr << "Could not resolve external global address: "
446                   << I->getName() << "\n";
447         abort();
448       }
449     }
450   
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();
454        I != E; ++I)
455     if (!I->isExternal())
456       EmitGlobalVariable(I);
457 }
458
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();
465   if (GA == 0) {
466     // If it's not already specified, allocate memory for the global.
467     GA = new char[getTargetData().getTypeSize(ElTy)];
468   }
469
470   InitializeMemory(GV->getInitializer(), GA);
471   NumInitBytes += getTargetData().getTypeSize(ElTy);
472   ++NumGlobals;
473 }