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