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