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