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 #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ExecutionEngine/GenericValue.h"
19 #include "llvm/ExecutionEngine/JITEventListener.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include "llvm/Object/Archive.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/DynamicLibrary.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/MutexGuard.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
40 #define DEBUG_TYPE "jit"
42 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43 STATISTIC(NumGlobals , "Number of global vars initialized");
45 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
46 std::unique_ptr<Module> M, std::string *ErrorStr,
47 RTDyldMemoryManager *MCJMM, std::unique_ptr<TargetMachine> TM) = nullptr;
48 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
49 std::string *ErrorStr) =nullptr;
51 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
53 LazyFunctionCreator(nullptr) {
54 CompilingLazily = false;
55 GVCompilationDisabled = false;
56 SymbolSearchingDisabled = false;
58 // IR module verification is enabled by default in debug builds, and disabled
59 // by default in release builds.
63 VerifyModules = false;
66 assert(M && "Module is null?");
67 Modules.push_back(std::move(M));
70 ExecutionEngine::~ExecutionEngine() {
71 clearAllGlobalMappings();
75 /// \brief Helper class which uses a value handler to automatically deletes the
76 /// memory block when the GlobalVariable is destroyed.
77 class GVMemoryBlock : public CallbackVH {
78 GVMemoryBlock(const GlobalVariable *GV)
79 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
82 /// \brief Returns the address the GlobalVariable should be written into. The
83 /// GVMemoryBlock object prefixes that.
84 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
85 Type *ElTy = GV->getType()->getElementType();
86 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
87 void *RawMemory = ::operator new(
88 RoundUpToAlignment(sizeof(GVMemoryBlock),
89 TD.getPreferredAlignment(GV))
91 new(RawMemory) GVMemoryBlock(GV);
92 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
95 void deleted() override {
96 // We allocated with operator new and with some extra memory hanging off the
97 // end, so don't just delete this. I'm not sure if this is actually
99 this->~GVMemoryBlock();
100 ::operator delete(this);
103 } // anonymous namespace
105 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
106 return GVMemoryBlock::Create(GV, *getDataLayout());
109 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
110 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
114 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
115 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
118 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
119 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
122 bool ExecutionEngine::removeModule(Module *M) {
123 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
124 Module *Found = I->get();
128 clearGlobalMappingsFromModule(M);
135 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
136 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
137 if (Function *F = Modules[i]->getFunction(FnName))
144 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
145 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
148 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
150 if (I == GlobalAddressMap.end())
154 GlobalAddressMap.erase(I);
157 GlobalAddressReverseMap.erase(OldVal);
161 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
162 MutexGuard locked(lock);
164 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
165 << "\' to [" << Addr << "]\n";);
166 void *&CurVal = EEState.getGlobalAddressMap()[GV];
167 assert((!CurVal || !Addr) && "GlobalMapping already established!");
170 // If we are using the reverse mapping, add it too.
171 if (!EEState.getGlobalAddressReverseMap().empty()) {
172 AssertingVH<const GlobalValue> &V =
173 EEState.getGlobalAddressReverseMap()[Addr];
174 assert((!V || !GV) && "GlobalMapping already established!");
179 void ExecutionEngine::clearAllGlobalMappings() {
180 MutexGuard locked(lock);
182 EEState.getGlobalAddressMap().clear();
183 EEState.getGlobalAddressReverseMap().clear();
186 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
187 MutexGuard locked(lock);
189 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
190 EEState.RemoveMapping(FI);
191 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
193 EEState.RemoveMapping(GI);
196 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
197 MutexGuard locked(lock);
199 ExecutionEngineState::GlobalAddressMapTy &Map =
200 EEState.getGlobalAddressMap();
202 // Deleting from the mapping?
204 return EEState.RemoveMapping(GV);
206 void *&CurVal = Map[GV];
207 void *OldVal = CurVal;
209 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
210 EEState.getGlobalAddressReverseMap().erase(CurVal);
213 // If we are using the reverse mapping, add it too.
214 if (!EEState.getGlobalAddressReverseMap().empty()) {
215 AssertingVH<const GlobalValue> &V =
216 EEState.getGlobalAddressReverseMap()[Addr];
217 assert((!V || !GV) && "GlobalMapping already established!");
223 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
224 MutexGuard locked(lock);
226 ExecutionEngineState::GlobalAddressMapTy::iterator I =
227 EEState.getGlobalAddressMap().find(GV);
228 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
231 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
232 MutexGuard locked(lock);
234 // If we haven't computed the reverse mapping yet, do so first.
235 if (EEState.getGlobalAddressReverseMap().empty()) {
236 for (ExecutionEngineState::GlobalAddressMapTy::iterator
237 I = EEState.getGlobalAddressMap().begin(),
238 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
239 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
240 I->second, I->first));
243 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
244 EEState.getGlobalAddressReverseMap().find(Addr);
245 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
250 std::unique_ptr<char[]> Array;
251 std::vector<std::unique_ptr<char[]>> Values;
253 /// Turn a vector of strings into a nice argv style array of pointers to null
254 /// terminated strings.
255 void *reset(LLVMContext &C, ExecutionEngine *EE,
256 const std::vector<std::string> &InputArgv);
258 } // anonymous namespace
259 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
260 const std::vector<std::string> &InputArgv) {
261 Values.clear(); // Free the old contents.
262 Values.reserve(InputArgv.size());
263 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
264 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
266 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
267 Type *SBytePtr = Type::getInt8PtrTy(C);
269 for (unsigned i = 0; i != InputArgv.size(); ++i) {
270 unsigned Size = InputArgv[i].size()+1;
271 auto Dest = make_unique<char[]>(Size);
272 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
274 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
277 // Endian safe: Array[i] = (PointerTy)Dest;
278 EE->StoreValueToMemory(PTOGV(Dest.get()),
279 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
280 Values.push_back(std::move(Dest));
284 EE->StoreValueToMemory(PTOGV(nullptr),
285 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
290 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
292 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
293 GlobalVariable *GV = module.getNamedGlobal(Name);
295 // If this global has internal linkage, or if it has a use, then it must be
296 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
297 // this is the case, don't execute any of the global ctors, __main will do
299 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
301 // Should be an array of '{ i32, void ()* }' structs. The first value is
302 // the init priority, which we ignore.
303 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
306 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
307 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
310 Constant *FP = CS->getOperand(1);
311 if (FP->isNullValue())
312 continue; // Found a sentinal value, ignore.
314 // Strip off constant expression casts.
315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
317 FP = CE->getOperand(0);
319 // Execute the ctor/dtor function!
320 if (Function *F = dyn_cast<Function>(FP))
321 runFunction(F, std::vector<GenericValue>());
323 // FIXME: It is marginally lame that we just do nothing here if we see an
324 // entry we don't recognize. It might not be unreasonable for the verifier
325 // to not even allow this and just assert here.
329 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
330 // Execute global ctors/dtors for each module in the program.
331 for (std::unique_ptr<Module> &M : Modules)
332 runStaticConstructorsDestructors(*M, isDtors);
336 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
337 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
338 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
339 for (unsigned i = 0; i < PtrSize; ++i)
340 if (*(i + (uint8_t*)Loc))
346 int ExecutionEngine::runFunctionAsMain(Function *Fn,
347 const std::vector<std::string> &argv,
348 const char * const * envp) {
349 std::vector<GenericValue> GVArgs;
351 GVArgc.IntVal = APInt(32, argv.size());
354 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
355 FunctionType *FTy = Fn->getFunctionType();
356 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
358 // Check the argument types.
360 report_fatal_error("Invalid number of arguments of main() supplied");
361 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
362 report_fatal_error("Invalid type for third argument of main() supplied");
363 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
364 report_fatal_error("Invalid type for second argument of main() supplied");
365 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
366 report_fatal_error("Invalid type for first argument of main() supplied");
367 if (!FTy->getReturnType()->isIntegerTy() &&
368 !FTy->getReturnType()->isVoidTy())
369 report_fatal_error("Invalid return type of main() supplied");
374 GVArgs.push_back(GVArgc); // Arg #0 = argc.
377 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
378 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
379 "argv[0] was null after CreateArgv");
381 std::vector<std::string> EnvVars;
382 for (unsigned i = 0; envp[i]; ++i)
383 EnvVars.push_back(envp[i]);
385 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
390 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
393 void EngineBuilder::InitEngine() {
394 WhichEngine = EngineKind::Either;
396 OptLevel = CodeGenOpt::Default;
398 Options = TargetOptions();
399 RelocModel = Reloc::Default;
400 CMModel = CodeModel::JITDefault;
402 // IR module verification is enabled by default in debug builds, and disabled
403 // by default in release builds.
405 VerifyModules = true;
407 VerifyModules = false;
411 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
412 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
414 // Make sure we can resolve symbols in the program as well. The zero arg
415 // to the function tells DynamicLibrary to load the program, not a library.
416 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
419 // If the user specified a memory manager but didn't specify which engine to
420 // create, we assume they only want the JIT, and we fail if they only want
423 if (WhichEngine & EngineKind::JIT)
424 WhichEngine = EngineKind::JIT;
427 *ErrorStr = "Cannot create an interpreter with a memory manager.";
432 // Unless the interpreter was explicitly selected or the JIT is not linked,
434 if ((WhichEngine & EngineKind::JIT) && TheTM) {
435 Triple TT(M->getTargetTriple());
436 if (!TM->getTarget().hasJIT()) {
437 errs() << "WARNING: This target JIT is not designed for the host"
438 << " you are running. If bad things happen, please choose"
439 << " a different -march switch.\n";
442 ExecutionEngine *EE = nullptr;
443 if (ExecutionEngine::MCJITCtor)
444 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, MCJMM,
447 EE->setVerifyModules(VerifyModules);
452 // If we can't make a JIT and we didn't request one specifically, try making
453 // an interpreter instead.
454 if (WhichEngine & EngineKind::Interpreter) {
455 if (ExecutionEngine::InterpCtor)
456 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
458 *ErrorStr = "Interpreter has not been linked in.";
462 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
464 *ErrorStr = "JIT has not been linked in.";
470 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
471 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
472 return getPointerToFunction(F);
474 MutexGuard locked(lock);
475 if (void *P = EEState.getGlobalAddressMap()[GV])
478 // Global variable might have been added since interpreter started.
479 if (GlobalVariable *GVar =
480 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
481 EmitGlobalVariable(GVar);
483 llvm_unreachable("Global hasn't had an address allocated yet!");
485 return EEState.getGlobalAddressMap()[GV];
488 /// \brief Converts a Constant* into a GenericValue, including handling of
489 /// ConstantExpr values.
490 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
491 // If its undefined, return the garbage.
492 if (isa<UndefValue>(C)) {
494 switch (C->getType()->getTypeID()) {
497 case Type::IntegerTyID:
498 case Type::X86_FP80TyID:
499 case Type::FP128TyID:
500 case Type::PPC_FP128TyID:
501 // Although the value is undefined, we still have to construct an APInt
502 // with the correct bit width.
503 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
505 case Type::StructTyID: {
506 // if the whole struct is 'undef' just reserve memory for the value.
507 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
508 unsigned int elemNum = STy->getNumElements();
509 Result.AggregateVal.resize(elemNum);
510 for (unsigned int i = 0; i < elemNum; ++i) {
511 Type *ElemTy = STy->getElementType(i);
512 if (ElemTy->isIntegerTy())
513 Result.AggregateVal[i].IntVal =
514 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
515 else if (ElemTy->isAggregateType()) {
516 const Constant *ElemUndef = UndefValue::get(ElemTy);
517 Result.AggregateVal[i] = getConstantValue(ElemUndef);
523 case Type::VectorTyID:
524 // if the whole vector is 'undef' just reserve memory for the value.
525 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
526 const Type *ElemTy = VTy->getElementType();
527 unsigned int elemNum = VTy->getNumElements();
528 Result.AggregateVal.resize(elemNum);
529 if (ElemTy->isIntegerTy())
530 for (unsigned int i = 0; i < elemNum; ++i)
531 Result.AggregateVal[i].IntVal =
532 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
538 // Otherwise, if the value is a ConstantExpr...
539 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
540 Constant *Op0 = CE->getOperand(0);
541 switch (CE->getOpcode()) {
542 case Instruction::GetElementPtr: {
544 GenericValue Result = getConstantValue(Op0);
545 APInt Offset(DL->getPointerSizeInBits(), 0);
546 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
548 char* tmp = (char*) Result.PointerVal;
549 Result = PTOGV(tmp + Offset.getSExtValue());
552 case Instruction::Trunc: {
553 GenericValue GV = getConstantValue(Op0);
554 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
555 GV.IntVal = GV.IntVal.trunc(BitWidth);
558 case Instruction::ZExt: {
559 GenericValue GV = getConstantValue(Op0);
560 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
561 GV.IntVal = GV.IntVal.zext(BitWidth);
564 case Instruction::SExt: {
565 GenericValue GV = getConstantValue(Op0);
566 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
567 GV.IntVal = GV.IntVal.sext(BitWidth);
570 case Instruction::FPTrunc: {
572 GenericValue GV = getConstantValue(Op0);
573 GV.FloatVal = float(GV.DoubleVal);
576 case Instruction::FPExt:{
578 GenericValue GV = getConstantValue(Op0);
579 GV.DoubleVal = double(GV.FloatVal);
582 case Instruction::UIToFP: {
583 GenericValue GV = getConstantValue(Op0);
584 if (CE->getType()->isFloatTy())
585 GV.FloatVal = float(GV.IntVal.roundToDouble());
586 else if (CE->getType()->isDoubleTy())
587 GV.DoubleVal = GV.IntVal.roundToDouble();
588 else if (CE->getType()->isX86_FP80Ty()) {
589 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
590 (void)apf.convertFromAPInt(GV.IntVal,
592 APFloat::rmNearestTiesToEven);
593 GV.IntVal = apf.bitcastToAPInt();
597 case Instruction::SIToFP: {
598 GenericValue GV = getConstantValue(Op0);
599 if (CE->getType()->isFloatTy())
600 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
601 else if (CE->getType()->isDoubleTy())
602 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
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::FPToUI: // double->APInt conversion handles sign
613 case Instruction::FPToSI: {
614 GenericValue GV = getConstantValue(Op0);
615 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
616 if (Op0->getType()->isFloatTy())
617 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
618 else if (Op0->getType()->isDoubleTy())
619 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
620 else if (Op0->getType()->isX86_FP80Ty()) {
621 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
624 (void)apf.convertToInteger(&v, BitWidth,
625 CE->getOpcode()==Instruction::FPToSI,
626 APFloat::rmTowardZero, &ignored);
627 GV.IntVal = v; // endian?
631 case Instruction::PtrToInt: {
632 GenericValue GV = getConstantValue(Op0);
633 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
634 assert(PtrWidth <= 64 && "Bad pointer width");
635 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
636 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
637 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
640 case Instruction::IntToPtr: {
641 GenericValue GV = getConstantValue(Op0);
642 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
643 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
644 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
645 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
648 case Instruction::BitCast: {
649 GenericValue GV = getConstantValue(Op0);
650 Type* DestTy = CE->getType();
651 switch (Op0->getType()->getTypeID()) {
652 default: llvm_unreachable("Invalid bitcast operand");
653 case Type::IntegerTyID:
654 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
655 if (DestTy->isFloatTy())
656 GV.FloatVal = GV.IntVal.bitsToFloat();
657 else if (DestTy->isDoubleTy())
658 GV.DoubleVal = GV.IntVal.bitsToDouble();
660 case Type::FloatTyID:
661 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
662 GV.IntVal = APInt::floatToBits(GV.FloatVal);
664 case Type::DoubleTyID:
665 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
666 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
668 case Type::PointerTyID:
669 assert(DestTy->isPointerTy() && "Invalid bitcast");
670 break; // getConstantValue(Op0) above already converted it
674 case Instruction::Add:
675 case Instruction::FAdd:
676 case Instruction::Sub:
677 case Instruction::FSub:
678 case Instruction::Mul:
679 case Instruction::FMul:
680 case Instruction::UDiv:
681 case Instruction::SDiv:
682 case Instruction::URem:
683 case Instruction::SRem:
684 case Instruction::And:
685 case Instruction::Or:
686 case Instruction::Xor: {
687 GenericValue LHS = getConstantValue(Op0);
688 GenericValue RHS = getConstantValue(CE->getOperand(1));
690 switch (CE->getOperand(0)->getType()->getTypeID()) {
691 default: llvm_unreachable("Bad add type!");
692 case Type::IntegerTyID:
693 switch (CE->getOpcode()) {
694 default: llvm_unreachable("Invalid integer opcode");
695 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
696 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
697 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
698 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
699 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
700 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
701 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
702 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
703 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
704 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
707 case Type::FloatTyID:
708 switch (CE->getOpcode()) {
709 default: llvm_unreachable("Invalid float opcode");
710 case Instruction::FAdd:
711 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
712 case Instruction::FSub:
713 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
714 case Instruction::FMul:
715 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
716 case Instruction::FDiv:
717 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
718 case Instruction::FRem:
719 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
722 case Type::DoubleTyID:
723 switch (CE->getOpcode()) {
724 default: llvm_unreachable("Invalid double opcode");
725 case Instruction::FAdd:
726 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
727 case Instruction::FSub:
728 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
729 case Instruction::FMul:
730 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
731 case Instruction::FDiv:
732 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
733 case Instruction::FRem:
734 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
737 case Type::X86_FP80TyID:
738 case Type::PPC_FP128TyID:
739 case Type::FP128TyID: {
740 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
741 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
742 switch (CE->getOpcode()) {
743 default: llvm_unreachable("Invalid long double opcode");
744 case Instruction::FAdd:
745 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
746 GV.IntVal = apfLHS.bitcastToAPInt();
748 case Instruction::FSub:
749 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
750 APFloat::rmNearestTiesToEven);
751 GV.IntVal = apfLHS.bitcastToAPInt();
753 case Instruction::FMul:
754 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
755 APFloat::rmNearestTiesToEven);
756 GV.IntVal = apfLHS.bitcastToAPInt();
758 case Instruction::FDiv:
759 apfLHS.divide(APFloat(Sem, RHS.IntVal),
760 APFloat::rmNearestTiesToEven);
761 GV.IntVal = apfLHS.bitcastToAPInt();
763 case Instruction::FRem:
764 apfLHS.mod(APFloat(Sem, RHS.IntVal),
765 APFloat::rmNearestTiesToEven);
766 GV.IntVal = apfLHS.bitcastToAPInt();
778 SmallString<256> Msg;
779 raw_svector_ostream OS(Msg);
780 OS << "ConstantExpr not handled: " << *CE;
781 report_fatal_error(OS.str());
784 // Otherwise, we have a simple constant.
786 switch (C->getType()->getTypeID()) {
787 case Type::FloatTyID:
788 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
790 case Type::DoubleTyID:
791 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
793 case Type::X86_FP80TyID:
794 case Type::FP128TyID:
795 case Type::PPC_FP128TyID:
796 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
798 case Type::IntegerTyID:
799 Result.IntVal = cast<ConstantInt>(C)->getValue();
801 case Type::PointerTyID:
802 if (isa<ConstantPointerNull>(C))
803 Result.PointerVal = nullptr;
804 else if (const Function *F = dyn_cast<Function>(C))
805 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
806 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
807 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
809 llvm_unreachable("Unknown constant pointer type!");
811 case Type::VectorTyID: {
814 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
815 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
816 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
819 elemNum = CDV->getNumElements();
820 ElemTy = CDV->getElementType();
821 } else if (CV || CAZ) {
822 VectorType* VTy = dyn_cast<VectorType>(C->getType());
823 elemNum = VTy->getNumElements();
824 ElemTy = VTy->getElementType();
826 llvm_unreachable("Unknown constant vector type!");
829 Result.AggregateVal.resize(elemNum);
830 // Check if vector holds floats.
831 if(ElemTy->isFloatTy()) {
833 GenericValue floatZero;
834 floatZero.FloatVal = 0.f;
835 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
840 for (unsigned i = 0; i < elemNum; ++i)
841 if (!isa<UndefValue>(CV->getOperand(i)))
842 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
843 CV->getOperand(i))->getValueAPF().convertToFloat();
847 for (unsigned i = 0; i < elemNum; ++i)
848 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
852 // Check if vector holds doubles.
853 if (ElemTy->isDoubleTy()) {
855 GenericValue doubleZero;
856 doubleZero.DoubleVal = 0.0;
857 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
862 for (unsigned i = 0; i < elemNum; ++i)
863 if (!isa<UndefValue>(CV->getOperand(i)))
864 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
865 CV->getOperand(i))->getValueAPF().convertToDouble();
869 for (unsigned i = 0; i < elemNum; ++i)
870 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
874 // Check if vector holds integers.
875 if (ElemTy->isIntegerTy()) {
877 GenericValue intZero;
878 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
879 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
884 for (unsigned i = 0; i < elemNum; ++i)
885 if (!isa<UndefValue>(CV->getOperand(i)))
886 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
887 CV->getOperand(i))->getValue();
889 Result.AggregateVal[i].IntVal =
890 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
895 for (unsigned i = 0; i < elemNum; ++i)
896 Result.AggregateVal[i].IntVal = APInt(
897 CDV->getElementType()->getPrimitiveSizeInBits(),
898 CDV->getElementAsInteger(i));
902 llvm_unreachable("Unknown constant pointer type!");
907 SmallString<256> Msg;
908 raw_svector_ostream OS(Msg);
909 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
910 report_fatal_error(OS.str());
916 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
917 /// with the integer held in IntVal.
918 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
919 unsigned StoreBytes) {
920 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
921 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
923 if (sys::IsLittleEndianHost) {
924 // Little-endian host - the source is ordered from LSB to MSB. Order the
925 // destination from LSB to MSB: Do a straight copy.
926 memcpy(Dst, Src, StoreBytes);
928 // Big-endian host - the source is an array of 64 bit words ordered from
929 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
930 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
931 while (StoreBytes > sizeof(uint64_t)) {
932 StoreBytes -= sizeof(uint64_t);
933 // May not be aligned so use memcpy.
934 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
935 Src += sizeof(uint64_t);
938 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
942 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
943 GenericValue *Ptr, Type *Ty) {
944 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
946 switch (Ty->getTypeID()) {
948 dbgs() << "Cannot store value of type " << *Ty << "!\n";
950 case Type::IntegerTyID:
951 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
953 case Type::FloatTyID:
954 *((float*)Ptr) = Val.FloatVal;
956 case Type::DoubleTyID:
957 *((double*)Ptr) = Val.DoubleVal;
959 case Type::X86_FP80TyID:
960 memcpy(Ptr, Val.IntVal.getRawData(), 10);
962 case Type::PointerTyID:
963 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
964 if (StoreBytes != sizeof(PointerTy))
965 memset(&(Ptr->PointerVal), 0, StoreBytes);
967 *((PointerTy*)Ptr) = Val.PointerVal;
969 case Type::VectorTyID:
970 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
971 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
972 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
973 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
974 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
975 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
976 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
977 StoreIntToMemory(Val.AggregateVal[i].IntVal,
978 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
984 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
985 // Host and target are different endian - reverse the stored bytes.
986 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
989 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
990 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
991 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
992 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
993 uint8_t *Dst = reinterpret_cast<uint8_t *>(
994 const_cast<uint64_t *>(IntVal.getRawData()));
996 if (sys::IsLittleEndianHost)
997 // Little-endian host - the destination must be ordered from LSB to MSB.
998 // The source is ordered from LSB to MSB: Do a straight copy.
999 memcpy(Dst, Src, LoadBytes);
1001 // Big-endian - the destination is an array of 64 bit words ordered from
1002 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1003 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1005 while (LoadBytes > sizeof(uint64_t)) {
1006 LoadBytes -= sizeof(uint64_t);
1007 // May not be aligned so use memcpy.
1008 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1009 Dst += sizeof(uint64_t);
1012 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1018 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1021 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1023 switch (Ty->getTypeID()) {
1024 case Type::IntegerTyID:
1025 // An APInt with all words initially zero.
1026 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1027 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1029 case Type::FloatTyID:
1030 Result.FloatVal = *((float*)Ptr);
1032 case Type::DoubleTyID:
1033 Result.DoubleVal = *((double*)Ptr);
1035 case Type::PointerTyID:
1036 Result.PointerVal = *((PointerTy*)Ptr);
1038 case Type::X86_FP80TyID: {
1039 // This is endian dependent, but it will only work on x86 anyway.
1040 // FIXME: Will not trap if loading a signaling NaN.
1043 Result.IntVal = APInt(80, y);
1046 case Type::VectorTyID: {
1047 const VectorType *VT = cast<VectorType>(Ty);
1048 const Type *ElemT = VT->getElementType();
1049 const unsigned numElems = VT->getNumElements();
1050 if (ElemT->isFloatTy()) {
1051 Result.AggregateVal.resize(numElems);
1052 for (unsigned i = 0; i < numElems; ++i)
1053 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1055 if (ElemT->isDoubleTy()) {
1056 Result.AggregateVal.resize(numElems);
1057 for (unsigned i = 0; i < numElems; ++i)
1058 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1060 if (ElemT->isIntegerTy()) {
1061 GenericValue intZero;
1062 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1063 intZero.IntVal = APInt(elemBitWidth, 0);
1064 Result.AggregateVal.resize(numElems, intZero);
1065 for (unsigned i = 0; i < numElems; ++i)
1066 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1067 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1072 SmallString<256> Msg;
1073 raw_svector_ostream OS(Msg);
1074 OS << "Cannot load value of type " << *Ty << "!";
1075 report_fatal_error(OS.str());
1079 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1080 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1081 DEBUG(Init->dump());
1082 if (isa<UndefValue>(Init))
1085 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1086 unsigned ElementSize =
1087 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1088 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1089 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1093 if (isa<ConstantAggregateZero>(Init)) {
1094 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1098 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1099 unsigned ElementSize =
1100 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1101 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1102 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1106 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1107 const StructLayout *SL =
1108 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1109 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1110 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1114 if (const ConstantDataSequential *CDS =
1115 dyn_cast<ConstantDataSequential>(Init)) {
1116 // CDS is already laid out in host memory order.
1117 StringRef Data = CDS->getRawDataValues();
1118 memcpy(Addr, Data.data(), Data.size());
1122 if (Init->getType()->isFirstClassType()) {
1123 GenericValue Val = getConstantValue(Init);
1124 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1128 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1129 llvm_unreachable("Unknown constant type to initialize memory with!");
1132 /// EmitGlobals - Emit all of the global variables to memory, storing their
1133 /// addresses into GlobalAddress. This must make sure to copy the contents of
1134 /// their initializers into the memory.
1135 void ExecutionEngine::emitGlobals() {
1136 // Loop over all of the global variables in the program, allocating the memory
1137 // to hold them. If there is more than one module, do a prepass over globals
1138 // to figure out how the different modules should link together.
1139 std::map<std::pair<std::string, Type*>,
1140 const GlobalValue*> LinkedGlobalsMap;
1142 if (Modules.size() != 1) {
1143 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1144 Module &M = *Modules[m];
1145 for (const auto &GV : M.globals()) {
1146 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1147 GV.hasAppendingLinkage() || !GV.hasName())
1148 continue;// Ignore external globals and globals with internal linkage.
1150 const GlobalValue *&GVEntry =
1151 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1153 // If this is the first time we've seen this global, it is the canonical
1160 // If the existing global is strong, never replace it.
1161 if (GVEntry->hasExternalLinkage())
1164 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1165 // symbol. FIXME is this right for common?
1166 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1172 std::vector<const GlobalValue*> NonCanonicalGlobals;
1173 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1174 Module &M = *Modules[m];
1175 for (const auto &GV : M.globals()) {
1176 // In the multi-module case, see what this global maps to.
1177 if (!LinkedGlobalsMap.empty()) {
1178 if (const GlobalValue *GVEntry =
1179 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1180 // If something else is the canonical global, ignore this one.
1181 if (GVEntry != &GV) {
1182 NonCanonicalGlobals.push_back(&GV);
1188 if (!GV.isDeclaration()) {
1189 addGlobalMapping(&GV, getMemoryForGV(&GV));
1191 // External variable reference. Try to use the dynamic loader to
1192 // get a pointer to it.
1194 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1195 addGlobalMapping(&GV, SymAddr);
1197 report_fatal_error("Could not resolve external global address: "
1203 // If there are multiple modules, map the non-canonical globals to their
1204 // canonical location.
1205 if (!NonCanonicalGlobals.empty()) {
1206 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1207 const GlobalValue *GV = NonCanonicalGlobals[i];
1208 const GlobalValue *CGV =
1209 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1210 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1211 assert(Ptr && "Canonical global wasn't codegen'd!");
1212 addGlobalMapping(GV, Ptr);
1216 // Now that all of the globals are set up in memory, loop through them all
1217 // and initialize their contents.
1218 for (const auto &GV : M.globals()) {
1219 if (!GV.isDeclaration()) {
1220 if (!LinkedGlobalsMap.empty()) {
1221 if (const GlobalValue *GVEntry =
1222 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1223 if (GVEntry != &GV) // Not the canonical variable.
1226 EmitGlobalVariable(&GV);
1232 // EmitGlobalVariable - This method emits the specified global variable to the
1233 // address specified in GlobalAddresses, or allocates new memory if it's not
1234 // already in the map.
1235 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1236 void *GA = getPointerToGlobalIfAvailable(GV);
1239 // If it's not already specified, allocate memory for the global.
1240 GA = getMemoryForGV(GV);
1242 // If we failed to allocate memory for this global, return.
1245 addGlobalMapping(GV, GA);
1248 // Don't initialize if it's thread local, let the client do it.
1249 if (!GV->isThreadLocal())
1250 InitializeMemory(GV->getInitializer(), GA);
1252 Type *ElTy = GV->getType()->getElementType();
1253 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1254 NumInitBytes += (unsigned)GVSize;
1258 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1259 : EE(EE), GlobalAddressMap(this) {
1263 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1264 return &EES->EE.lock;
1267 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1268 const GlobalValue *Old) {
1269 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1270 EES->GlobalAddressReverseMap.erase(OldVal);
1273 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1274 const GlobalValue *,
1275 const GlobalValue *) {
1276 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1277 " RAUW on a value it has a global mapping for.");