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