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/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MutexGuard.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/DataLayout.h"
34 #include "llvm/Target/TargetMachine.h"
39 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
40 STATISTIC(NumGlobals , "Number of global vars initialized");
42 ExecutionEngine *(*ExecutionEngine::JITCtor)(
44 std::string *ErrorStr,
45 JITMemoryManager *JMM,
47 TargetMachine *TM) = 0;
48 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 std::string *ErrorStr,
51 JITMemoryManager *JMM,
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 DataLayout& TD) {
96 Type *ElTy = GV->getType()->getElementType();
97 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98 void *RawMemory = ::operator new(
99 DataLayout::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, *getDataLayout());
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->getDataLayout()->getPointerSize(0);
272 Array = new char[(InputArgv.size()+1)*PtrSize];
274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275 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 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
316 if (CS == 0) continue;
318 Constant *FP = CS->getOperand(1);
319 if (FP->isNullValue())
320 continue; // Found a sentinal value, ignore.
322 // Strip off constant expression casts.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325 FP = CE->getOperand(0);
327 // Execute the ctor/dtor function!
328 if (Function *F = dyn_cast<Function>(FP))
329 runFunction(F, std::vector<GenericValue>());
331 // FIXME: It is marginally lame that we just do nothing here if we see an
332 // entry we don't recognize. It might not be unreasonable for the verifier
333 // to not even allow this and just assert here.
337 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
338 // Execute global ctors/dtors for each module in the program.
339 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
340 runStaticConstructorsDestructors(Modules[i], isDtors);
344 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
345 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
346 unsigned PtrSize = EE->getDataLayout()->getPointerSize(0);
347 for (unsigned i = 0; i < PtrSize; ++i)
348 if (*(i + (uint8_t*)Loc))
354 int ExecutionEngine::runFunctionAsMain(Function *Fn,
355 const std::vector<std::string> &argv,
356 const char * const * envp) {
357 std::vector<GenericValue> GVArgs;
359 GVArgc.IntVal = APInt(32, argv.size());
362 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
363 FunctionType *FTy = Fn->getFunctionType();
364 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366 // Check the argument types.
368 report_fatal_error("Invalid number of arguments of main() supplied");
369 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
370 report_fatal_error("Invalid type for third argument of main() supplied");
371 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
372 report_fatal_error("Invalid type for second argument of main() supplied");
373 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
374 report_fatal_error("Invalid type for first argument of main() supplied");
375 if (!FTy->getReturnType()->isIntegerTy() &&
376 !FTy->getReturnType()->isVoidTy())
377 report_fatal_error("Invalid return type of main() supplied");
382 GVArgs.push_back(GVArgc); // Arg #0 = argc.
385 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
386 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
387 "argv[0] was null after CreateArgv");
389 std::vector<std::string> EnvVars;
390 for (unsigned i = 0; envp[i]; ++i)
391 EnvVars.push_back(envp[i]);
393 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
398 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
401 ExecutionEngine *ExecutionEngine::create(Module *M,
402 bool ForceInterpreter,
403 std::string *ErrorStr,
404 CodeGenOpt::Level OptLevel,
406 EngineBuilder EB = EngineBuilder(M)
407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode);
417 /// createJIT - This is the factory method for creating a JIT for the current
418 /// machine, it does not fall back to the interpreter. This takes ownership
420 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421 std::string *ErrorStr,
422 JITMemoryManager *JMM,
423 CodeGenOpt::Level OL,
426 CodeModel::Model CMM) {
427 if (ExecutionEngine::JITCtor == 0) {
429 *ErrorStr = "JIT has not been linked in.";
433 // Use the defaults for extra parameters. Users can use EngineBuilder to
436 EB.setEngineKind(EngineKind::JIT);
437 EB.setErrorStr(ErrorStr);
438 EB.setRelocationModel(RM);
439 EB.setCodeModel(CMM);
440 EB.setAllocateGVsWithCode(GVsWithCode);
442 EB.setJITMemoryManager(JMM);
444 // TODO: permit custom TargetOptions here
445 TargetMachine *TM = EB.selectTarget();
446 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
448 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
451 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
452 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
454 // Make sure we can resolve symbols in the program as well. The zero arg
455 // to the function tells DynamicLibrary to load the program, not a library.
456 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
459 // If the user specified a memory manager but didn't specify which engine to
460 // create, we assume they only want the JIT, and we fail if they only want
463 if (WhichEngine & EngineKind::JIT)
464 WhichEngine = EngineKind::JIT;
467 *ErrorStr = "Cannot create an interpreter with a memory manager.";
472 // Unless the interpreter was explicitly selected or the JIT is not linked,
474 if ((WhichEngine & EngineKind::JIT) && TheTM) {
475 Triple TT(M->getTargetTriple());
476 if (!TM->getTarget().hasJIT()) {
477 errs() << "WARNING: This target JIT is not designed for the host"
478 << " you are running. If bad things happen, please choose"
479 << " a different -march switch.\n";
482 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
483 ExecutionEngine *EE =
484 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
485 AllocateGVsWithCode, TheTM.take());
487 } else if (ExecutionEngine::JITCtor) {
488 ExecutionEngine *EE =
489 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
490 AllocateGVsWithCode, TheTM.take());
495 // If we can't make a JIT and we didn't request one specifically, try making
496 // an interpreter instead.
497 if (WhichEngine & EngineKind::Interpreter) {
498 if (ExecutionEngine::InterpCtor)
499 return ExecutionEngine::InterpCtor(M, ErrorStr);
501 *ErrorStr = "Interpreter has not been linked in.";
505 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
506 ExecutionEngine::MCJITCtor == 0) {
508 *ErrorStr = "JIT has not been linked in.";
514 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
515 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
516 return getPointerToFunction(F);
518 MutexGuard locked(lock);
519 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
522 // Global variable might have been added since interpreter started.
523 if (GlobalVariable *GVar =
524 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
525 EmitGlobalVariable(GVar);
527 llvm_unreachable("Global hasn't had an address allocated yet!");
529 return EEState.getGlobalAddressMap(locked)[GV];
532 /// \brief Converts a Constant* into a GenericValue, including handling of
533 /// ConstantExpr values.
534 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
535 // If its undefined, return the garbage.
536 if (isa<UndefValue>(C)) {
538 switch (C->getType()->getTypeID()) {
539 case Type::IntegerTyID:
540 case Type::X86_FP80TyID:
541 case Type::FP128TyID:
542 case Type::PPC_FP128TyID:
543 // Although the value is undefined, we still have to construct an APInt
544 // with the correct bit width.
545 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
553 // Otherwise, if the value is a ConstantExpr...
554 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555 Constant *Op0 = CE->getOperand(0);
556 switch (CE->getOpcode()) {
557 case Instruction::GetElementPtr: {
559 GenericValue Result = getConstantValue(Op0);
560 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
561 uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
563 char* tmp = (char*) Result.PointerVal;
564 Result = PTOGV(tmp + Offset);
567 case Instruction::Trunc: {
568 GenericValue GV = getConstantValue(Op0);
569 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
570 GV.IntVal = GV.IntVal.trunc(BitWidth);
573 case Instruction::ZExt: {
574 GenericValue GV = getConstantValue(Op0);
575 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
576 GV.IntVal = GV.IntVal.zext(BitWidth);
579 case Instruction::SExt: {
580 GenericValue GV = getConstantValue(Op0);
581 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
582 GV.IntVal = GV.IntVal.sext(BitWidth);
585 case Instruction::FPTrunc: {
587 GenericValue GV = getConstantValue(Op0);
588 GV.FloatVal = float(GV.DoubleVal);
591 case Instruction::FPExt:{
593 GenericValue GV = getConstantValue(Op0);
594 GV.DoubleVal = double(GV.FloatVal);
597 case Instruction::UIToFP: {
598 GenericValue GV = getConstantValue(Op0);
599 if (CE->getType()->isFloatTy())
600 GV.FloatVal = float(GV.IntVal.roundToDouble());
601 else if (CE->getType()->isDoubleTy())
602 GV.DoubleVal = GV.IntVal.roundToDouble();
603 else if (CE->getType()->isX86_FP80Ty()) {
604 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
605 (void)apf.convertFromAPInt(GV.IntVal,
607 APFloat::rmNearestTiesToEven);
608 GV.IntVal = apf.bitcastToAPInt();
612 case Instruction::SIToFP: {
613 GenericValue GV = getConstantValue(Op0);
614 if (CE->getType()->isFloatTy())
615 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
616 else if (CE->getType()->isDoubleTy())
617 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
618 else if (CE->getType()->isX86_FP80Ty()) {
619 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
620 (void)apf.convertFromAPInt(GV.IntVal,
622 APFloat::rmNearestTiesToEven);
623 GV.IntVal = apf.bitcastToAPInt();
627 case Instruction::FPToUI: // double->APInt conversion handles sign
628 case Instruction::FPToSI: {
629 GenericValue GV = getConstantValue(Op0);
630 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
631 if (Op0->getType()->isFloatTy())
632 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
633 else if (Op0->getType()->isDoubleTy())
634 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
635 else if (Op0->getType()->isX86_FP80Ty()) {
636 APFloat apf = APFloat(GV.IntVal);
639 (void)apf.convertToInteger(&v, BitWidth,
640 CE->getOpcode()==Instruction::FPToSI,
641 APFloat::rmTowardZero, &ignored);
642 GV.IntVal = v; // endian?
646 case Instruction::PtrToInt: {
647 GenericValue GV = getConstantValue(Op0);
648 unsigned AS = cast<PointerType>(CE->getOperand(1)->getType())
650 uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
651 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
654 case Instruction::IntToPtr: {
655 GenericValue GV = getConstantValue(Op0);
656 unsigned AS = cast<PointerType>(CE->getType())->getAddressSpace();
657 uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
658 if (PtrWidth != GV.IntVal.getBitWidth())
659 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
660 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
661 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
664 case Instruction::BitCast: {
665 GenericValue GV = getConstantValue(Op0);
666 Type* DestTy = CE->getType();
667 switch (Op0->getType()->getTypeID()) {
668 default: llvm_unreachable("Invalid bitcast operand");
669 case Type::IntegerTyID:
670 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
671 if (DestTy->isFloatTy())
672 GV.FloatVal = GV.IntVal.bitsToFloat();
673 else if (DestTy->isDoubleTy())
674 GV.DoubleVal = GV.IntVal.bitsToDouble();
676 case Type::FloatTyID:
677 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
678 GV.IntVal = APInt::floatToBits(GV.FloatVal);
680 case Type::DoubleTyID:
681 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
682 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
684 case Type::PointerTyID:
685 assert(DestTy->isPointerTy() && "Invalid bitcast");
686 break; // getConstantValue(Op0) above already converted it
690 case Instruction::Add:
691 case Instruction::FAdd:
692 case Instruction::Sub:
693 case Instruction::FSub:
694 case Instruction::Mul:
695 case Instruction::FMul:
696 case Instruction::UDiv:
697 case Instruction::SDiv:
698 case Instruction::URem:
699 case Instruction::SRem:
700 case Instruction::And:
701 case Instruction::Or:
702 case Instruction::Xor: {
703 GenericValue LHS = getConstantValue(Op0);
704 GenericValue RHS = getConstantValue(CE->getOperand(1));
706 switch (CE->getOperand(0)->getType()->getTypeID()) {
707 default: llvm_unreachable("Bad add type!");
708 case Type::IntegerTyID:
709 switch (CE->getOpcode()) {
710 default: llvm_unreachable("Invalid integer opcode");
711 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
712 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
713 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
714 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
715 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
716 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
717 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
718 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
719 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
720 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
723 case Type::FloatTyID:
724 switch (CE->getOpcode()) {
725 default: llvm_unreachable("Invalid float opcode");
726 case Instruction::FAdd:
727 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
728 case Instruction::FSub:
729 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
730 case Instruction::FMul:
731 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
732 case Instruction::FDiv:
733 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
734 case Instruction::FRem:
735 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
738 case Type::DoubleTyID:
739 switch (CE->getOpcode()) {
740 default: llvm_unreachable("Invalid double opcode");
741 case Instruction::FAdd:
742 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
743 case Instruction::FSub:
744 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
745 case Instruction::FMul:
746 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
747 case Instruction::FDiv:
748 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
749 case Instruction::FRem:
750 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
753 case Type::X86_FP80TyID:
754 case Type::PPC_FP128TyID:
755 case Type::FP128TyID: {
756 APFloat apfLHS = APFloat(LHS.IntVal);
757 switch (CE->getOpcode()) {
758 default: llvm_unreachable("Invalid long double opcode");
759 case Instruction::FAdd:
760 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
761 GV.IntVal = apfLHS.bitcastToAPInt();
763 case Instruction::FSub:
764 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
765 GV.IntVal = apfLHS.bitcastToAPInt();
767 case Instruction::FMul:
768 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
769 GV.IntVal = apfLHS.bitcastToAPInt();
771 case Instruction::FDiv:
772 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
773 GV.IntVal = apfLHS.bitcastToAPInt();
775 case Instruction::FRem:
776 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
777 GV.IntVal = apfLHS.bitcastToAPInt();
789 SmallString<256> Msg;
790 raw_svector_ostream OS(Msg);
791 OS << "ConstantExpr not handled: " << *CE;
792 report_fatal_error(OS.str());
795 // Otherwise, we have a simple constant.
797 switch (C->getType()->getTypeID()) {
798 case Type::FloatTyID:
799 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
801 case Type::DoubleTyID:
802 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
804 case Type::X86_FP80TyID:
805 case Type::FP128TyID:
806 case Type::PPC_FP128TyID:
807 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
809 case Type::IntegerTyID:
810 Result.IntVal = cast<ConstantInt>(C)->getValue();
812 case Type::PointerTyID:
813 if (isa<ConstantPointerNull>(C))
814 Result.PointerVal = 0;
815 else if (const Function *F = dyn_cast<Function>(C))
816 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
817 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
818 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
819 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
820 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
821 BA->getBasicBlock())));
823 llvm_unreachable("Unknown constant pointer type!");
826 SmallString<256> Msg;
827 raw_svector_ostream OS(Msg);
828 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
829 report_fatal_error(OS.str());
835 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
836 /// with the integer held in IntVal.
837 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
838 unsigned StoreBytes) {
839 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
840 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
842 if (sys::isLittleEndianHost()) {
843 // Little-endian host - the source is ordered from LSB to MSB. Order the
844 // destination from LSB to MSB: Do a straight copy.
845 memcpy(Dst, Src, StoreBytes);
847 // Big-endian host - the source is an array of 64 bit words ordered from
848 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
849 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
850 while (StoreBytes > sizeof(uint64_t)) {
851 StoreBytes -= sizeof(uint64_t);
852 // May not be aligned so use memcpy.
853 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
854 Src += sizeof(uint64_t);
857 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
861 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
862 GenericValue *Ptr, Type *Ty) {
863 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
865 switch (Ty->getTypeID()) {
866 case Type::IntegerTyID:
867 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
869 case Type::FloatTyID:
870 *((float*)Ptr) = Val.FloatVal;
872 case Type::DoubleTyID:
873 *((double*)Ptr) = Val.DoubleVal;
875 case Type::X86_FP80TyID:
876 memcpy(Ptr, Val.IntVal.getRawData(), 10);
878 case Type::PointerTyID:
879 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
880 if (StoreBytes != sizeof(PointerTy))
881 memset(&(Ptr->PointerVal), 0, StoreBytes);
883 *((PointerTy*)Ptr) = Val.PointerVal;
886 dbgs() << "Cannot store value of type " << *Ty << "!\n";
889 if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
890 // Host and target are different endian - reverse the stored bytes.
891 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
894 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
895 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
896 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
897 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
898 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
900 if (sys::isLittleEndianHost())
901 // Little-endian host - the destination must be ordered from LSB to MSB.
902 // The source is ordered from LSB to MSB: Do a straight copy.
903 memcpy(Dst, Src, LoadBytes);
905 // Big-endian - the destination is an array of 64 bit words ordered from
906 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
907 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
909 while (LoadBytes > sizeof(uint64_t)) {
910 LoadBytes -= sizeof(uint64_t);
911 // May not be aligned so use memcpy.
912 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
913 Dst += sizeof(uint64_t);
916 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
922 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
925 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
927 switch (Ty->getTypeID()) {
928 case Type::IntegerTyID:
929 // An APInt with all words initially zero.
930 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
931 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
933 case Type::FloatTyID:
934 Result.FloatVal = *((float*)Ptr);
936 case Type::DoubleTyID:
937 Result.DoubleVal = *((double*)Ptr);
939 case Type::PointerTyID:
940 Result.PointerVal = *((PointerTy*)Ptr);
942 case Type::X86_FP80TyID: {
943 // This is endian dependent, but it will only work on x86 anyway.
944 // FIXME: Will not trap if loading a signaling NaN.
947 Result.IntVal = APInt(80, y);
951 SmallString<256> Msg;
952 raw_svector_ostream OS(Msg);
953 OS << "Cannot load value of type " << *Ty << "!";
954 report_fatal_error(OS.str());
958 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
959 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
961 if (isa<UndefValue>(Init))
964 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
965 unsigned ElementSize =
966 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
967 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
968 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
972 if (isa<ConstantAggregateZero>(Init)) {
973 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
977 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
978 unsigned ElementSize =
979 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
980 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
981 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
985 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
986 const StructLayout *SL =
987 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
988 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
989 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
993 if (const ConstantDataSequential *CDS =
994 dyn_cast<ConstantDataSequential>(Init)) {
995 // CDS is already laid out in host memory order.
996 StringRef Data = CDS->getRawDataValues();
997 memcpy(Addr, Data.data(), Data.size());
1001 if (Init->getType()->isFirstClassType()) {
1002 GenericValue Val = getConstantValue(Init);
1003 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1007 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1008 llvm_unreachable("Unknown constant type to initialize memory with!");
1011 /// EmitGlobals - Emit all of the global variables to memory, storing their
1012 /// addresses into GlobalAddress. This must make sure to copy the contents of
1013 /// their initializers into the memory.
1014 void ExecutionEngine::emitGlobals() {
1015 // Loop over all of the global variables in the program, allocating the memory
1016 // to hold them. If there is more than one module, do a prepass over globals
1017 // to figure out how the different modules should link together.
1018 std::map<std::pair<std::string, Type*>,
1019 const GlobalValue*> LinkedGlobalsMap;
1021 if (Modules.size() != 1) {
1022 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1023 Module &M = *Modules[m];
1024 for (Module::const_global_iterator I = M.global_begin(),
1025 E = M.global_end(); I != E; ++I) {
1026 const GlobalValue *GV = I;
1027 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1028 GV->hasAppendingLinkage() || !GV->hasName())
1029 continue;// Ignore external globals and globals with internal linkage.
1031 const GlobalValue *&GVEntry =
1032 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1034 // If this is the first time we've seen this global, it is the canonical
1041 // If the existing global is strong, never replace it.
1042 if (GVEntry->hasExternalLinkage() ||
1043 GVEntry->hasDLLImportLinkage() ||
1044 GVEntry->hasDLLExportLinkage())
1047 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1048 // symbol. FIXME is this right for common?
1049 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1055 std::vector<const GlobalValue*> NonCanonicalGlobals;
1056 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1057 Module &M = *Modules[m];
1058 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1060 // In the multi-module case, see what this global maps to.
1061 if (!LinkedGlobalsMap.empty()) {
1062 if (const GlobalValue *GVEntry =
1063 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1064 // If something else is the canonical global, ignore this one.
1065 if (GVEntry != &*I) {
1066 NonCanonicalGlobals.push_back(I);
1072 if (!I->isDeclaration()) {
1073 addGlobalMapping(I, getMemoryForGV(I));
1075 // External variable reference. Try to use the dynamic loader to
1076 // get a pointer to it.
1078 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1079 addGlobalMapping(I, SymAddr);
1081 report_fatal_error("Could not resolve external global address: "
1087 // If there are multiple modules, map the non-canonical globals to their
1088 // canonical location.
1089 if (!NonCanonicalGlobals.empty()) {
1090 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1091 const GlobalValue *GV = NonCanonicalGlobals[i];
1092 const GlobalValue *CGV =
1093 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1094 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1095 assert(Ptr && "Canonical global wasn't codegen'd!");
1096 addGlobalMapping(GV, Ptr);
1100 // Now that all of the globals are set up in memory, loop through them all
1101 // and initialize their contents.
1102 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1104 if (!I->isDeclaration()) {
1105 if (!LinkedGlobalsMap.empty()) {
1106 if (const GlobalValue *GVEntry =
1107 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1108 if (GVEntry != &*I) // Not the canonical variable.
1111 EmitGlobalVariable(I);
1117 // EmitGlobalVariable - This method emits the specified global variable to the
1118 // address specified in GlobalAddresses, or allocates new memory if it's not
1119 // already in the map.
1120 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1121 void *GA = getPointerToGlobalIfAvailable(GV);
1124 // If it's not already specified, allocate memory for the global.
1125 GA = getMemoryForGV(GV);
1126 addGlobalMapping(GV, GA);
1129 // Don't initialize if it's thread local, let the client do it.
1130 if (!GV->isThreadLocal())
1131 InitializeMemory(GV->getInitializer(), GA);
1133 Type *ElTy = GV->getType()->getElementType();
1134 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1135 NumInitBytes += (unsigned)GVSize;
1139 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1140 : EE(EE), GlobalAddressMap(this) {
1144 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1145 return &EES->EE.lock;
1148 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1149 const GlobalValue *Old) {
1150 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1151 EES->GlobalAddressReverseMap.erase(OldVal);
1154 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1155 const GlobalValue *,
1156 const GlobalValue *) {
1157 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1158 " RAUW on a value it has a global mapping for.");