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/ExecutionEngine/ExecutionEngine.h"
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"
36 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37 STATISTIC(NumGlobals , "Number of global vars initialized");
39 ExecutionEngine *(*ExecutionEngine::JITCtor)(
41 std::string *ErrorStr,
42 JITMemoryManager *JMM,
43 CodeGenOpt::Level OptLevel,
48 const SmallVectorImpl<std::string>& MAttrs) = 0;
49 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
51 std::string *ErrorStr,
52 JITMemoryManager *JMM,
53 CodeGenOpt::Level OptLevel,
58 const SmallVectorImpl<std::string>& MAttrs) = 0;
59 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
60 std::string *ErrorStr) = 0;
62 ExecutionEngine::ExecutionEngine(Module *M)
64 LazyFunctionCreator(0),
65 ExceptionTableRegister(0),
66 ExceptionTableDeregister(0) {
67 CompilingLazily = false;
68 GVCompilationDisabled = false;
69 SymbolSearchingDisabled = false;
71 assert(M && "Module is null?");
74 ExecutionEngine::~ExecutionEngine() {
75 clearAllGlobalMappings();
76 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
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();
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)) {}
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))
106 new(RawMemory) GVMemoryBlock(GV);
107 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
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
114 this->~GVMemoryBlock();
115 ::operator delete(this);
118 } // anonymous namespace
120 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
121 return GVMemoryBlock::Create(GV, *getTargetData());
124 bool ExecutionEngine::removeModule(Module *M) {
125 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
126 E = Modules.end(); I != E; ++I) {
130 clearGlobalMappingsFromModule(M);
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))
146 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
147 const GlobalValue *ToUnmap) {
148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
153 if (I == GlobalAddressMap.end())
157 GlobalAddressMap.erase(I);
160 GlobalAddressReverseMap.erase(OldVal);
164 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
165 MutexGuard locked(lock);
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!");
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!");
182 void ExecutionEngine::clearAllGlobalMappings() {
183 MutexGuard locked(lock);
185 EEState.getGlobalAddressMap(locked).clear();
186 EEState.getGlobalAddressReverseMap(locked).clear();
189 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
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();
196 EEState.RemoveMapping(locked, GI);
199 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
200 MutexGuard locked(lock);
202 ExecutionEngineState::GlobalAddressMapTy &Map =
203 EEState.getGlobalAddressMap(locked);
205 // Deleting from the mapping?
207 return EEState.RemoveMapping(locked, GV);
209 void *&CurVal = Map[GV];
210 void *OldVal = CurVal;
212 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
213 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
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!");
226 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
227 MutexGuard locked(lock);
229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
230 EEState.getGlobalAddressMap(locked).find(GV);
231 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
234 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
235 MutexGuard locked(lock);
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));
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;
254 std::vector<char*> Values;
256 ArgvArray() : Array(NULL) {}
257 ~ArgvArray() { clear(); }
261 for (size_t I = 0, E = Values.size(); I != E; ++I) {
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);
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];
278 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
279 const Type *SBytePtr = Type::getInt8PtrTy(C);
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");
287 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
290 // Endian safe: Array[i] = (PointerTy)Dest;
291 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
296 EE->StoreValueToMemory(PTOGV(0),
297 (GenericValue*)(Array+InputArgv.size()*PtrSize),
302 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
304 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
305 GlobalVariable *GV = module->getNamedGlobal(Name);
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
311 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
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) {
319 dyn_cast<ConstantStruct>(InitList->getOperand(i));
321 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
323 Constant *FP = CS->getOperand(1);
324 if (FP->isNullValue())
325 break; // Found a null terminator, exit.
327 // Strip off constant expression casts.
328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
330 FP = CE->getOperand(0);
332 // Execute the ctor/dtor function!
333 if (Function *F = dyn_cast<Function>(FP))
334 runFunction(F, std::vector<GenericValue>());
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.
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);
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))
359 int ExecutionEngine::runFunctionAsMain(Function *Fn,
360 const std::vector<std::string> &argv,
361 const char * const * envp) {
362 std::vector<GenericValue> GVArgs;
364 GVArgc.IntVal = APInt(32, argv.size());
367 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
368 const FunctionType *FTy = Fn->getFunctionType();
369 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
371 // Check the argument types.
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");
387 GVArgs.push_back(GVArgc); // Arg #0 = argc.
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");
394 std::vector<std::string> EnvVars;
395 for (unsigned i = 0; envp[i]; ++i)
396 EnvVars.push_back(envp[i]);
398 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
403 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
406 ExecutionEngine *ExecutionEngine::create(Module *M,
407 bool ForceInterpreter,
408 std::string *ErrorStr,
409 CodeGenOpt::Level OptLevel,
411 return EngineBuilder(M)
412 .setEngineKind(ForceInterpreter
413 ? EngineKind::Interpreter
415 .setErrorStr(ErrorStr)
416 .setOptLevel(OptLevel)
417 .setAllocateGVsWithCode(GVsWithCode)
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))
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
431 if (WhichEngine & EngineKind::JIT)
432 WhichEngine = EngineKind::JIT;
435 *ErrorStr = "Cannot create an interpreter with a memory manager.";
440 // Unless the interpreter was explicitly selected or the JIT is not linked,
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);
449 } else if (ExecutionEngine::JITCtor) {
450 ExecutionEngine *EE =
451 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
452 AllocateGVsWithCode, CMModel,
453 MArch, MCPU, MAttrs);
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);
464 *ErrorStr = "Interpreter has not been linked in.";
468 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
470 *ErrorStr = "JIT has not been linked in.";
476 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
477 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
478 return getPointerToFunction(F);
480 MutexGuard locked(lock);
481 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
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);
489 llvm_unreachable("Global hasn't had an address allocated yet!");
491 return EEState.getGlobalAddressMap(locked)[GV];
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)) {
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);
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: {
521 GenericValue Result = getConstantValue(Op0);
522 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
524 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
526 char* tmp = (char*) Result.PointerVal;
527 Result = PTOGV(tmp + Offset);
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);
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);
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);
548 case Instruction::FPTrunc: {
550 GenericValue GV = getConstantValue(Op0);
551 GV.FloatVal = float(GV.DoubleVal);
554 case Instruction::FPExt:{
556 GenericValue GV = getConstantValue(Op0);
557 GV.DoubleVal = double(GV.FloatVal);
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 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
568 (void)apf.convertFromAPInt(GV.IntVal,
570 APFloat::rmNearestTiesToEven);
571 GV.IntVal = apf.bitcastToAPInt();
575 case Instruction::SIToFP: {
576 GenericValue GV = getConstantValue(Op0);
577 if (CE->getType()->isFloatTy())
578 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
579 else if (CE->getType()->isDoubleTy())
580 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
581 else if (CE->getType()->isX86_FP80Ty()) {
582 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
583 (void)apf.convertFromAPInt(GV.IntVal,
585 APFloat::rmNearestTiesToEven);
586 GV.IntVal = apf.bitcastToAPInt();
590 case Instruction::FPToUI: // double->APInt conversion handles sign
591 case Instruction::FPToSI: {
592 GenericValue GV = getConstantValue(Op0);
593 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
594 if (Op0->getType()->isFloatTy())
595 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
596 else if (Op0->getType()->isDoubleTy())
597 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
598 else if (Op0->getType()->isX86_FP80Ty()) {
599 APFloat apf = APFloat(GV.IntVal);
602 (void)apf.convertToInteger(&v, BitWidth,
603 CE->getOpcode()==Instruction::FPToSI,
604 APFloat::rmTowardZero, &ignored);
605 GV.IntVal = v; // endian?
609 case Instruction::PtrToInt: {
610 GenericValue GV = getConstantValue(Op0);
611 uint32_t PtrWidth = TD->getPointerSizeInBits();
612 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
615 case Instruction::IntToPtr: {
616 GenericValue GV = getConstantValue(Op0);
617 uint32_t PtrWidth = TD->getPointerSizeInBits();
618 if (PtrWidth != GV.IntVal.getBitWidth())
619 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
620 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
621 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
624 case Instruction::BitCast: {
625 GenericValue GV = getConstantValue(Op0);
626 const Type* DestTy = CE->getType();
627 switch (Op0->getType()->getTypeID()) {
628 default: llvm_unreachable("Invalid bitcast operand");
629 case Type::IntegerTyID:
630 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
631 if (DestTy->isFloatTy())
632 GV.FloatVal = GV.IntVal.bitsToFloat();
633 else if (DestTy->isDoubleTy())
634 GV.DoubleVal = GV.IntVal.bitsToDouble();
636 case Type::FloatTyID:
637 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
638 GV.IntVal = APInt::floatToBits(GV.FloatVal);
640 case Type::DoubleTyID:
641 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
642 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
644 case Type::PointerTyID:
645 assert(DestTy->isPointerTy() && "Invalid bitcast");
646 break; // getConstantValue(Op0) above already converted it
650 case Instruction::Add:
651 case Instruction::FAdd:
652 case Instruction::Sub:
653 case Instruction::FSub:
654 case Instruction::Mul:
655 case Instruction::FMul:
656 case Instruction::UDiv:
657 case Instruction::SDiv:
658 case Instruction::URem:
659 case Instruction::SRem:
660 case Instruction::And:
661 case Instruction::Or:
662 case Instruction::Xor: {
663 GenericValue LHS = getConstantValue(Op0);
664 GenericValue RHS = getConstantValue(CE->getOperand(1));
666 switch (CE->getOperand(0)->getType()->getTypeID()) {
667 default: llvm_unreachable("Bad add type!");
668 case Type::IntegerTyID:
669 switch (CE->getOpcode()) {
670 default: llvm_unreachable("Invalid integer opcode");
671 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
672 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
673 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
674 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
675 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
676 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
677 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
678 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
679 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
680 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
683 case Type::FloatTyID:
684 switch (CE->getOpcode()) {
685 default: llvm_unreachable("Invalid float opcode");
686 case Instruction::FAdd:
687 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
688 case Instruction::FSub:
689 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
690 case Instruction::FMul:
691 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
692 case Instruction::FDiv:
693 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
694 case Instruction::FRem:
695 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
698 case Type::DoubleTyID:
699 switch (CE->getOpcode()) {
700 default: llvm_unreachable("Invalid double opcode");
701 case Instruction::FAdd:
702 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
703 case Instruction::FSub:
704 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
705 case Instruction::FMul:
706 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
707 case Instruction::FDiv:
708 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
709 case Instruction::FRem:
710 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
713 case Type::X86_FP80TyID:
714 case Type::PPC_FP128TyID:
715 case Type::FP128TyID: {
716 APFloat apfLHS = APFloat(LHS.IntVal);
717 switch (CE->getOpcode()) {
718 default: llvm_unreachable("Invalid long double opcode");
719 case Instruction::FAdd:
720 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
721 GV.IntVal = apfLHS.bitcastToAPInt();
723 case Instruction::FSub:
724 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
725 GV.IntVal = apfLHS.bitcastToAPInt();
727 case Instruction::FMul:
728 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
729 GV.IntVal = apfLHS.bitcastToAPInt();
731 case Instruction::FDiv:
732 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
733 GV.IntVal = apfLHS.bitcastToAPInt();
735 case Instruction::FRem:
736 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
737 GV.IntVal = apfLHS.bitcastToAPInt();
749 SmallString<256> Msg;
750 raw_svector_ostream OS(Msg);
751 OS << "ConstantExpr not handled: " << *CE;
752 report_fatal_error(OS.str());
755 // Otherwise, we have a simple constant.
757 switch (C->getType()->getTypeID()) {
758 case Type::FloatTyID:
759 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
761 case Type::DoubleTyID:
762 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
764 case Type::X86_FP80TyID:
765 case Type::FP128TyID:
766 case Type::PPC_FP128TyID:
767 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
769 case Type::IntegerTyID:
770 Result.IntVal = cast<ConstantInt>(C)->getValue();
772 case Type::PointerTyID:
773 if (isa<ConstantPointerNull>(C))
774 Result.PointerVal = 0;
775 else if (const Function *F = dyn_cast<Function>(C))
776 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
777 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
778 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
779 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
780 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
781 BA->getBasicBlock())));
783 llvm_unreachable("Unknown constant pointer type!");
786 SmallString<256> Msg;
787 raw_svector_ostream OS(Msg);
788 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
789 report_fatal_error(OS.str());
795 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
796 /// with the integer held in IntVal.
797 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
798 unsigned StoreBytes) {
799 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
800 uint8_t *Src = (uint8_t *)IntVal.getRawData();
802 if (sys::isLittleEndianHost()) {
803 // Little-endian host - the source is ordered from LSB to MSB. Order the
804 // destination from LSB to MSB: Do a straight copy.
805 memcpy(Dst, Src, StoreBytes);
807 // Big-endian host - the source is an array of 64 bit words ordered from
808 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
809 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
810 while (StoreBytes > sizeof(uint64_t)) {
811 StoreBytes -= sizeof(uint64_t);
812 // May not be aligned so use memcpy.
813 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
814 Src += sizeof(uint64_t);
817 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
821 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
822 GenericValue *Ptr, const Type *Ty) {
823 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
825 switch (Ty->getTypeID()) {
826 case Type::IntegerTyID:
827 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
829 case Type::FloatTyID:
830 *((float*)Ptr) = Val.FloatVal;
832 case Type::DoubleTyID:
833 *((double*)Ptr) = Val.DoubleVal;
835 case Type::X86_FP80TyID:
836 memcpy(Ptr, Val.IntVal.getRawData(), 10);
838 case Type::PointerTyID:
839 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
840 if (StoreBytes != sizeof(PointerTy))
841 memset(Ptr, 0, StoreBytes);
843 *((PointerTy*)Ptr) = Val.PointerVal;
846 dbgs() << "Cannot store value of type " << *Ty << "!\n";
849 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
850 // Host and target are different endian - reverse the stored bytes.
851 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
854 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
855 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
856 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
857 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
858 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
860 if (sys::isLittleEndianHost())
861 // Little-endian host - the destination must be ordered from LSB to MSB.
862 // The source is ordered from LSB to MSB: Do a straight copy.
863 memcpy(Dst, Src, LoadBytes);
865 // Big-endian - the destination is an array of 64 bit words ordered from
866 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
867 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
869 while (LoadBytes > sizeof(uint64_t)) {
870 LoadBytes -= sizeof(uint64_t);
871 // May not be aligned so use memcpy.
872 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
873 Dst += sizeof(uint64_t);
876 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
882 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
885 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
887 switch (Ty->getTypeID()) {
888 case Type::IntegerTyID:
889 // An APInt with all words initially zero.
890 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
891 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
893 case Type::FloatTyID:
894 Result.FloatVal = *((float*)Ptr);
896 case Type::DoubleTyID:
897 Result.DoubleVal = *((double*)Ptr);
899 case Type::PointerTyID:
900 Result.PointerVal = *((PointerTy*)Ptr);
902 case Type::X86_FP80TyID: {
903 // This is endian dependent, but it will only work on x86 anyway.
904 // FIXME: Will not trap if loading a signaling NaN.
907 Result.IntVal = APInt(80, 2, y);
911 SmallString<256> Msg;
912 raw_svector_ostream OS(Msg);
913 OS << "Cannot load value of type " << *Ty << "!";
914 report_fatal_error(OS.str());
918 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
919 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
921 if (isa<UndefValue>(Init)) {
923 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
924 unsigned ElementSize =
925 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
926 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
927 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
929 } else if (isa<ConstantAggregateZero>(Init)) {
930 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
932 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
933 unsigned ElementSize =
934 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
935 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
936 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
938 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
939 const StructLayout *SL =
940 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
941 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
942 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
944 } else if (Init->getType()->isFirstClassType()) {
945 GenericValue Val = getConstantValue(Init);
946 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
950 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
951 llvm_unreachable("Unknown constant type to initialize memory with!");
954 /// EmitGlobals - Emit all of the global variables to memory, storing their
955 /// addresses into GlobalAddress. This must make sure to copy the contents of
956 /// their initializers into the memory.
957 void ExecutionEngine::emitGlobals() {
958 // Loop over all of the global variables in the program, allocating the memory
959 // to hold them. If there is more than one module, do a prepass over globals
960 // to figure out how the different modules should link together.
961 std::map<std::pair<std::string, const Type*>,
962 const GlobalValue*> LinkedGlobalsMap;
964 if (Modules.size() != 1) {
965 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
966 Module &M = *Modules[m];
967 for (Module::const_global_iterator I = M.global_begin(),
968 E = M.global_end(); I != E; ++I) {
969 const GlobalValue *GV = I;
970 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
971 GV->hasAppendingLinkage() || !GV->hasName())
972 continue;// Ignore external globals and globals with internal linkage.
974 const GlobalValue *&GVEntry =
975 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
977 // If this is the first time we've seen this global, it is the canonical
984 // If the existing global is strong, never replace it.
985 if (GVEntry->hasExternalLinkage() ||
986 GVEntry->hasDLLImportLinkage() ||
987 GVEntry->hasDLLExportLinkage())
990 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
991 // symbol. FIXME is this right for common?
992 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
998 std::vector<const GlobalValue*> NonCanonicalGlobals;
999 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1000 Module &M = *Modules[m];
1001 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1003 // In the multi-module case, see what this global maps to.
1004 if (!LinkedGlobalsMap.empty()) {
1005 if (const GlobalValue *GVEntry =
1006 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1007 // If something else is the canonical global, ignore this one.
1008 if (GVEntry != &*I) {
1009 NonCanonicalGlobals.push_back(I);
1015 if (!I->isDeclaration()) {
1016 addGlobalMapping(I, getMemoryForGV(I));
1018 // External variable reference. Try to use the dynamic loader to
1019 // get a pointer to it.
1021 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1022 addGlobalMapping(I, SymAddr);
1024 report_fatal_error("Could not resolve external global address: "
1030 // If there are multiple modules, map the non-canonical globals to their
1031 // canonical location.
1032 if (!NonCanonicalGlobals.empty()) {
1033 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1034 const GlobalValue *GV = NonCanonicalGlobals[i];
1035 const GlobalValue *CGV =
1036 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1037 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1038 assert(Ptr && "Canonical global wasn't codegen'd!");
1039 addGlobalMapping(GV, Ptr);
1043 // Now that all of the globals are set up in memory, loop through them all
1044 // and initialize their contents.
1045 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1047 if (!I->isDeclaration()) {
1048 if (!LinkedGlobalsMap.empty()) {
1049 if (const GlobalValue *GVEntry =
1050 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1051 if (GVEntry != &*I) // Not the canonical variable.
1054 EmitGlobalVariable(I);
1060 // EmitGlobalVariable - This method emits the specified global variable to the
1061 // address specified in GlobalAddresses, or allocates new memory if it's not
1062 // already in the map.
1063 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1064 void *GA = getPointerToGlobalIfAvailable(GV);
1067 // If it's not already specified, allocate memory for the global.
1068 GA = getMemoryForGV(GV);
1069 addGlobalMapping(GV, GA);
1072 // Don't initialize if it's thread local, let the client do it.
1073 if (!GV->isThreadLocal())
1074 InitializeMemory(GV->getInitializer(), GA);
1076 const Type *ElTy = GV->getType()->getElementType();
1077 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1078 NumInitBytes += (unsigned)GVSize;
1082 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1083 : EE(EE), GlobalAddressMap(this) {
1087 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1088 return &EES->EE.lock;
1091 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1092 const GlobalValue *Old) {
1093 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1094 EES->GlobalAddressReverseMap.erase(OldVal);
1097 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1098 const GlobalValue *,
1099 const GlobalValue *) {
1100 assert(false && "The ExecutionEngine doesn't know how to handle a"
1101 " RAUW on a value it has a global mapping for.");