* Tabs to spaces
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2 // 
3 // This file defines the common interface used by the various execution engine
4 // subclasses.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #define DEBUG_TYPE "jit"
9 #include "llvm/ExecutionEngine/ExecutionEngine.h"
10 #include "JIT/VM.h"
11 #include "Interpreter/Interpreter.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Constants.h"
14 #include "llvm/Module.h"
15 #include "llvm/ExecutionEngine/GenericValue.h"
16 #include "llvm/Target/TargetData.h"
17 #include "Support/Debug.h"
18 #include "Support/Statistic.h"
19 #include "Support/DynamicLinker.h"
20 #include "Config/dlfcn.h"
21
22 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
23
24 ExecutionEngine::~ExecutionEngine() {
25   delete &CurMod;
26 }
27
28 /// FIXME: document
29 ///
30 ExecutionEngine *ExecutionEngine::create(Module *M, bool ForceInterpreter,
31                                          bool TraceMode) {
32   ExecutionEngine *EE = 0;
33
34   // If there is nothing that is forcing us to use the interpreter, make a JIT.
35   if (!ForceInterpreter && !TraceMode)
36     EE = VM::create(M);
37
38   // If we can't make a JIT, make an interpreter instead.
39   if (EE == 0)
40     EE = Interpreter::create(M, TraceMode);
41   return EE;
42 }
43
44 /// getPointerToGlobal - This returns the address of the specified global
45 /// value.  This may involve code generation if it's a function.
46 ///
47 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
48   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
49     return getPointerToFunction(F);
50
51   assert(GlobalAddress[GV] && "Global hasn't had an address allocated yet?");
52   return GlobalAddress[GV];
53 }
54
55 /// FIXME: document
56 /// 
57 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
58   GenericValue Result;
59
60   if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
61     switch (CE->getOpcode()) {
62     case Instruction::GetElementPtr: {
63       Result = getConstantValue(CE->getOperand(0));
64       std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
65       uint64_t Offset =
66         TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
67                              
68       Result.LongVal += Offset;
69       return Result;
70     }
71     case Instruction::Cast: {
72       // We only need to handle a few cases here.  Almost all casts will
73       // automatically fold, just the ones involving pointers won't.
74       //
75       Constant *Op = CE->getOperand(0);
76
77       // Handle cast of pointer to pointer...
78       if (Op->getType()->getPrimitiveID() == C->getType()->getPrimitiveID())
79         return getConstantValue(Op);
80
81       // Handle a cast of pointer to any integral type...
82       if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
83         return getConstantValue(Op);
84         
85       // Handle cast of long to pointer...
86       if (isa<PointerType>(C->getType()) && (Op->getType() == Type::LongTy ||
87                                              Op->getType() == Type::ULongTy))
88         return getConstantValue(Op);
89       break;
90     }
91
92     case Instruction::Add:
93       if (CE->getOperand(0)->getType() == Type::LongTy ||
94           CE->getOperand(0)->getType() == Type::ULongTy)
95         Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
96                          getConstantValue(CE->getOperand(1)).LongVal;
97       else
98         break;
99       return Result;
100
101     default:
102       break;
103     }
104     std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
105     abort();
106   }
107   
108   switch (C->getType()->getPrimitiveID()) {
109 #define GET_CONST_VAL(TY, CLASS) \
110   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break
111     GET_CONST_VAL(Bool   , ConstantBool);
112     GET_CONST_VAL(UByte  , ConstantUInt);
113     GET_CONST_VAL(SByte  , ConstantSInt);
114     GET_CONST_VAL(UShort , ConstantUInt);
115     GET_CONST_VAL(Short  , ConstantSInt);
116     GET_CONST_VAL(UInt   , ConstantUInt);
117     GET_CONST_VAL(Int    , ConstantSInt);
118     GET_CONST_VAL(ULong  , ConstantUInt);
119     GET_CONST_VAL(Long   , ConstantSInt);
120     GET_CONST_VAL(Float  , ConstantFP);
121     GET_CONST_VAL(Double , ConstantFP);
122 #undef GET_CONST_VAL
123   case Type::PointerTyID:
124     if (isa<ConstantPointerNull>(C)) {
125       Result.PointerVal = 0;
126     } else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)){
127       Result = PTOGV(getPointerToGlobal(CPR->getValue()));
128
129     } else {
130       assert(0 && "Unknown constant pointer type!");
131     }
132     break;
133   default:
134     std::cout << "ERROR: Constant unimp for type: " << C->getType() << "\n";
135     abort();
136   }
137   return Result;
138 }
139
140 /// FIXME: document
141 ///
142 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
143                                          const Type *Ty) {
144   if (getTargetData().isLittleEndian()) {
145     switch (Ty->getPrimitiveID()) {
146     case Type::BoolTyID:
147     case Type::UByteTyID:
148     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
149     case Type::UShortTyID:
150     case Type::ShortTyID:   Ptr->Untyped[0] = Val.UShortVal & 255;
151                             Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
152                             break;
153     Store4BytesLittleEndian:
154     case Type::FloatTyID:
155     case Type::UIntTyID:
156     case Type::IntTyID:     Ptr->Untyped[0] =  Val.UIntVal        & 255;
157                             Ptr->Untyped[1] = (Val.UIntVal >>  8) & 255;
158                             Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
159                             Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
160                             break;
161     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
162                               goto Store4BytesLittleEndian;
163     case Type::DoubleTyID:
164     case Type::ULongTyID:
165     case Type::LongTyID:    Ptr->Untyped[0] =  Val.ULongVal        & 255;
166                             Ptr->Untyped[1] = (Val.ULongVal >>  8) & 255;
167                             Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255;
168                             Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255;
169                             Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255;
170                             Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255;
171                             Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255;
172                             Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255;
173                             break;
174     default:
175       std::cout << "Cannot store value of type " << Ty << "!\n";
176     }
177   } else {
178     switch (Ty->getPrimitiveID()) {
179     case Type::BoolTyID:
180     case Type::UByteTyID:
181     case Type::SByteTyID:   Ptr->Untyped[0] = Val.UByteVal; break;
182     case Type::UShortTyID:
183     case Type::ShortTyID:   Ptr->Untyped[1] = Val.UShortVal & 255;
184                             Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
185                             break;
186     Store4BytesBigEndian:
187     case Type::FloatTyID:
188     case Type::UIntTyID:
189     case Type::IntTyID:     Ptr->Untyped[3] =  Val.UIntVal        & 255;
190                             Ptr->Untyped[2] = (Val.UIntVal >>  8) & 255;
191                             Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
192                             Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
193                             break;
194     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
195                               goto Store4BytesBigEndian;
196     case Type::DoubleTyID:
197     case Type::ULongTyID:
198     case Type::LongTyID:    Ptr->Untyped[7] =  Val.ULongVal        & 255;
199                             Ptr->Untyped[6] = (Val.ULongVal >>  8) & 255;
200                             Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255;
201                             Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255;
202                             Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255;
203                             Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255;
204                             Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255;
205                             Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255;
206                             break;
207     default:
208       std::cout << "Cannot store value of type " << Ty << "!\n";
209     }
210   }
211 }
212
213 /// FIXME: document
214 ///
215 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
216                                                   const Type *Ty) {
217   GenericValue Result;
218   if (getTargetData().isLittleEndian()) {
219     switch (Ty->getPrimitiveID()) {
220     case Type::BoolTyID:
221     case Type::UByteTyID:
222     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
223     case Type::UShortTyID:
224     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[0] |
225                                               ((unsigned)Ptr->Untyped[1] << 8);
226                             break;
227     Load4BytesLittleEndian:                            
228     case Type::FloatTyID:
229     case Type::UIntTyID:
230     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[0] |
231                                             ((unsigned)Ptr->Untyped[1] <<  8) |
232                                             ((unsigned)Ptr->Untyped[2] << 16) |
233                                             ((unsigned)Ptr->Untyped[3] << 24);
234                             break;
235     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
236                               goto Load4BytesLittleEndian;
237     case Type::DoubleTyID:
238     case Type::ULongTyID:
239     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
240                                              ((uint64_t)Ptr->Untyped[1] <<  8) |
241                                              ((uint64_t)Ptr->Untyped[2] << 16) |
242                                              ((uint64_t)Ptr->Untyped[3] << 24) |
243                                              ((uint64_t)Ptr->Untyped[4] << 32) |
244                                              ((uint64_t)Ptr->Untyped[5] << 40) |
245                                              ((uint64_t)Ptr->Untyped[6] << 48) |
246                                              ((uint64_t)Ptr->Untyped[7] << 56);
247                             break;
248     default:
249       std::cout << "Cannot load value of type " << *Ty << "!\n";
250       abort();
251     }
252   } else {
253     switch (Ty->getPrimitiveID()) {
254     case Type::BoolTyID:
255     case Type::UByteTyID:
256     case Type::SByteTyID:   Result.UByteVal = Ptr->Untyped[0]; break;
257     case Type::UShortTyID:
258     case Type::ShortTyID:   Result.UShortVal = (unsigned)Ptr->Untyped[1] |
259                                               ((unsigned)Ptr->Untyped[0] << 8);
260                             break;
261     Load4BytesBigEndian:
262     case Type::FloatTyID:
263     case Type::UIntTyID:
264     case Type::IntTyID:     Result.UIntVal = (unsigned)Ptr->Untyped[3] |
265                                             ((unsigned)Ptr->Untyped[2] <<  8) |
266                                             ((unsigned)Ptr->Untyped[1] << 16) |
267                                             ((unsigned)Ptr->Untyped[0] << 24);
268                             break;
269     case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
270                               goto Load4BytesBigEndian;
271     case Type::DoubleTyID:
272     case Type::ULongTyID:
273     case Type::LongTyID:    Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
274                                              ((uint64_t)Ptr->Untyped[6] <<  8) |
275                                              ((uint64_t)Ptr->Untyped[5] << 16) |
276                                              ((uint64_t)Ptr->Untyped[4] << 24) |
277                                              ((uint64_t)Ptr->Untyped[3] << 32) |
278                                              ((uint64_t)Ptr->Untyped[2] << 40) |
279                                              ((uint64_t)Ptr->Untyped[1] << 48) |
280                                              ((uint64_t)Ptr->Untyped[0] << 56);
281                             break;
282     default:
283       std::cout << "Cannot load value of type " << *Ty << "!\n";
284       abort();
285     }
286   }
287   return Result;
288 }
289
290 // InitializeMemory - Recursive function to apply a Constant value into the
291 // specified memory location...
292 //
293 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
294   if (Init->getType()->isFirstClassType()) {
295     GenericValue Val = getConstantValue(Init);
296     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
297     return;
298   }
299
300   switch (Init->getType()->getPrimitiveID()) {
301   case Type::ArrayTyID: {
302     const ConstantArray *CPA = cast<ConstantArray>(Init);
303     const std::vector<Use> &Val = CPA->getValues();
304     unsigned ElementSize = 
305       getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
306     for (unsigned i = 0; i < Val.size(); ++i)
307       InitializeMemory(cast<Constant>(Val[i].get()), (char*)Addr+i*ElementSize);
308     return;
309   }
310
311   case Type::StructTyID: {
312     const ConstantStruct *CPS = cast<ConstantStruct>(Init);
313     const StructLayout *SL =
314       getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
315     const std::vector<Use> &Val = CPS->getValues();
316     for (unsigned i = 0; i < Val.size(); ++i)
317       InitializeMemory(cast<Constant>(Val[i].get()),
318                        (char*)Addr+SL->MemberOffsets[i]);
319     return;
320   }
321
322   default:
323     std::cerr << "Bad Type: " << Init->getType() << "\n";
324     assert(0 && "Unknown constant type to initialize memory with!");
325   }
326 }
327
328 /// EmitGlobals - Emit all of the global variables to memory, storing their
329 /// addresses into GlobalAddress.  This must make sure to copy the contents of
330 /// their initializers into the memory.
331 ///
332 void ExecutionEngine::emitGlobals() {
333   const TargetData &TD = getTargetData();
334   
335   // Loop over all of the global variables in the program, allocating the memory
336   // to hold them.
337   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
338        I != E; ++I)
339     if (!I->isExternal()) {
340       // Get the type of the global...
341       const Type *Ty = I->getType()->getElementType();
342       
343       // Allocate some memory for it!
344       unsigned Size = TD.getTypeSize(Ty);
345       GlobalAddress[I] = new char[Size];
346       NumInitBytes += Size;
347
348       DEBUG(std::cerr << "Global '" << I->getName() << "' -> "
349                       << (void*)GlobalAddress[I] << "\n");
350     } else {
351       // External variable reference. Try to use the dynamic loader to
352       // get a pointer to it.
353       if (void *SymAddr = GetAddressOfSymbol(I->getName().c_str()))
354         GlobalAddress[I] = SymAddr;
355       else {
356         std::cerr << "Could not resolve external global address: "
357                   << I->getName() << "\n";
358         abort();
359       }
360     }
361   
362   // Now that all of the globals are set up in memory, loop through them all and
363   // initialize their contents.
364   for (Module::giterator I = getModule().gbegin(), E = getModule().gend();
365        I != E; ++I)
366     if (!I->isExternal())
367       InitializeMemory(I->getInitializer(), GlobalAddress[I]);
368 }
369