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"
32 #include "llvm/Target/TargetMachine.h"
37 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38 STATISTIC(NumGlobals , "Number of global vars initialized");
40 ExecutionEngine *(*ExecutionEngine::JITCtor)(
42 std::string *ErrorStr,
43 JITMemoryManager *JMM,
44 CodeGenOpt::Level OptLevel,
46 TargetMachine *TM) = 0;
47 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
49 std::string *ErrorStr,
50 JITMemoryManager *JMM,
51 CodeGenOpt::Level OptLevel,
53 TargetMachine *TM) = 0;
54 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55 std::string *ErrorStr) = 0;
57 ExecutionEngine::ExecutionEngine(Module *M)
59 LazyFunctionCreator(0),
60 ExceptionTableRegister(0),
61 ExceptionTableDeregister(0) {
62 CompilingLazily = false;
63 GVCompilationDisabled = false;
64 SymbolSearchingDisabled = false;
66 assert(M && "Module is null?");
69 ExecutionEngine::~ExecutionEngine() {
70 clearAllGlobalMappings();
71 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
75 void ExecutionEngine::DeregisterAllTables() {
76 if (ExceptionTableDeregister) {
77 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79 for (; it != ite; ++it)
80 ExceptionTableDeregister(it->second);
81 AllExceptionTables.clear();
86 /// \brief Helper class which uses a value handler to automatically deletes the
87 /// memory block when the GlobalVariable is destroyed.
88 class GVMemoryBlock : public CallbackVH {
89 GVMemoryBlock(const GlobalVariable *GV)
90 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
93 /// \brief Returns the address the GlobalVariable should be written into. The
94 /// GVMemoryBlock object prefixes that.
95 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
96 const Type *ElTy = GV->getType()->getElementType();
97 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98 void *RawMemory = ::operator new(
99 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
100 TD.getPreferredAlignment(GV))
102 new(RawMemory) GVMemoryBlock(GV);
103 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
106 virtual void deleted() {
107 // We allocated with operator new and with some extra memory hanging off the
108 // end, so don't just delete this. I'm not sure if this is actually
110 this->~GVMemoryBlock();
111 ::operator delete(this);
114 } // anonymous namespace
116 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117 return GVMemoryBlock::Create(GV, *getTargetData());
120 bool ExecutionEngine::removeModule(Module *M) {
121 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122 E = Modules.end(); I != E; ++I) {
126 clearGlobalMappingsFromModule(M);
133 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135 if (Function *F = Modules[i]->getFunction(FnName))
142 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143 const GlobalValue *ToUnmap) {
144 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
147 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
149 if (I == GlobalAddressMap.end())
153 GlobalAddressMap.erase(I);
156 GlobalAddressReverseMap.erase(OldVal);
160 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161 MutexGuard locked(lock);
163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
164 << "\' to [" << Addr << "]\n";);
165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
169 // If we are using the reverse mapping, add it too.
170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
171 AssertingVH<const GlobalValue> &V =
172 EEState.getGlobalAddressReverseMap(locked)[Addr];
173 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
178 void ExecutionEngine::clearAllGlobalMappings() {
179 MutexGuard locked(lock);
181 EEState.getGlobalAddressMap(locked).clear();
182 EEState.getGlobalAddressReverseMap(locked).clear();
185 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186 MutexGuard locked(lock);
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189 EEState.RemoveMapping(locked, FI);
190 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
192 EEState.RemoveMapping(locked, GI);
195 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
196 MutexGuard locked(lock);
198 ExecutionEngineState::GlobalAddressMapTy &Map =
199 EEState.getGlobalAddressMap(locked);
201 // Deleting from the mapping?
203 return EEState.RemoveMapping(locked, GV);
205 void *&CurVal = Map[GV];
206 void *OldVal = CurVal;
208 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
212 // If we are using the reverse mapping, add it too.
213 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
214 AssertingVH<const GlobalValue> &V =
215 EEState.getGlobalAddressReverseMap(locked)[Addr];
216 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
222 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223 MutexGuard locked(lock);
225 ExecutionEngineState::GlobalAddressMapTy::iterator I =
226 EEState.getGlobalAddressMap(locked).find(GV);
227 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
230 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
231 MutexGuard locked(lock);
233 // If we haven't computed the reverse mapping yet, do so first.
234 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235 for (ExecutionEngineState::GlobalAddressMapTy::iterator
236 I = EEState.getGlobalAddressMap(locked).begin(),
237 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239 I->second, I->first));
242 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243 EEState.getGlobalAddressReverseMap(locked).find(Addr);
244 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
250 std::vector<char*> Values;
252 ArgvArray() : Array(NULL) {}
253 ~ArgvArray() { clear(); }
257 for (size_t I = 0, E = Values.size(); I != E; ++I) {
262 /// Turn a vector of strings into a nice argv style array of pointers to null
263 /// terminated strings.
264 void *reset(LLVMContext &C, ExecutionEngine *EE,
265 const std::vector<std::string> &InputArgv);
267 } // anonymous namespace
268 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv) {
270 clear(); // Free the old contents.
271 unsigned PtrSize = EE->getTargetData()->getPointerSize();
272 Array = new char[(InputArgv.size()+1)*PtrSize];
274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275 const Type *SBytePtr = Type::getInt8PtrTy(C);
277 for (unsigned i = 0; i != InputArgv.size(); ++i) {
278 unsigned Size = InputArgv[i].size()+1;
279 char *Dest = new char[Size];
280 Values.push_back(Dest);
281 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
283 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
286 // Endian safe: Array[i] = (PointerTy)Dest;
287 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
292 EE->StoreValueToMemory(PTOGV(0),
293 (GenericValue*)(Array+InputArgv.size()*PtrSize),
298 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
300 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
301 GlobalVariable *GV = module->getNamedGlobal(Name);
303 // If this global has internal linkage, or if it has a use, then it must be
304 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
305 // this is the case, don't execute any of the global ctors, __main will do
307 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
309 // Should be an array of '{ i32, void ()* }' structs. The first value is
310 // the init priority, which we ignore.
311 if (isa<ConstantAggregateZero>(GV->getInitializer()))
313 ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315 if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
317 ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
319 Constant *FP = CS->getOperand(1);
320 if (FP->isNullValue())
321 continue; // Found a sentinal value, ignore.
323 // Strip off constant expression casts.
324 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
326 FP = CE->getOperand(0);
328 // Execute the ctor/dtor function!
329 if (Function *F = dyn_cast<Function>(FP))
330 runFunction(F, std::vector<GenericValue>());
332 // FIXME: It is marginally lame that we just do nothing here if we see an
333 // entry we don't recognize. It might not be unreasonable for the verifier
334 // to not even allow this and just assert here.
338 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
339 // Execute global ctors/dtors for each module in the program.
340 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
341 runStaticConstructorsDestructors(Modules[i], isDtors);
345 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
346 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
347 unsigned PtrSize = EE->getTargetData()->getPointerSize();
348 for (unsigned i = 0; i < PtrSize; ++i)
349 if (*(i + (uint8_t*)Loc))
355 int ExecutionEngine::runFunctionAsMain(Function *Fn,
356 const std::vector<std::string> &argv,
357 const char * const * envp) {
358 std::vector<GenericValue> GVArgs;
360 GVArgc.IntVal = APInt(32, argv.size());
363 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
364 const FunctionType *FTy = Fn->getFunctionType();
365 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
367 // Check the argument types.
369 report_fatal_error("Invalid number of arguments of main() supplied");
370 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
371 report_fatal_error("Invalid type for third argument of main() supplied");
372 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
373 report_fatal_error("Invalid type for second argument of main() supplied");
374 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
375 report_fatal_error("Invalid type for first argument of main() supplied");
376 if (!FTy->getReturnType()->isIntegerTy() &&
377 !FTy->getReturnType()->isVoidTy())
378 report_fatal_error("Invalid return type of main() supplied");
383 GVArgs.push_back(GVArgc); // Arg #0 = argc.
386 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
387 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
388 "argv[0] was null after CreateArgv");
390 std::vector<std::string> EnvVars;
391 for (unsigned i = 0; envp[i]; ++i)
392 EnvVars.push_back(envp[i]);
394 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
399 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
402 ExecutionEngine *ExecutionEngine::create(Module *M,
403 bool ForceInterpreter,
404 std::string *ErrorStr,
405 CodeGenOpt::Level OptLevel,
407 return EngineBuilder(M)
408 .setEngineKind(ForceInterpreter
409 ? EngineKind::Interpreter
411 .setErrorStr(ErrorStr)
412 .setOptLevel(OptLevel)
413 .setAllocateGVsWithCode(GVsWithCode)
417 ExecutionEngine *EngineBuilder::create() {
418 // Make sure we can resolve symbols in the program as well. The zero arg
419 // to the function tells DynamicLibrary to load the program, not a library.
420 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
423 // If the user specified a memory manager but didn't specify which engine to
424 // create, we assume they only want the JIT, and we fail if they only want
427 if (WhichEngine & EngineKind::JIT)
428 WhichEngine = EngineKind::JIT;
431 *ErrorStr = "Cannot create an interpreter with a memory manager.";
436 // Unless the interpreter was explicitly selected or the JIT is not linked,
438 if (WhichEngine & EngineKind::JIT) {
440 ExecutionEngine::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
441 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
442 TM->setCodeModel(CMModel);
444 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
445 ExecutionEngine *EE =
446 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
447 AllocateGVsWithCode, TM);
449 } else if (ExecutionEngine::JITCtor) {
450 ExecutionEngine *EE =
451 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
452 AllocateGVsWithCode, TM);
457 // If we can't make a JIT and we didn't request one specifically, try making
458 // an interpreter instead.
459 if (WhichEngine & EngineKind::Interpreter) {
460 if (ExecutionEngine::InterpCtor)
461 return ExecutionEngine::InterpCtor(M, ErrorStr);
463 *ErrorStr = "Interpreter has not been linked in.";
467 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
469 *ErrorStr = "JIT has not been linked in.";
475 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
476 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
477 return getPointerToFunction(F);
479 MutexGuard locked(lock);
480 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
483 // Global variable might have been added since interpreter started.
484 if (GlobalVariable *GVar =
485 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
486 EmitGlobalVariable(GVar);
488 llvm_unreachable("Global hasn't had an address allocated yet!");
490 return EEState.getGlobalAddressMap(locked)[GV];
493 /// \brief Converts a Constant* into a GenericValue, including handling of
494 /// ConstantExpr values.
495 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
496 // If its undefined, return the garbage.
497 if (isa<UndefValue>(C)) {
499 switch (C->getType()->getTypeID()) {
500 case Type::IntegerTyID:
501 case Type::X86_FP80TyID:
502 case Type::FP128TyID:
503 case Type::PPC_FP128TyID:
504 // Although the value is undefined, we still have to construct an APInt
505 // with the correct bit width.
506 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
514 // Otherwise, if the value is a ConstantExpr...
515 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
516 Constant *Op0 = CE->getOperand(0);
517 switch (CE->getOpcode()) {
518 case Instruction::GetElementPtr: {
520 GenericValue Result = getConstantValue(Op0);
521 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
523 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
525 char* tmp = (char*) Result.PointerVal;
526 Result = PTOGV(tmp + Offset);
529 case Instruction::Trunc: {
530 GenericValue GV = getConstantValue(Op0);
531 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
532 GV.IntVal = GV.IntVal.trunc(BitWidth);
535 case Instruction::ZExt: {
536 GenericValue GV = getConstantValue(Op0);
537 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
538 GV.IntVal = GV.IntVal.zext(BitWidth);
541 case Instruction::SExt: {
542 GenericValue GV = getConstantValue(Op0);
543 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
544 GV.IntVal = GV.IntVal.sext(BitWidth);
547 case Instruction::FPTrunc: {
549 GenericValue GV = getConstantValue(Op0);
550 GV.FloatVal = float(GV.DoubleVal);
553 case Instruction::FPExt:{
555 GenericValue GV = getConstantValue(Op0);
556 GV.DoubleVal = double(GV.FloatVal);
559 case Instruction::UIToFP: {
560 GenericValue GV = getConstantValue(Op0);
561 if (CE->getType()->isFloatTy())
562 GV.FloatVal = float(GV.IntVal.roundToDouble());
563 else if (CE->getType()->isDoubleTy())
564 GV.DoubleVal = GV.IntVal.roundToDouble();
565 else if (CE->getType()->isX86_FP80Ty()) {
566 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
567 (void)apf.convertFromAPInt(GV.IntVal,
569 APFloat::rmNearestTiesToEven);
570 GV.IntVal = apf.bitcastToAPInt();
574 case Instruction::SIToFP: {
575 GenericValue GV = getConstantValue(Op0);
576 if (CE->getType()->isFloatTy())
577 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
578 else if (CE->getType()->isDoubleTy())
579 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
580 else if (CE->getType()->isX86_FP80Ty()) {
581 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
582 (void)apf.convertFromAPInt(GV.IntVal,
584 APFloat::rmNearestTiesToEven);
585 GV.IntVal = apf.bitcastToAPInt();
589 case Instruction::FPToUI: // double->APInt conversion handles sign
590 case Instruction::FPToSI: {
591 GenericValue GV = getConstantValue(Op0);
592 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
593 if (Op0->getType()->isFloatTy())
594 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
595 else if (Op0->getType()->isDoubleTy())
596 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
597 else if (Op0->getType()->isX86_FP80Ty()) {
598 APFloat apf = APFloat(GV.IntVal);
601 (void)apf.convertToInteger(&v, BitWidth,
602 CE->getOpcode()==Instruction::FPToSI,
603 APFloat::rmTowardZero, &ignored);
604 GV.IntVal = v; // endian?
608 case Instruction::PtrToInt: {
609 GenericValue GV = getConstantValue(Op0);
610 uint32_t PtrWidth = TD->getPointerSizeInBits();
611 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
614 case Instruction::IntToPtr: {
615 GenericValue GV = getConstantValue(Op0);
616 uint32_t PtrWidth = TD->getPointerSizeInBits();
617 if (PtrWidth != GV.IntVal.getBitWidth())
618 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
619 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
620 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
623 case Instruction::BitCast: {
624 GenericValue GV = getConstantValue(Op0);
625 const Type* DestTy = CE->getType();
626 switch (Op0->getType()->getTypeID()) {
627 default: llvm_unreachable("Invalid bitcast operand");
628 case Type::IntegerTyID:
629 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
630 if (DestTy->isFloatTy())
631 GV.FloatVal = GV.IntVal.bitsToFloat();
632 else if (DestTy->isDoubleTy())
633 GV.DoubleVal = GV.IntVal.bitsToDouble();
635 case Type::FloatTyID:
636 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
637 GV.IntVal = APInt::floatToBits(GV.FloatVal);
639 case Type::DoubleTyID:
640 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
641 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
643 case Type::PointerTyID:
644 assert(DestTy->isPointerTy() && "Invalid bitcast");
645 break; // getConstantValue(Op0) above already converted it
649 case Instruction::Add:
650 case Instruction::FAdd:
651 case Instruction::Sub:
652 case Instruction::FSub:
653 case Instruction::Mul:
654 case Instruction::FMul:
655 case Instruction::UDiv:
656 case Instruction::SDiv:
657 case Instruction::URem:
658 case Instruction::SRem:
659 case Instruction::And:
660 case Instruction::Or:
661 case Instruction::Xor: {
662 GenericValue LHS = getConstantValue(Op0);
663 GenericValue RHS = getConstantValue(CE->getOperand(1));
665 switch (CE->getOperand(0)->getType()->getTypeID()) {
666 default: llvm_unreachable("Bad add type!");
667 case Type::IntegerTyID:
668 switch (CE->getOpcode()) {
669 default: llvm_unreachable("Invalid integer opcode");
670 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
671 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
672 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
673 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
674 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
675 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
676 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
677 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
678 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
679 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
682 case Type::FloatTyID:
683 switch (CE->getOpcode()) {
684 default: llvm_unreachable("Invalid float opcode");
685 case Instruction::FAdd:
686 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
687 case Instruction::FSub:
688 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
689 case Instruction::FMul:
690 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
691 case Instruction::FDiv:
692 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
693 case Instruction::FRem:
694 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
697 case Type::DoubleTyID:
698 switch (CE->getOpcode()) {
699 default: llvm_unreachable("Invalid double opcode");
700 case Instruction::FAdd:
701 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
702 case Instruction::FSub:
703 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
704 case Instruction::FMul:
705 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
706 case Instruction::FDiv:
707 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
708 case Instruction::FRem:
709 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
712 case Type::X86_FP80TyID:
713 case Type::PPC_FP128TyID:
714 case Type::FP128TyID: {
715 APFloat apfLHS = APFloat(LHS.IntVal);
716 switch (CE->getOpcode()) {
717 default: llvm_unreachable("Invalid long double opcode");
718 case Instruction::FAdd:
719 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
720 GV.IntVal = apfLHS.bitcastToAPInt();
722 case Instruction::FSub:
723 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
724 GV.IntVal = apfLHS.bitcastToAPInt();
726 case Instruction::FMul:
727 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
728 GV.IntVal = apfLHS.bitcastToAPInt();
730 case Instruction::FDiv:
731 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
732 GV.IntVal = apfLHS.bitcastToAPInt();
734 case Instruction::FRem:
735 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
736 GV.IntVal = apfLHS.bitcastToAPInt();
748 SmallString<256> Msg;
749 raw_svector_ostream OS(Msg);
750 OS << "ConstantExpr not handled: " << *CE;
751 report_fatal_error(OS.str());
754 // Otherwise, we have a simple constant.
756 switch (C->getType()->getTypeID()) {
757 case Type::FloatTyID:
758 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
760 case Type::DoubleTyID:
761 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
763 case Type::X86_FP80TyID:
764 case Type::FP128TyID:
765 case Type::PPC_FP128TyID:
766 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
768 case Type::IntegerTyID:
769 Result.IntVal = cast<ConstantInt>(C)->getValue();
771 case Type::PointerTyID:
772 if (isa<ConstantPointerNull>(C))
773 Result.PointerVal = 0;
774 else if (const Function *F = dyn_cast<Function>(C))
775 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
776 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
777 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
778 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
779 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
780 BA->getBasicBlock())));
782 llvm_unreachable("Unknown constant pointer type!");
785 SmallString<256> Msg;
786 raw_svector_ostream OS(Msg);
787 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
788 report_fatal_error(OS.str());
794 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
795 /// with the integer held in IntVal.
796 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
797 unsigned StoreBytes) {
798 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
799 uint8_t *Src = (uint8_t *)IntVal.getRawData();
801 if (sys::isLittleEndianHost()) {
802 // Little-endian host - the source is ordered from LSB to MSB. Order the
803 // destination from LSB to MSB: Do a straight copy.
804 memcpy(Dst, Src, StoreBytes);
806 // Big-endian host - the source is an array of 64 bit words ordered from
807 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
808 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
809 while (StoreBytes > sizeof(uint64_t)) {
810 StoreBytes -= sizeof(uint64_t);
811 // May not be aligned so use memcpy.
812 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
813 Src += sizeof(uint64_t);
816 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
820 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
821 GenericValue *Ptr, const Type *Ty) {
822 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
824 switch (Ty->getTypeID()) {
825 case Type::IntegerTyID:
826 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
828 case Type::FloatTyID:
829 *((float*)Ptr) = Val.FloatVal;
831 case Type::DoubleTyID:
832 *((double*)Ptr) = Val.DoubleVal;
834 case Type::X86_FP80TyID:
835 memcpy(Ptr, Val.IntVal.getRawData(), 10);
837 case Type::PointerTyID:
838 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
839 if (StoreBytes != sizeof(PointerTy))
840 memset(&(Ptr->PointerVal), 0, StoreBytes);
842 *((PointerTy*)Ptr) = Val.PointerVal;
845 dbgs() << "Cannot store value of type " << *Ty << "!\n";
848 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
849 // Host and target are different endian - reverse the stored bytes.
850 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
853 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
854 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
855 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
856 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
857 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
859 if (sys::isLittleEndianHost())
860 // Little-endian host - the destination must be ordered from LSB to MSB.
861 // The source is ordered from LSB to MSB: Do a straight copy.
862 memcpy(Dst, Src, LoadBytes);
864 // Big-endian - the destination is an array of 64 bit words ordered from
865 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
866 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
868 while (LoadBytes > sizeof(uint64_t)) {
869 LoadBytes -= sizeof(uint64_t);
870 // May not be aligned so use memcpy.
871 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
872 Dst += sizeof(uint64_t);
875 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
881 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
884 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
886 switch (Ty->getTypeID()) {
887 case Type::IntegerTyID:
888 // An APInt with all words initially zero.
889 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
890 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
892 case Type::FloatTyID:
893 Result.FloatVal = *((float*)Ptr);
895 case Type::DoubleTyID:
896 Result.DoubleVal = *((double*)Ptr);
898 case Type::PointerTyID:
899 Result.PointerVal = *((PointerTy*)Ptr);
901 case Type::X86_FP80TyID: {
902 // This is endian dependent, but it will only work on x86 anyway.
903 // FIXME: Will not trap if loading a signaling NaN.
906 Result.IntVal = APInt(80, 2, y);
910 SmallString<256> Msg;
911 raw_svector_ostream OS(Msg);
912 OS << "Cannot load value of type " << *Ty << "!";
913 report_fatal_error(OS.str());
917 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
918 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
920 if (isa<UndefValue>(Init)) {
922 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
923 unsigned ElementSize =
924 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
925 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
926 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
928 } else if (isa<ConstantAggregateZero>(Init)) {
929 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
931 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
932 unsigned ElementSize =
933 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
934 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
935 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
937 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
938 const StructLayout *SL =
939 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
940 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
941 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
943 } else if (Init->getType()->isFirstClassType()) {
944 GenericValue Val = getConstantValue(Init);
945 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
949 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
950 llvm_unreachable("Unknown constant type to initialize memory with!");
953 /// EmitGlobals - Emit all of the global variables to memory, storing their
954 /// addresses into GlobalAddress. This must make sure to copy the contents of
955 /// their initializers into the memory.
956 void ExecutionEngine::emitGlobals() {
957 // Loop over all of the global variables in the program, allocating the memory
958 // to hold them. If there is more than one module, do a prepass over globals
959 // to figure out how the different modules should link together.
960 std::map<std::pair<std::string, const Type*>,
961 const GlobalValue*> LinkedGlobalsMap;
963 if (Modules.size() != 1) {
964 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
965 Module &M = *Modules[m];
966 for (Module::const_global_iterator I = M.global_begin(),
967 E = M.global_end(); I != E; ++I) {
968 const GlobalValue *GV = I;
969 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
970 GV->hasAppendingLinkage() || !GV->hasName())
971 continue;// Ignore external globals and globals with internal linkage.
973 const GlobalValue *&GVEntry =
974 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
976 // If this is the first time we've seen this global, it is the canonical
983 // If the existing global is strong, never replace it.
984 if (GVEntry->hasExternalLinkage() ||
985 GVEntry->hasDLLImportLinkage() ||
986 GVEntry->hasDLLExportLinkage())
989 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
990 // symbol. FIXME is this right for common?
991 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
997 std::vector<const GlobalValue*> NonCanonicalGlobals;
998 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
999 Module &M = *Modules[m];
1000 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1002 // In the multi-module case, see what this global maps to.
1003 if (!LinkedGlobalsMap.empty()) {
1004 if (const GlobalValue *GVEntry =
1005 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1006 // If something else is the canonical global, ignore this one.
1007 if (GVEntry != &*I) {
1008 NonCanonicalGlobals.push_back(I);
1014 if (!I->isDeclaration()) {
1015 addGlobalMapping(I, getMemoryForGV(I));
1017 // External variable reference. Try to use the dynamic loader to
1018 // get a pointer to it.
1020 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1021 addGlobalMapping(I, SymAddr);
1023 report_fatal_error("Could not resolve external global address: "
1029 // If there are multiple modules, map the non-canonical globals to their
1030 // canonical location.
1031 if (!NonCanonicalGlobals.empty()) {
1032 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1033 const GlobalValue *GV = NonCanonicalGlobals[i];
1034 const GlobalValue *CGV =
1035 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1036 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1037 assert(Ptr && "Canonical global wasn't codegen'd!");
1038 addGlobalMapping(GV, Ptr);
1042 // Now that all of the globals are set up in memory, loop through them all
1043 // and initialize their contents.
1044 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1046 if (!I->isDeclaration()) {
1047 if (!LinkedGlobalsMap.empty()) {
1048 if (const GlobalValue *GVEntry =
1049 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1050 if (GVEntry != &*I) // Not the canonical variable.
1053 EmitGlobalVariable(I);
1059 // EmitGlobalVariable - This method emits the specified global variable to the
1060 // address specified in GlobalAddresses, or allocates new memory if it's not
1061 // already in the map.
1062 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1063 void *GA = getPointerToGlobalIfAvailable(GV);
1066 // If it's not already specified, allocate memory for the global.
1067 GA = getMemoryForGV(GV);
1068 addGlobalMapping(GV, GA);
1071 // Don't initialize if it's thread local, let the client do it.
1072 if (!GV->isThreadLocal())
1073 InitializeMemory(GV->getInitializer(), GA);
1075 const Type *ElTy = GV->getType()->getElementType();
1076 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1077 NumInitBytes += (unsigned)GVSize;
1081 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1082 : EE(EE), GlobalAddressMap(this) {
1086 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1087 return &EES->EE.lock;
1090 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1091 const GlobalValue *Old) {
1092 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1093 EES->GlobalAddressReverseMap.erase(OldVal);
1096 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1097 const GlobalValue *,
1098 const GlobalValue *) {
1099 assert(false && "The ExecutionEngine doesn't know how to handle a"
1100 " RAUW on a value it has a global mapping for.");