allow main to have any integer type.
[oota-llvm.git] / lib / ExecutionEngine / ExecutionEngine.cpp
1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the common interface used by the various execution engine
11 // subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Config/alloca.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/System/Host.h"
28 #include "llvm/Target/TargetData.h"
29 #include <cmath>
30 #include <cstring>
31 using namespace llvm;
32
33 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34 STATISTIC(NumGlobals  , "Number of global vars initialized");
35
36 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
39
40
41 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
42   LazyCompilationDisabled = false;
43   GVCompilationDisabled   = false;
44   SymbolSearchingDisabled = false;
45   Modules.push_back(P);
46   assert(P && "ModuleProvider is null?");
47 }
48
49 ExecutionEngine::~ExecutionEngine() {
50   clearAllGlobalMappings();
51   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
52     delete Modules[i];
53 }
54
55 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
56   const Type *ElTy = GV->getType()->getElementType();
57   size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
58   return new char[GVSize];
59 }
60
61 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
62 /// Relases the Module from the ModuleProvider, materializing it in the
63 /// process, and returns the materialized Module.
64 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 
65                                               std::string *ErrInfo) {
66   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 
67         E = Modules.end(); I != E; ++I) {
68     ModuleProvider *MP = *I;
69     if (MP == P) {
70       Modules.erase(I);
71       clearGlobalMappingsFromModule(MP->getModule());
72       return MP->releaseModule(ErrInfo);
73     }
74   }
75   return NULL;
76 }
77
78 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
79 /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
80 /// the underlying module.
81 void ExecutionEngine::deleteModuleProvider(ModuleProvider *P, 
82                                            std::string *ErrInfo) {
83   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 
84       E = Modules.end(); I != E; ++I) {
85     ModuleProvider *MP = *I;
86     if (MP == P) {
87       Modules.erase(I);
88       clearGlobalMappingsFromModule(MP->getModule());
89       delete MP;
90       return;
91     }
92   }
93 }
94
95 /// FindFunctionNamed - Search all of the active modules to find the one that
96 /// defines FnName.  This is very slow operation and shouldn't be used for
97 /// general code.
98 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
99   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
100     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
101       return F;
102   }
103   return 0;
104 }
105
106
107 /// addGlobalMapping - Tell the execution engine that the specified global is
108 /// at the specified location.  This is used internally as functions are JIT'd
109 /// and as global variables are laid out in memory.  It can and should also be
110 /// used by clients of the EE that want to have an LLVM global overlay
111 /// existing data in memory.
112 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
113   MutexGuard locked(lock);
114
115   DOUT << "JIT: Map \'" << GV->getNameStart() << "\' to [" << Addr << "]\n";  
116   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
117   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
118   CurVal = Addr;
119   
120   // If we are using the reverse mapping, add it too
121   if (!state.getGlobalAddressReverseMap(locked).empty()) {
122     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
123     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
124     V = GV;
125   }
126 }
127
128 /// clearAllGlobalMappings - Clear all global mappings and start over again
129 /// use in dynamic compilation scenarios when you want to move globals
130 void ExecutionEngine::clearAllGlobalMappings() {
131   MutexGuard locked(lock);
132   
133   state.getGlobalAddressMap(locked).clear();
134   state.getGlobalAddressReverseMap(locked).clear();
135 }
136
137 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
138 /// particular module, because it has been removed from the JIT.
139 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
140   MutexGuard locked(lock);
141   
142   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
143     state.getGlobalAddressMap(locked).erase(FI);
144     state.getGlobalAddressReverseMap(locked).erase(FI);
145   }
146   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 
147        GI != GE; ++GI) {
148     state.getGlobalAddressMap(locked).erase(GI);
149     state.getGlobalAddressReverseMap(locked).erase(GI);
150   }
151 }
152
153 /// updateGlobalMapping - Replace an existing mapping for GV with a new
154 /// address.  This updates both maps as required.  If "Addr" is null, the
155 /// entry for the global is removed from the mappings.
156 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
157   MutexGuard locked(lock);
158
159   std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
160
161   // Deleting from the mapping?
162   if (Addr == 0) {
163     std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
164     void *OldVal;
165     if (I == Map.end())
166       OldVal = 0;
167     else {
168       OldVal = I->second;
169       Map.erase(I); 
170     }
171     
172     if (!state.getGlobalAddressReverseMap(locked).empty())
173       state.getGlobalAddressReverseMap(locked).erase(Addr);
174     return OldVal;
175   }
176   
177   void *&CurVal = Map[GV];
178   void *OldVal = CurVal;
179
180   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
181     state.getGlobalAddressReverseMap(locked).erase(CurVal);
182   CurVal = Addr;
183   
184   // If we are using the reverse mapping, add it too
185   if (!state.getGlobalAddressReverseMap(locked).empty()) {
186     const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
187     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188     V = GV;
189   }
190   return OldVal;
191 }
192
193 /// getPointerToGlobalIfAvailable - This returns the address of the specified
194 /// global value if it is has already been codegen'd, otherwise it returns null.
195 ///
196 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197   MutexGuard locked(lock);
198   
199   std::map<const GlobalValue*, void*>::iterator I =
200   state.getGlobalAddressMap(locked).find(GV);
201   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
202 }
203
204 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
205 /// at the specified address.
206 ///
207 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
208   MutexGuard locked(lock);
209
210   // If we haven't computed the reverse mapping yet, do so first.
211   if (state.getGlobalAddressReverseMap(locked).empty()) {
212     for (std::map<const GlobalValue*, void *>::iterator
213          I = state.getGlobalAddressMap(locked).begin(),
214          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
215       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
216                                                                      I->first));
217   }
218
219   std::map<void *, const GlobalValue*>::iterator I =
220     state.getGlobalAddressReverseMap(locked).find(Addr);
221   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
222 }
223
224 // CreateArgv - Turn a vector of strings into a nice argv style array of
225 // pointers to null terminated strings.
226 //
227 static void *CreateArgv(ExecutionEngine *EE,
228                         const std::vector<std::string> &InputArgv) {
229   unsigned PtrSize = EE->getTargetData()->getPointerSize();
230   char *Result = new char[(InputArgv.size()+1)*PtrSize];
231
232   DOUT << "JIT: ARGV = " << (void*)Result << "\n";
233   const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
234
235   for (unsigned i = 0; i != InputArgv.size(); ++i) {
236     unsigned Size = InputArgv[i].size()+1;
237     char *Dest = new char[Size];
238     DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n";
239
240     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
241     Dest[Size-1] = 0;
242
243     // Endian safe: Result[i] = (PointerTy)Dest;
244     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245                            SBytePtr);
246   }
247
248   // Null terminate it
249   EE->StoreValueToMemory(PTOGV(0),
250                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
251                          SBytePtr);
252   return Result;
253 }
254
255
256 /// runStaticConstructorsDestructors - This method is used to execute all of
257 /// the static constructors or destructors for a module, depending on the
258 /// value of isDtors.
259 void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
260   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
261   
262   // Execute global ctors/dtors for each module in the program.
263   
264  GlobalVariable *GV = module->getNamedGlobal(Name);
265
266  // If this global has internal linkage, or if it has a use, then it must be
267  // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
268  // this is the case, don't execute any of the global ctors, __main will do
269  // it.
270  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
271  
272  // Should be an array of '{ int, void ()* }' structs.  The first value is
273  // the init priority, which we ignore.
274  ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
275  if (!InitList) return;
276  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
277    if (ConstantStruct *CS = 
278        dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
279      if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
280    
281      Constant *FP = CS->getOperand(1);
282      if (FP->isNullValue())
283        break;  // Found a null terminator, exit.
284    
285      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
286        if (CE->isCast())
287          FP = CE->getOperand(0);
288      if (Function *F = dyn_cast<Function>(FP)) {
289        // Execute the ctor/dtor function!
290        runFunction(F, std::vector<GenericValue>());
291      }
292    }
293 }
294
295 /// runStaticConstructorsDestructors - This method is used to execute all of
296 /// the static constructors or destructors for a program, depending on the
297 /// value of isDtors.
298 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
299   // Execute global ctors/dtors for each module in the program.
300   for (unsigned m = 0, e = Modules.size(); m != e; ++m)
301     runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
302 }
303
304 #ifndef NDEBUG
305 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
306 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
307   unsigned PtrSize = EE->getTargetData()->getPointerSize();
308   for (unsigned i = 0; i < PtrSize; ++i)
309     if (*(i + (uint8_t*)Loc))
310       return false;
311   return true;
312 }
313 #endif
314
315 /// runFunctionAsMain - This is a helper function which wraps runFunction to
316 /// handle the common task of starting up main with the specified argc, argv,
317 /// and envp parameters.
318 int ExecutionEngine::runFunctionAsMain(Function *Fn,
319                                        const std::vector<std::string> &argv,
320                                        const char * const * envp) {
321   std::vector<GenericValue> GVArgs;
322   GenericValue GVArgc;
323   GVArgc.IntVal = APInt(32, argv.size());
324
325   // Check main() type
326   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
327   const FunctionType *FTy = Fn->getFunctionType();
328   const Type* PPInt8Ty = 
329     PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
330   switch (NumArgs) {
331   case 3:
332    if (FTy->getParamType(2) != PPInt8Ty) {
333      cerr << "Invalid type for third argument of main() supplied\n";
334      abort();
335    }
336    // FALLS THROUGH
337   case 2:
338    if (FTy->getParamType(1) != PPInt8Ty) {
339      cerr << "Invalid type for second argument of main() supplied\n";
340      abort();
341    }
342    // FALLS THROUGH
343   case 1:
344    if (FTy->getParamType(0) != Type::Int32Ty) {
345      cerr << "Invalid type for first argument of main() supplied\n";
346      abort();
347    }
348    // FALLS THROUGH
349   case 0:
350    if (!isa<IntegerType>(FTy->getReturnType()) &&
351        FTy->getReturnType() != Type::VoidTy) {
352      cerr << "Invalid return type of main() supplied\n";
353      abort();
354    }
355    break;
356   default:
357    cerr << "Invalid number of arguments of main() supplied\n";
358    abort();
359   }
360   
361   if (NumArgs) {
362     GVArgs.push_back(GVArgc); // Arg #0 = argc.
363     if (NumArgs > 1) {
364       GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
365       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
366              "argv[0] was null after CreateArgv");
367       if (NumArgs > 2) {
368         std::vector<std::string> EnvVars;
369         for (unsigned i = 0; envp[i]; ++i)
370           EnvVars.push_back(envp[i]);
371         GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
372       }
373     }
374   }
375   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
376 }
377
378 /// If possible, create a JIT, unless the caller specifically requests an
379 /// Interpreter or there's an error. If even an Interpreter cannot be created,
380 /// NULL is returned.
381 ///
382 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
383                                          bool ForceInterpreter,
384                                          std::string *ErrorStr,
385                                          bool Fast) {
386   ExecutionEngine *EE = 0;
387
388   // Make sure we can resolve symbols in the program as well. The zero arg
389   // to the function tells DynamicLibrary to load the program, not a library.
390   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
391     return 0;
392
393   // Unless the interpreter was explicitly selected, try making a JIT.
394   if (!ForceInterpreter && JITCtor)
395     EE = JITCtor(MP, ErrorStr, Fast);
396
397   // If we can't make a JIT, make an interpreter instead.
398   if (EE == 0 && InterpCtor)
399     EE = InterpCtor(MP, ErrorStr, Fast);
400
401   return EE;
402 }
403
404 ExecutionEngine *ExecutionEngine::create(Module *M) {
405   return create(new ExistingModuleProvider(M));
406 }
407
408 /// getPointerToGlobal - This returns the address of the specified global
409 /// value.  This may involve code generation if it's a function.
410 ///
411 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
412   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
413     return getPointerToFunction(F);
414
415   MutexGuard locked(lock);
416   void *p = state.getGlobalAddressMap(locked)[GV];
417   if (p)
418     return p;
419
420   // Global variable might have been added since interpreter started.
421   if (GlobalVariable *GVar =
422           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
423     EmitGlobalVariable(GVar);
424   else
425     assert(0 && "Global hasn't had an address allocated yet!");
426   return state.getGlobalAddressMap(locked)[GV];
427 }
428
429 /// This function converts a Constant* into a GenericValue. The interesting 
430 /// part is if C is a ConstantExpr.
431 /// @brief Get a GenericValue for a Constant*
432 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
433   // If its undefined, return the garbage.
434   if (isa<UndefValue>(C)) 
435     return GenericValue();
436
437   // If the value is a ConstantExpr
438   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
439     Constant *Op0 = CE->getOperand(0);
440     switch (CE->getOpcode()) {
441     case Instruction::GetElementPtr: {
442       // Compute the index 
443       GenericValue Result = getConstantValue(Op0);
444       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
445       uint64_t Offset =
446         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
447
448       char* tmp = (char*) Result.PointerVal;
449       Result = PTOGV(tmp + Offset);
450       return Result;
451     }
452     case Instruction::Trunc: {
453       GenericValue GV = getConstantValue(Op0);
454       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
455       GV.IntVal = GV.IntVal.trunc(BitWidth);
456       return GV;
457     }
458     case Instruction::ZExt: {
459       GenericValue GV = getConstantValue(Op0);
460       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
461       GV.IntVal = GV.IntVal.zext(BitWidth);
462       return GV;
463     }
464     case Instruction::SExt: {
465       GenericValue GV = getConstantValue(Op0);
466       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
467       GV.IntVal = GV.IntVal.sext(BitWidth);
468       return GV;
469     }
470     case Instruction::FPTrunc: {
471       // FIXME long double
472       GenericValue GV = getConstantValue(Op0);
473       GV.FloatVal = float(GV.DoubleVal);
474       return GV;
475     }
476     case Instruction::FPExt:{
477       // FIXME long double
478       GenericValue GV = getConstantValue(Op0);
479       GV.DoubleVal = double(GV.FloatVal);
480       return GV;
481     }
482     case Instruction::UIToFP: {
483       GenericValue GV = getConstantValue(Op0);
484       if (CE->getType() == Type::FloatTy)
485         GV.FloatVal = float(GV.IntVal.roundToDouble());
486       else if (CE->getType() == Type::DoubleTy)
487         GV.DoubleVal = GV.IntVal.roundToDouble();
488       else if (CE->getType() == Type::X86_FP80Ty) {
489         const uint64_t zero[] = {0, 0};
490         APFloat apf = APFloat(APInt(80, 2, zero));
491         (void)apf.convertFromAPInt(GV.IntVal, 
492                                    false,
493                                    APFloat::rmNearestTiesToEven);
494         GV.IntVal = apf.bitcastToAPInt();
495       }
496       return GV;
497     }
498     case Instruction::SIToFP: {
499       GenericValue GV = getConstantValue(Op0);
500       if (CE->getType() == Type::FloatTy)
501         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
502       else if (CE->getType() == Type::DoubleTy)
503         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
504       else if (CE->getType() == Type::X86_FP80Ty) {
505         const uint64_t zero[] = { 0, 0};
506         APFloat apf = APFloat(APInt(80, 2, zero));
507         (void)apf.convertFromAPInt(GV.IntVal, 
508                                    true,
509                                    APFloat::rmNearestTiesToEven);
510         GV.IntVal = apf.bitcastToAPInt();
511       }
512       return GV;
513     }
514     case Instruction::FPToUI: // double->APInt conversion handles sign
515     case Instruction::FPToSI: {
516       GenericValue GV = getConstantValue(Op0);
517       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
518       if (Op0->getType() == Type::FloatTy)
519         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
520       else if (Op0->getType() == Type::DoubleTy)
521         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
522       else if (Op0->getType() == Type::X86_FP80Ty) {
523         APFloat apf = APFloat(GV.IntVal);
524         uint64_t v;
525         bool ignored;
526         (void)apf.convertToInteger(&v, BitWidth,
527                                    CE->getOpcode()==Instruction::FPToSI, 
528                                    APFloat::rmTowardZero, &ignored);
529         GV.IntVal = v; // endian?
530       }
531       return GV;
532     }
533     case Instruction::PtrToInt: {
534       GenericValue GV = getConstantValue(Op0);
535       uint32_t PtrWidth = TD->getPointerSizeInBits();
536       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
537       return GV;
538     }
539     case Instruction::IntToPtr: {
540       GenericValue GV = getConstantValue(Op0);
541       uint32_t PtrWidth = TD->getPointerSizeInBits();
542       if (PtrWidth != GV.IntVal.getBitWidth())
543         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
544       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
545       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
546       return GV;
547     }
548     case Instruction::BitCast: {
549       GenericValue GV = getConstantValue(Op0);
550       const Type* DestTy = CE->getType();
551       switch (Op0->getType()->getTypeID()) {
552         default: assert(0 && "Invalid bitcast operand");
553         case Type::IntegerTyID:
554           assert(DestTy->isFloatingPoint() && "invalid bitcast");
555           if (DestTy == Type::FloatTy)
556             GV.FloatVal = GV.IntVal.bitsToFloat();
557           else if (DestTy == Type::DoubleTy)
558             GV.DoubleVal = GV.IntVal.bitsToDouble();
559           break;
560         case Type::FloatTyID: 
561           assert(DestTy == Type::Int32Ty && "Invalid bitcast");
562           GV.IntVal.floatToBits(GV.FloatVal);
563           break;
564         case Type::DoubleTyID:
565           assert(DestTy == Type::Int64Ty && "Invalid bitcast");
566           GV.IntVal.doubleToBits(GV.DoubleVal);
567           break;
568         case Type::PointerTyID:
569           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
570           break; // getConstantValue(Op0)  above already converted it
571       }
572       return GV;
573     }
574     case Instruction::Add:
575     case Instruction::Sub:
576     case Instruction::Mul:
577     case Instruction::UDiv:
578     case Instruction::SDiv:
579     case Instruction::URem:
580     case Instruction::SRem:
581     case Instruction::And:
582     case Instruction::Or:
583     case Instruction::Xor: {
584       GenericValue LHS = getConstantValue(Op0);
585       GenericValue RHS = getConstantValue(CE->getOperand(1));
586       GenericValue GV;
587       switch (CE->getOperand(0)->getType()->getTypeID()) {
588       default: assert(0 && "Bad add type!"); abort();
589       case Type::IntegerTyID:
590         switch (CE->getOpcode()) {
591           default: assert(0 && "Invalid integer opcode");
592           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
593           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
594           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
595           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
596           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
597           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
598           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
599           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
600           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
601           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
602         }
603         break;
604       case Type::FloatTyID:
605         switch (CE->getOpcode()) {
606           default: assert(0 && "Invalid float opcode"); abort();
607           case Instruction::Add:  
608             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
609           case Instruction::Sub:  
610             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
611           case Instruction::Mul:  
612             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
613           case Instruction::FDiv: 
614             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
615           case Instruction::FRem: 
616             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
617         }
618         break;
619       case Type::DoubleTyID:
620         switch (CE->getOpcode()) {
621           default: assert(0 && "Invalid double opcode"); abort();
622           case Instruction::Add:  
623             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
624           case Instruction::Sub:  
625             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
626           case Instruction::Mul:  
627             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
628           case Instruction::FDiv: 
629             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
630           case Instruction::FRem: 
631             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
632         }
633         break;
634       case Type::X86_FP80TyID:
635       case Type::PPC_FP128TyID:
636       case Type::FP128TyID: {
637         APFloat apfLHS = APFloat(LHS.IntVal);
638         switch (CE->getOpcode()) {
639           default: assert(0 && "Invalid long double opcode"); abort();
640           case Instruction::Add:  
641             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
642             GV.IntVal = apfLHS.bitcastToAPInt();
643             break;
644           case Instruction::Sub:  
645             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
646             GV.IntVal = apfLHS.bitcastToAPInt();
647             break;
648           case Instruction::Mul:  
649             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
650             GV.IntVal = apfLHS.bitcastToAPInt();
651             break;
652           case Instruction::FDiv: 
653             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
654             GV.IntVal = apfLHS.bitcastToAPInt();
655             break;
656           case Instruction::FRem: 
657             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
658             GV.IntVal = apfLHS.bitcastToAPInt();
659             break;
660           }
661         }
662         break;
663       }
664       return GV;
665     }
666     default:
667       break;
668     }
669     cerr << "ConstantExpr not handled: " << *CE << "\n";
670     abort();
671   }
672
673   GenericValue Result;
674   switch (C->getType()->getTypeID()) {
675   case Type::FloatTyID: 
676     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 
677     break;
678   case Type::DoubleTyID:
679     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
680     break;
681   case Type::X86_FP80TyID:
682   case Type::FP128TyID:
683   case Type::PPC_FP128TyID:
684     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
685     break;
686   case Type::IntegerTyID:
687     Result.IntVal = cast<ConstantInt>(C)->getValue();
688     break;
689   case Type::PointerTyID:
690     if (isa<ConstantPointerNull>(C))
691       Result.PointerVal = 0;
692     else if (const Function *F = dyn_cast<Function>(C))
693       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
694     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
695       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
696     else
697       assert(0 && "Unknown constant pointer type!");
698     break;
699   default:
700     cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
701     abort();
702   }
703   return Result;
704 }
705
706 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
707 /// with the integer held in IntVal.
708 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
709                              unsigned StoreBytes) {
710   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
711   uint8_t *Src = (uint8_t *)IntVal.getRawData();
712
713   if (sys::isLittleEndianHost())
714     // Little-endian host - the source is ordered from LSB to MSB.  Order the
715     // destination from LSB to MSB: Do a straight copy.
716     memcpy(Dst, Src, StoreBytes);
717   else {
718     // Big-endian host - the source is an array of 64 bit words ordered from
719     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
720     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
721     while (StoreBytes > sizeof(uint64_t)) {
722       StoreBytes -= sizeof(uint64_t);
723       // May not be aligned so use memcpy.
724       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
725       Src += sizeof(uint64_t);
726     }
727
728     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
729   }
730 }
731
732 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
733 /// is the address of the memory at which to store Val, cast to GenericValue *.
734 /// It is not a pointer to a GenericValue containing the address at which to
735 /// store Val.
736 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
737                                          GenericValue *Ptr, const Type *Ty) {
738   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
739
740   switch (Ty->getTypeID()) {
741   case Type::IntegerTyID:
742     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
743     break;
744   case Type::FloatTyID:
745     *((float*)Ptr) = Val.FloatVal;
746     break;
747   case Type::DoubleTyID:
748     *((double*)Ptr) = Val.DoubleVal;
749     break;
750   case Type::X86_FP80TyID: {
751       uint16_t *Dest = (uint16_t*)Ptr;
752       const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
753       // This is endian dependent, but it will only work on x86 anyway.
754       Dest[0] = Src[4];
755       Dest[1] = Src[0];
756       Dest[2] = Src[1];
757       Dest[3] = Src[2];
758       Dest[4] = Src[3];
759       break;
760     }
761   case Type::PointerTyID:
762     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
763     if (StoreBytes != sizeof(PointerTy))
764       memset(Ptr, 0, StoreBytes);
765
766     *((PointerTy*)Ptr) = Val.PointerVal;
767     break;
768   default:
769     cerr << "Cannot store value of type " << *Ty << "!\n";
770   }
771
772   if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
773     // Host and target are different endian - reverse the stored bytes.
774     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
775 }
776
777 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
778 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
779 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
780   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
781   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
782
783   if (sys::isLittleEndianHost())
784     // Little-endian host - the destination must be ordered from LSB to MSB.
785     // The source is ordered from LSB to MSB: Do a straight copy.
786     memcpy(Dst, Src, LoadBytes);
787   else {
788     // Big-endian - the destination is an array of 64 bit words ordered from
789     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
790     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
791     // a word.
792     while (LoadBytes > sizeof(uint64_t)) {
793       LoadBytes -= sizeof(uint64_t);
794       // May not be aligned so use memcpy.
795       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
796       Dst += sizeof(uint64_t);
797     }
798
799     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
800   }
801 }
802
803 /// FIXME: document
804 ///
805 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
806                                           GenericValue *Ptr,
807                                           const Type *Ty) {
808   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
809
810   if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) {
811     // Host and target are different endian - reverse copy the stored
812     // bytes into a buffer, and load from that.
813     uint8_t *Src = (uint8_t*)Ptr;
814     uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
815     std::reverse_copy(Src, Src + LoadBytes, Buf);
816     Ptr = (GenericValue*)Buf;
817   }
818
819   switch (Ty->getTypeID()) {
820   case Type::IntegerTyID:
821     // An APInt with all words initially zero.
822     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
823     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
824     break;
825   case Type::FloatTyID:
826     Result.FloatVal = *((float*)Ptr);
827     break;
828   case Type::DoubleTyID:
829     Result.DoubleVal = *((double*)Ptr);
830     break;
831   case Type::PointerTyID:
832     Result.PointerVal = *((PointerTy*)Ptr);
833     break;
834   case Type::X86_FP80TyID: {
835     // This is endian dependent, but it will only work on x86 anyway.
836     // FIXME: Will not trap if loading a signaling NaN.
837     uint16_t *p = (uint16_t*)Ptr;
838     union {
839       uint16_t x[8];
840       uint64_t y[2];
841     };
842     x[0] = p[1];
843     x[1] = p[2];
844     x[2] = p[3];
845     x[3] = p[4];
846     x[4] = p[0];
847     Result.IntVal = APInt(80, 2, y);
848     break;
849   }
850   default:
851     cerr << "Cannot load value of type " << *Ty << "!\n";
852     abort();
853   }
854 }
855
856 // InitializeMemory - Recursive function to apply a Constant value into the
857 // specified memory location...
858 //
859 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
860   DOUT << "JIT: Initializing " << Addr << " ";
861   DEBUG(Init->dump());
862   if (isa<UndefValue>(Init)) {
863     return;
864   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
865     unsigned ElementSize =
866       getTargetData()->getTypePaddedSize(CP->getType()->getElementType());
867     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
868       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
869     return;
870   } else if (isa<ConstantAggregateZero>(Init)) {
871     memset(Addr, 0, (size_t)getTargetData()->getTypePaddedSize(Init->getType()));
872     return;
873   } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
874     unsigned ElementSize =
875       getTargetData()->getTypePaddedSize(CPA->getType()->getElementType());
876     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
877       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
878     return;
879   } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
880     const StructLayout *SL =
881       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
882     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
883       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
884     return;
885   } else if (Init->getType()->isFirstClassType()) {
886     GenericValue Val = getConstantValue(Init);
887     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
888     return;
889   }
890
891   cerr << "Bad Type: " << *Init->getType() << "\n";
892   assert(0 && "Unknown constant type to initialize memory with!");
893 }
894
895 /// EmitGlobals - Emit all of the global variables to memory, storing their
896 /// addresses into GlobalAddress.  This must make sure to copy the contents of
897 /// their initializers into the memory.
898 ///
899 void ExecutionEngine::emitGlobals() {
900
901   // Loop over all of the global variables in the program, allocating the memory
902   // to hold them.  If there is more than one module, do a prepass over globals
903   // to figure out how the different modules should link together.
904   //
905   std::map<std::pair<std::string, const Type*>,
906            const GlobalValue*> LinkedGlobalsMap;
907
908   if (Modules.size() != 1) {
909     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
910       Module &M = *Modules[m]->getModule();
911       for (Module::const_global_iterator I = M.global_begin(),
912            E = M.global_end(); I != E; ++I) {
913         const GlobalValue *GV = I;
914         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
915             GV->hasAppendingLinkage() || !GV->hasName())
916           continue;// Ignore external globals and globals with internal linkage.
917           
918         const GlobalValue *&GVEntry = 
919           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
920
921         // If this is the first time we've seen this global, it is the canonical
922         // version.
923         if (!GVEntry) {
924           GVEntry = GV;
925           continue;
926         }
927         
928         // If the existing global is strong, never replace it.
929         if (GVEntry->hasExternalLinkage() ||
930             GVEntry->hasDLLImportLinkage() ||
931             GVEntry->hasDLLExportLinkage())
932           continue;
933         
934         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
935         // symbol.  FIXME is this right for common?
936         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
937           GVEntry = GV;
938       }
939     }
940   }
941   
942   std::vector<const GlobalValue*> NonCanonicalGlobals;
943   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
944     Module &M = *Modules[m]->getModule();
945     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
946          I != E; ++I) {
947       // In the multi-module case, see what this global maps to.
948       if (!LinkedGlobalsMap.empty()) {
949         if (const GlobalValue *GVEntry = 
950               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
951           // If something else is the canonical global, ignore this one.
952           if (GVEntry != &*I) {
953             NonCanonicalGlobals.push_back(I);
954             continue;
955           }
956         }
957       }
958       
959       if (!I->isDeclaration()) {
960         addGlobalMapping(I, getMemoryForGV(I));
961       } else {
962         // External variable reference. Try to use the dynamic loader to
963         // get a pointer to it.
964         if (void *SymAddr =
965             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
966           addGlobalMapping(I, SymAddr);
967         else {
968           cerr << "Could not resolve external global address: "
969                << I->getName() << "\n";
970           abort();
971         }
972       }
973     }
974     
975     // If there are multiple modules, map the non-canonical globals to their
976     // canonical location.
977     if (!NonCanonicalGlobals.empty()) {
978       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
979         const GlobalValue *GV = NonCanonicalGlobals[i];
980         const GlobalValue *CGV =
981           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
982         void *Ptr = getPointerToGlobalIfAvailable(CGV);
983         assert(Ptr && "Canonical global wasn't codegen'd!");
984         addGlobalMapping(GV, Ptr);
985       }
986     }
987     
988     // Now that all of the globals are set up in memory, loop through them all 
989     // and initialize their contents.
990     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
991          I != E; ++I) {
992       if (!I->isDeclaration()) {
993         if (!LinkedGlobalsMap.empty()) {
994           if (const GlobalValue *GVEntry = 
995                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
996             if (GVEntry != &*I)  // Not the canonical variable.
997               continue;
998         }
999         EmitGlobalVariable(I);
1000       }
1001     }
1002   }
1003 }
1004
1005 // EmitGlobalVariable - This method emits the specified global variable to the
1006 // address specified in GlobalAddresses, or allocates new memory if it's not
1007 // already in the map.
1008 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1009   void *GA = getPointerToGlobalIfAvailable(GV);
1010
1011   if (GA == 0) {
1012     // If it's not already specified, allocate memory for the global.
1013     GA = getMemoryForGV(GV);
1014     addGlobalMapping(GV, GA);
1015   }
1016   
1017   // Don't initialize if it's thread local, let the client do it.
1018   if (!GV->isThreadLocal())
1019     InitializeMemory(GV->getInitializer(), GA);
1020   
1021   const Type *ElTy = GV->getType()->getElementType();
1022   size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
1023   NumInitBytes += (unsigned)GVSize;
1024   ++NumGlobals;
1025 }