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 const uint64_t zero[] = {0, 0};
568 APFloat apf = APFloat(APInt(80, 2, zero));
569 (void)apf.convertFromAPInt(GV.IntVal,
571 APFloat::rmNearestTiesToEven);
572 GV.IntVal = apf.bitcastToAPInt();
576 case Instruction::SIToFP: {
577 GenericValue GV = getConstantValue(Op0);
578 if (CE->getType()->isFloatTy())
579 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
580 else if (CE->getType()->isDoubleTy())
581 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
582 else if (CE->getType()->isX86_FP80Ty()) {
583 const uint64_t zero[] = { 0, 0};
584 APFloat apf = APFloat(APInt(80, 2, zero));
585 (void)apf.convertFromAPInt(GV.IntVal,
587 APFloat::rmNearestTiesToEven);
588 GV.IntVal = apf.bitcastToAPInt();
592 case Instruction::FPToUI: // double->APInt conversion handles sign
593 case Instruction::FPToSI: {
594 GenericValue GV = getConstantValue(Op0);
595 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
596 if (Op0->getType()->isFloatTy())
597 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
598 else if (Op0->getType()->isDoubleTy())
599 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
600 else if (Op0->getType()->isX86_FP80Ty()) {
601 APFloat apf = APFloat(GV.IntVal);
604 (void)apf.convertToInteger(&v, BitWidth,
605 CE->getOpcode()==Instruction::FPToSI,
606 APFloat::rmTowardZero, &ignored);
607 GV.IntVal = v; // endian?
611 case Instruction::PtrToInt: {
612 GenericValue GV = getConstantValue(Op0);
613 uint32_t PtrWidth = TD->getPointerSizeInBits();
614 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
617 case Instruction::IntToPtr: {
618 GenericValue GV = getConstantValue(Op0);
619 uint32_t PtrWidth = TD->getPointerSizeInBits();
620 if (PtrWidth != GV.IntVal.getBitWidth())
621 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
622 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
623 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
626 case Instruction::BitCast: {
627 GenericValue GV = getConstantValue(Op0);
628 const Type* DestTy = CE->getType();
629 switch (Op0->getType()->getTypeID()) {
630 default: llvm_unreachable("Invalid bitcast operand");
631 case Type::IntegerTyID:
632 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
633 if (DestTy->isFloatTy())
634 GV.FloatVal = GV.IntVal.bitsToFloat();
635 else if (DestTy->isDoubleTy())
636 GV.DoubleVal = GV.IntVal.bitsToDouble();
638 case Type::FloatTyID:
639 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
640 GV.IntVal = APInt::floatToBits(GV.FloatVal);
642 case Type::DoubleTyID:
643 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
644 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
646 case Type::PointerTyID:
647 assert(DestTy->isPointerTy() && "Invalid bitcast");
648 break; // getConstantValue(Op0) above already converted it
652 case Instruction::Add:
653 case Instruction::FAdd:
654 case Instruction::Sub:
655 case Instruction::FSub:
656 case Instruction::Mul:
657 case Instruction::FMul:
658 case Instruction::UDiv:
659 case Instruction::SDiv:
660 case Instruction::URem:
661 case Instruction::SRem:
662 case Instruction::And:
663 case Instruction::Or:
664 case Instruction::Xor: {
665 GenericValue LHS = getConstantValue(Op0);
666 GenericValue RHS = getConstantValue(CE->getOperand(1));
668 switch (CE->getOperand(0)->getType()->getTypeID()) {
669 default: llvm_unreachable("Bad add type!");
670 case Type::IntegerTyID:
671 switch (CE->getOpcode()) {
672 default: llvm_unreachable("Invalid integer opcode");
673 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
674 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
675 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
676 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
677 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
678 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
679 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
680 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
681 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
682 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
685 case Type::FloatTyID:
686 switch (CE->getOpcode()) {
687 default: llvm_unreachable("Invalid float opcode");
688 case Instruction::FAdd:
689 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
690 case Instruction::FSub:
691 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
692 case Instruction::FMul:
693 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
694 case Instruction::FDiv:
695 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
696 case Instruction::FRem:
697 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
700 case Type::DoubleTyID:
701 switch (CE->getOpcode()) {
702 default: llvm_unreachable("Invalid double opcode");
703 case Instruction::FAdd:
704 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
705 case Instruction::FSub:
706 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
707 case Instruction::FMul:
708 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
709 case Instruction::FDiv:
710 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
711 case Instruction::FRem:
712 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
715 case Type::X86_FP80TyID:
716 case Type::PPC_FP128TyID:
717 case Type::FP128TyID: {
718 APFloat apfLHS = APFloat(LHS.IntVal);
719 switch (CE->getOpcode()) {
720 default: llvm_unreachable("Invalid long double opcode");
721 case Instruction::FAdd:
722 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
723 GV.IntVal = apfLHS.bitcastToAPInt();
725 case Instruction::FSub:
726 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
727 GV.IntVal = apfLHS.bitcastToAPInt();
729 case Instruction::FMul:
730 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
731 GV.IntVal = apfLHS.bitcastToAPInt();
733 case Instruction::FDiv:
734 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
735 GV.IntVal = apfLHS.bitcastToAPInt();
737 case Instruction::FRem:
738 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
739 GV.IntVal = apfLHS.bitcastToAPInt();
751 SmallString<256> Msg;
752 raw_svector_ostream OS(Msg);
753 OS << "ConstantExpr not handled: " << *CE;
754 report_fatal_error(OS.str());
757 // Otherwise, we have a simple constant.
759 switch (C->getType()->getTypeID()) {
760 case Type::FloatTyID:
761 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
763 case Type::DoubleTyID:
764 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
766 case Type::X86_FP80TyID:
767 case Type::FP128TyID:
768 case Type::PPC_FP128TyID:
769 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
771 case Type::IntegerTyID:
772 Result.IntVal = cast<ConstantInt>(C)->getValue();
774 case Type::PointerTyID:
775 if (isa<ConstantPointerNull>(C))
776 Result.PointerVal = 0;
777 else if (const Function *F = dyn_cast<Function>(C))
778 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
779 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
780 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
781 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
782 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
783 BA->getBasicBlock())));
785 llvm_unreachable("Unknown constant pointer type!");
788 SmallString<256> Msg;
789 raw_svector_ostream OS(Msg);
790 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
791 report_fatal_error(OS.str());
797 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
798 /// with the integer held in IntVal.
799 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
800 unsigned StoreBytes) {
801 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
802 uint8_t *Src = (uint8_t *)IntVal.getRawData();
804 if (sys::isLittleEndianHost()) {
805 // Little-endian host - the source is ordered from LSB to MSB. Order the
806 // destination from LSB to MSB: Do a straight copy.
807 memcpy(Dst, Src, StoreBytes);
809 // Big-endian host - the source is an array of 64 bit words ordered from
810 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
811 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
812 while (StoreBytes > sizeof(uint64_t)) {
813 StoreBytes -= sizeof(uint64_t);
814 // May not be aligned so use memcpy.
815 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
816 Src += sizeof(uint64_t);
819 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
823 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
824 GenericValue *Ptr, const Type *Ty) {
825 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
827 switch (Ty->getTypeID()) {
828 case Type::IntegerTyID:
829 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
831 case Type::FloatTyID:
832 *((float*)Ptr) = Val.FloatVal;
834 case Type::DoubleTyID:
835 *((double*)Ptr) = Val.DoubleVal;
837 case Type::X86_FP80TyID:
838 memcpy(Ptr, Val.IntVal.getRawData(), 10);
840 case Type::PointerTyID:
841 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
842 if (StoreBytes != sizeof(PointerTy))
843 memset(Ptr, 0, StoreBytes);
845 *((PointerTy*)Ptr) = Val.PointerVal;
848 dbgs() << "Cannot store value of type " << *Ty << "!\n";
851 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
852 // Host and target are different endian - reverse the stored bytes.
853 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
856 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
857 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
858 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
859 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
860 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
862 if (sys::isLittleEndianHost())
863 // Little-endian host - the destination must be ordered from LSB to MSB.
864 // The source is ordered from LSB to MSB: Do a straight copy.
865 memcpy(Dst, Src, LoadBytes);
867 // Big-endian - the destination is an array of 64 bit words ordered from
868 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
869 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
871 while (LoadBytes > sizeof(uint64_t)) {
872 LoadBytes -= sizeof(uint64_t);
873 // May not be aligned so use memcpy.
874 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
875 Dst += sizeof(uint64_t);
878 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
884 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
887 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
889 switch (Ty->getTypeID()) {
890 case Type::IntegerTyID:
891 // An APInt with all words initially zero.
892 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
893 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
895 case Type::FloatTyID:
896 Result.FloatVal = *((float*)Ptr);
898 case Type::DoubleTyID:
899 Result.DoubleVal = *((double*)Ptr);
901 case Type::PointerTyID:
902 Result.PointerVal = *((PointerTy*)Ptr);
904 case Type::X86_FP80TyID: {
905 // This is endian dependent, but it will only work on x86 anyway.
906 // FIXME: Will not trap if loading a signaling NaN.
909 Result.IntVal = APInt(80, 2, y);
913 SmallString<256> Msg;
914 raw_svector_ostream OS(Msg);
915 OS << "Cannot load value of type " << *Ty << "!";
916 report_fatal_error(OS.str());
920 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
921 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
923 if (isa<UndefValue>(Init)) {
925 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
926 unsigned ElementSize =
927 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
928 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
929 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
931 } else if (isa<ConstantAggregateZero>(Init)) {
932 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
934 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
935 unsigned ElementSize =
936 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
937 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
938 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
940 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
941 const StructLayout *SL =
942 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
943 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
944 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
946 } else if (Init->getType()->isFirstClassType()) {
947 GenericValue Val = getConstantValue(Init);
948 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
952 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
953 llvm_unreachable("Unknown constant type to initialize memory with!");
956 /// EmitGlobals - Emit all of the global variables to memory, storing their
957 /// addresses into GlobalAddress. This must make sure to copy the contents of
958 /// their initializers into the memory.
959 void ExecutionEngine::emitGlobals() {
960 // Loop over all of the global variables in the program, allocating the memory
961 // to hold them. If there is more than one module, do a prepass over globals
962 // to figure out how the different modules should link together.
963 std::map<std::pair<std::string, const Type*>,
964 const GlobalValue*> LinkedGlobalsMap;
966 if (Modules.size() != 1) {
967 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
968 Module &M = *Modules[m];
969 for (Module::const_global_iterator I = M.global_begin(),
970 E = M.global_end(); I != E; ++I) {
971 const GlobalValue *GV = I;
972 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
973 GV->hasAppendingLinkage() || !GV->hasName())
974 continue;// Ignore external globals and globals with internal linkage.
976 const GlobalValue *&GVEntry =
977 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
979 // If this is the first time we've seen this global, it is the canonical
986 // If the existing global is strong, never replace it.
987 if (GVEntry->hasExternalLinkage() ||
988 GVEntry->hasDLLImportLinkage() ||
989 GVEntry->hasDLLExportLinkage())
992 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
993 // symbol. FIXME is this right for common?
994 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1000 std::vector<const GlobalValue*> NonCanonicalGlobals;
1001 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1002 Module &M = *Modules[m];
1003 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1005 // In the multi-module case, see what this global maps to.
1006 if (!LinkedGlobalsMap.empty()) {
1007 if (const GlobalValue *GVEntry =
1008 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1009 // If something else is the canonical global, ignore this one.
1010 if (GVEntry != &*I) {
1011 NonCanonicalGlobals.push_back(I);
1017 if (!I->isDeclaration()) {
1018 addGlobalMapping(I, getMemoryForGV(I));
1020 // External variable reference. Try to use the dynamic loader to
1021 // get a pointer to it.
1023 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1024 addGlobalMapping(I, SymAddr);
1026 report_fatal_error("Could not resolve external global address: "
1032 // If there are multiple modules, map the non-canonical globals to their
1033 // canonical location.
1034 if (!NonCanonicalGlobals.empty()) {
1035 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1036 const GlobalValue *GV = NonCanonicalGlobals[i];
1037 const GlobalValue *CGV =
1038 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1039 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1040 assert(Ptr && "Canonical global wasn't codegen'd!");
1041 addGlobalMapping(GV, Ptr);
1045 // Now that all of the globals are set up in memory, loop through them all
1046 // and initialize their contents.
1047 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1049 if (!I->isDeclaration()) {
1050 if (!LinkedGlobalsMap.empty()) {
1051 if (const GlobalValue *GVEntry =
1052 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1053 if (GVEntry != &*I) // Not the canonical variable.
1056 EmitGlobalVariable(I);
1062 // EmitGlobalVariable - This method emits the specified global variable to the
1063 // address specified in GlobalAddresses, or allocates new memory if it's not
1064 // already in the map.
1065 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1066 void *GA = getPointerToGlobalIfAvailable(GV);
1069 // If it's not already specified, allocate memory for the global.
1070 GA = getMemoryForGV(GV);
1071 addGlobalMapping(GV, GA);
1074 // Don't initialize if it's thread local, let the client do it.
1075 if (!GV->isThreadLocal())
1076 InitializeMemory(GV->getInitializer(), GA);
1078 const Type *ElTy = GV->getType()->getElementType();
1079 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1080 NumInitBytes += (unsigned)GVSize;
1084 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1085 : EE(EE), GlobalAddressMap(this) {
1089 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1090 return &EES->EE.lock;
1093 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1094 const GlobalValue *Old) {
1095 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1096 EES->GlobalAddressReverseMap.erase(OldVal);
1099 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1100 const GlobalValue *,
1101 const GlobalValue *) {
1102 assert(false && "The ExecutionEngine doesn't know how to handle a"
1103 " RAUW on a value it has a global mapping for.");