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