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