1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
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"
33 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34 STATISTIC(NumGlobals , "Number of global vars initialized");
36 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
41 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
42 LazyCompilationDisabled = false;
43 GVCompilationDisabled = false;
44 SymbolSearchingDisabled = false;
46 assert(P && "ModuleProvider is null?");
49 ExecutionEngine::~ExecutionEngine() {
50 clearAllGlobalMappings();
51 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
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];
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;
71 clearGlobalMappingsFromModule(MP->getModule());
72 return MP->releaseModule(ErrInfo);
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;
88 clearGlobalMappingsFromModule(MP->getModule());
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
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))
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);
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!");
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!");
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);
133 state.getGlobalAddressMap(locked).clear();
134 state.getGlobalAddressReverseMap(locked).clear();
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);
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);
146 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
148 state.getGlobalAddressMap(locked).erase(GI);
149 state.getGlobalAddressReverseMap(locked).erase(GI);
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);
159 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
161 // Deleting from the mapping?
163 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
172 if (!state.getGlobalAddressReverseMap(locked).empty())
173 state.getGlobalAddressReverseMap(locked).erase(Addr);
177 void *&CurVal = Map[GV];
178 void *OldVal = CurVal;
180 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
181 state.getGlobalAddressReverseMap(locked).erase(CurVal);
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!");
193 /// getPointerToGlobalIfAvailable - This returns the address of the specified
194 /// global value if it is has already been codegen'd, otherwise it returns null.
196 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
199 std::map<const GlobalValue*, void*>::iterator I =
200 state.getGlobalAddressMap(locked).find(GV);
201 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
204 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
205 /// at the specified address.
207 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
208 MutexGuard locked(lock);
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,
219 std::map<void *, const GlobalValue*>::iterator I =
220 state.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
224 // CreateArgv - Turn a vector of strings into a nice argv style array of
225 // pointers to null terminated strings.
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];
232 DOUT << "JIT: ARGV = " << (void*)Result << "\n";
233 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
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";
240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
243 // Endian safe: Result[i] = (PointerTy)Dest;
244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
249 EE->StoreValueToMemory(PTOGV(0),
250 (GenericValue*)(Result+InputArgv.size()*PtrSize),
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";
262 // Execute global ctors/dtors for each module in the program.
264 GlobalVariable *GV = module->getNamedGlobal(Name);
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
270 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
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.
281 Constant *FP = CS->getOperand(1);
282 if (FP->isNullValue())
283 break; // Found a null terminator, exit.
285 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
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>());
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);
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))
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;
323 GVArgc.IntVal = APInt(32, argv.size());
326 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
327 const FunctionType *FTy = Fn->getFunctionType();
328 const Type* PPInt8Ty =
329 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
332 if (FTy->getParamType(2) != PPInt8Ty) {
333 cerr << "Invalid type for third argument of main() supplied\n";
338 if (FTy->getParamType(1) != PPInt8Ty) {
339 cerr << "Invalid type for second argument of main() supplied\n";
344 if (FTy->getParamType(0) != Type::Int32Ty) {
345 cerr << "Invalid type for first argument of main() supplied\n";
350 if (FTy->getReturnType() != Type::Int32Ty &&
351 FTy->getReturnType() != Type::VoidTy) {
352 cerr << "Invalid return type of main() supplied\n";
357 cerr << "Invalid number of arguments of main() supplied\n";
362 GVArgs.push_back(GVArgc); // Arg #0 = argc.
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");
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.
375 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
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.
382 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
383 bool ForceInterpreter,
384 std::string *ErrorStr,
386 ExecutionEngine *EE = 0;
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))
393 // Unless the interpreter was explicitly selected, try making a JIT.
394 if (!ForceInterpreter && JITCtor)
395 EE = JITCtor(MP, ErrorStr, Fast);
397 // If we can't make a JIT, make an interpreter instead.
398 if (EE == 0 && InterpCtor)
399 EE = InterpCtor(MP, ErrorStr, Fast);
404 ExecutionEngine *ExecutionEngine::create(Module *M) {
405 return create(new ExistingModuleProvider(M));
408 /// getPointerToGlobal - This returns the address of the specified global
409 /// value. This may involve code generation if it's a function.
411 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
412 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
413 return getPointerToFunction(F);
415 MutexGuard locked(lock);
416 void *p = state.getGlobalAddressMap(locked)[GV];
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);
425 assert(0 && "Global hasn't had an address allocated yet!");
426 return state.getGlobalAddressMap(locked)[GV];
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();
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: {
443 GenericValue Result = getConstantValue(Op0);
444 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
446 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
448 char* tmp = (char*) Result.PointerVal;
449 Result = PTOGV(tmp + Offset);
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);
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);
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);
470 case Instruction::FPTrunc: {
472 GenericValue GV = getConstantValue(Op0);
473 GV.FloatVal = float(GV.DoubleVal);
476 case Instruction::FPExt:{
478 GenericValue GV = getConstantValue(Op0);
479 GV.DoubleVal = double(GV.FloatVal);
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,
493 APFloat::rmNearestTiesToEven);
494 GV.IntVal = apf.bitcastToAPInt();
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,
509 APFloat::rmNearestTiesToEven);
510 GV.IntVal = apf.bitcastToAPInt();
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);
526 (void)apf.convertToInteger(&v, BitWidth,
527 CE->getOpcode()==Instruction::FPToSI,
528 APFloat::rmTowardZero, &ignored);
529 GV.IntVal = v; // endian?
533 case Instruction::PtrToInt: {
534 GenericValue GV = getConstantValue(Op0);
535 uint32_t PtrWidth = TD->getPointerSizeInBits();
536 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
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()));
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();
560 case Type::FloatTyID:
561 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
562 GV.IntVal.floatToBits(GV.FloatVal);
564 case Type::DoubleTyID:
565 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
566 GV.IntVal.doubleToBits(GV.DoubleVal);
568 case Type::PointerTyID:
569 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
570 break; // getConstantValue(Op0) above already converted it
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));
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;
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;
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;
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();
644 case Instruction::Sub:
645 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
646 GV.IntVal = apfLHS.bitcastToAPInt();
648 case Instruction::Mul:
649 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
650 GV.IntVal = apfLHS.bitcastToAPInt();
652 case Instruction::FDiv:
653 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
654 GV.IntVal = apfLHS.bitcastToAPInt();
656 case Instruction::FRem:
657 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
658 GV.IntVal = apfLHS.bitcastToAPInt();
669 cerr << "ConstantExpr not handled: " << *CE << "\n";
674 switch (C->getType()->getTypeID()) {
675 case Type::FloatTyID:
676 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
678 case Type::DoubleTyID:
679 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
681 case Type::X86_FP80TyID:
682 case Type::FP128TyID:
683 case Type::PPC_FP128TyID:
684 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
686 case Type::IntegerTyID:
687 Result.IntVal = cast<ConstantInt>(C)->getValue();
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)));
697 assert(0 && "Unknown constant pointer type!");
700 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
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();
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);
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);
728 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
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
736 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
737 GenericValue *Ptr, const Type *Ty) {
738 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
740 switch (Ty->getTypeID()) {
741 case Type::IntegerTyID:
742 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
744 case Type::FloatTyID:
745 *((float*)Ptr) = Val.FloatVal;
747 case Type::DoubleTyID:
748 *((double*)Ptr) = Val.DoubleVal;
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.
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);
766 *((PointerTy*)Ptr) = Val.PointerVal;
769 cerr << "Cannot store value of type " << *Ty << "!\n";
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);
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();
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);
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
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);
799 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
805 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
808 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
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;
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);
825 case Type::FloatTyID:
826 Result.FloatVal = *((float*)Ptr);
828 case Type::DoubleTyID:
829 Result.DoubleVal = *((double*)Ptr);
831 case Type::PointerTyID:
832 Result.PointerVal = *((PointerTy*)Ptr);
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;
847 Result.IntVal = APInt(80, 2, y);
851 cerr << "Cannot load value of type " << *Ty << "!\n";
856 // InitializeMemory - Recursive function to apply a Constant value into the
857 // specified memory location...
859 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
860 DOUT << "JIT: Initializing " << Addr << " ";
862 if (isa<UndefValue>(Init)) {
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);
870 } else if (isa<ConstantAggregateZero>(Init)) {
871 memset(Addr, 0, (size_t)getTargetData()->getTypePaddedSize(Init->getType()));
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);
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));
885 } else if (Init->getType()->isFirstClassType()) {
886 GenericValue Val = getConstantValue(Init);
887 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
891 cerr << "Bad Type: " << *Init->getType() << "\n";
892 assert(0 && "Unknown constant type to initialize memory with!");
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.
899 void ExecutionEngine::emitGlobals() {
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.
905 std::map<std::pair<std::string, const Type*>,
906 const GlobalValue*> LinkedGlobalsMap;
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.
918 const GlobalValue *&GVEntry =
919 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
921 // If this is the first time we've seen this global, it is the canonical
928 // If the existing global is strong, never replace it.
929 if (GVEntry->hasExternalLinkage() ||
930 GVEntry->hasDLLImportLinkage() ||
931 GVEntry->hasDLLExportLinkage())
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())
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();
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);
959 if (!I->isDeclaration()) {
960 addGlobalMapping(I, getMemoryForGV(I));
962 // External variable reference. Try to use the dynamic loader to
963 // get a pointer to it.
965 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
966 addGlobalMapping(I, SymAddr);
968 cerr << "Could not resolve external global address: "
969 << I->getName() << "\n";
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);
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();
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.
999 EmitGlobalVariable(I);
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);
1012 // If it's not already specified, allocate memory for the global.
1013 GA = getMemoryForGV(GV);
1014 addGlobalMapping(GV, GA);
1017 // Don't initialize if it's thread local, let the client do it.
1018 if (!GV->isThreadLocal())
1019 InitializeMemory(GV->getInitializer(), GA);
1021 const Type *ElTy = GV->getType()->getElementType();
1022 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
1023 NumInitBytes += (unsigned)GVSize;