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