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/JITMemoryManager.h"
20 #include "llvm/ExecutionEngine/ObjectCache.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/ValueHandle.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 // Pin the vtable to this file.
46 void ObjectCache::anchor() {}
47 void ObjectBuffer::anchor() {}
48 void ObjectBufferStream::anchor() {}
50 ExecutionEngine *(*ExecutionEngine::JITCtor)(
52 std::string *ErrorStr,
53 JITMemoryManager *JMM,
55 TargetMachine *TM) = nullptr;
56 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
58 std::string *ErrorStr,
59 RTDyldMemoryManager *MCJMM,
61 TargetMachine *TM) = nullptr;
62 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
63 std::string *ErrorStr) =nullptr;
65 ExecutionEngine::ExecutionEngine(Module *M)
67 LazyFunctionCreator(nullptr) {
68 CompilingLazily = false;
69 GVCompilationDisabled = false;
70 SymbolSearchingDisabled = false;
72 // IR module verification is enabled by default in debug builds, and disabled
73 // by default in release builds.
77 VerifyModules = false;
81 assert(M && "Module is null?");
84 ExecutionEngine::~ExecutionEngine() {
85 clearAllGlobalMappings();
86 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
91 /// \brief Helper class which uses a value handler to automatically deletes the
92 /// memory block when the GlobalVariable is destroyed.
93 class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
98 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
100 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
101 Type *ElTy = GV->getType()->getElementType();
102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
104 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
105 TD.getPreferredAlignment(GV))
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
111 void deleted() override {
112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
115 this->~GVMemoryBlock();
116 ::operator delete(this);
119 } // anonymous namespace
121 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
122 return GVMemoryBlock::Create(GV, *getDataLayout());
125 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
126 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
129 bool ExecutionEngine::removeModule(Module *M) {
130 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
131 E = Modules.end(); I != E; ++I) {
135 clearGlobalMappingsFromModule(M);
142 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
143 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
144 if (Function *F = Modules[i]->getFunction(FnName))
151 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
152 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
155 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
157 if (I == GlobalAddressMap.end())
161 GlobalAddressMap.erase(I);
164 GlobalAddressReverseMap.erase(OldVal);
168 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
169 MutexGuard locked(lock);
171 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
172 << "\' to [" << Addr << "]\n";);
173 void *&CurVal = EEState.getGlobalAddressMap()[GV];
174 assert((!CurVal || !Addr) && "GlobalMapping already established!");
177 // If we are using the reverse mapping, add it too.
178 if (!EEState.getGlobalAddressReverseMap().empty()) {
179 AssertingVH<const GlobalValue> &V =
180 EEState.getGlobalAddressReverseMap()[Addr];
181 assert((!V || !GV) && "GlobalMapping already established!");
186 void ExecutionEngine::clearAllGlobalMappings() {
187 MutexGuard locked(lock);
189 EEState.getGlobalAddressMap().clear();
190 EEState.getGlobalAddressReverseMap().clear();
193 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
194 MutexGuard locked(lock);
196 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
197 EEState.RemoveMapping(FI);
198 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
200 EEState.RemoveMapping(GI);
203 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
204 MutexGuard locked(lock);
206 ExecutionEngineState::GlobalAddressMapTy &Map =
207 EEState.getGlobalAddressMap();
209 // Deleting from the mapping?
211 return EEState.RemoveMapping(GV);
213 void *&CurVal = Map[GV];
214 void *OldVal = CurVal;
216 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
217 EEState.getGlobalAddressReverseMap().erase(CurVal);
220 // If we are using the reverse mapping, add it too.
221 if (!EEState.getGlobalAddressReverseMap().empty()) {
222 AssertingVH<const GlobalValue> &V =
223 EEState.getGlobalAddressReverseMap()[Addr];
224 assert((!V || !GV) && "GlobalMapping already established!");
230 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
231 MutexGuard locked(lock);
233 ExecutionEngineState::GlobalAddressMapTy::iterator I =
234 EEState.getGlobalAddressMap().find(GV);
235 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
238 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
239 MutexGuard locked(lock);
241 // If we haven't computed the reverse mapping yet, do so first.
242 if (EEState.getGlobalAddressReverseMap().empty()) {
243 for (ExecutionEngineState::GlobalAddressMapTy::iterator
244 I = EEState.getGlobalAddressMap().begin(),
245 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
246 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
247 I->second, I->first));
250 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
251 EEState.getGlobalAddressReverseMap().find(Addr);
252 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
258 std::vector<char*> Values;
260 ArgvArray() : Array(nullptr) {}
261 ~ArgvArray() { clear(); }
265 for (size_t I = 0, E = Values.size(); I != E; ++I) {
270 /// Turn a vector of strings into a nice argv style array of pointers to null
271 /// terminated strings.
272 void *reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv);
275 } // anonymous namespace
276 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
277 const std::vector<std::string> &InputArgv) {
278 clear(); // Free the old contents.
279 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
280 Array = new char[(InputArgv.size()+1)*PtrSize];
282 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
283 Type *SBytePtr = Type::getInt8PtrTy(C);
285 for (unsigned i = 0; i != InputArgv.size(); ++i) {
286 unsigned Size = InputArgv[i].size()+1;
287 char *Dest = new char[Size];
288 Values.push_back(Dest);
289 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
291 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
294 // Endian safe: Array[i] = (PointerTy)Dest;
295 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
300 EE->StoreValueToMemory(PTOGV(nullptr),
301 (GenericValue*)(Array+InputArgv.size()*PtrSize),
306 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
308 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
309 GlobalVariable *GV = module->getNamedGlobal(Name);
311 // If this global has internal linkage, or if it has a use, then it must be
312 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
313 // this is the case, don't execute any of the global ctors, __main will do
315 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
317 // Should be an array of '{ i32, void ()* }' structs. The first value is
318 // the init priority, which we ignore.
319 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
323 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
326 Constant *FP = CS->getOperand(1);
327 if (FP->isNullValue())
328 continue; // Found a sentinal value, ignore.
330 // Strip off constant expression casts.
331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
333 FP = CE->getOperand(0);
335 // Execute the ctor/dtor function!
336 if (Function *F = dyn_cast<Function>(FP))
337 runFunction(F, std::vector<GenericValue>());
339 // FIXME: It is marginally lame that we just do nothing here if we see an
340 // entry we don't recognize. It might not be unreasonable for the verifier
341 // to not even allow this and just assert here.
345 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
346 // Execute global ctors/dtors for each module in the program.
347 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
348 runStaticConstructorsDestructors(Modules[i], isDtors);
352 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
353 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
354 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
355 for (unsigned i = 0; i < PtrSize; ++i)
356 if (*(i + (uint8_t*)Loc))
362 int ExecutionEngine::runFunctionAsMain(Function *Fn,
363 const std::vector<std::string> &argv,
364 const char * const * envp) {
365 std::vector<GenericValue> GVArgs;
367 GVArgc.IntVal = APInt(32, argv.size());
370 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
371 FunctionType *FTy = Fn->getFunctionType();
372 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
374 // Check the argument types.
376 report_fatal_error("Invalid number of arguments of main() supplied");
377 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
378 report_fatal_error("Invalid type for third argument of main() supplied");
379 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
380 report_fatal_error("Invalid type for second argument of main() supplied");
381 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
382 report_fatal_error("Invalid type for first argument of main() supplied");
383 if (!FTy->getReturnType()->isIntegerTy() &&
384 !FTy->getReturnType()->isVoidTy())
385 report_fatal_error("Invalid return type of main() supplied");
390 GVArgs.push_back(GVArgc); // Arg #0 = argc.
393 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
394 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
395 "argv[0] was null after CreateArgv");
397 std::vector<std::string> EnvVars;
398 for (unsigned i = 0; envp[i]; ++i)
399 EnvVars.push_back(envp[i]);
401 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
406 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
409 ExecutionEngine *ExecutionEngine::create(Module *M,
410 bool ForceInterpreter,
411 std::string *ErrorStr,
412 CodeGenOpt::Level OptLevel,
417 .setEngineKind(ForceInterpreter ? EngineKind::Interpreter
418 : EngineKind::Either)
419 .setErrorStr(ErrorStr)
420 .setOptLevel(OptLevel)
421 .setAllocateGVsWithCode(GVsWithCode);
426 /// createJIT - This is the factory method for creating a JIT for the current
427 /// machine, it does not fall back to the interpreter. This takes ownership
429 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
430 std::string *ErrorStr,
431 JITMemoryManager *JMM,
432 CodeGenOpt::Level OL,
435 CodeModel::Model CMM) {
436 if (!ExecutionEngine::JITCtor) {
438 *ErrorStr = "JIT has not been linked in.";
442 // Use the defaults for extra parameters. Users can use EngineBuilder to
445 EB.setEngineKind(EngineKind::JIT);
446 EB.setErrorStr(ErrorStr);
447 EB.setRelocationModel(RM);
448 EB.setCodeModel(CMM);
449 EB.setAllocateGVsWithCode(GVsWithCode);
451 EB.setJITMemoryManager(JMM);
453 // TODO: permit custom TargetOptions here
454 TargetMachine *TM = EB.selectTarget();
455 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
457 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
460 void EngineBuilder::InitEngine() {
461 WhichEngine = EngineKind::Either;
463 OptLevel = CodeGenOpt::Default;
466 Options = TargetOptions();
467 AllocateGVsWithCode = false;
468 RelocModel = Reloc::Default;
469 CMModel = CodeModel::JITDefault;
472 // IR module verification is enabled by default in debug builds, and disabled
473 // by default in release builds.
475 VerifyModules = true;
477 VerifyModules = false;
481 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
482 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
484 // Make sure we can resolve symbols in the program as well. The zero arg
485 // to the function tells DynamicLibrary to load the program, not a library.
486 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
489 assert(!(JMM && MCJMM));
491 // If the user specified a memory manager but didn't specify which engine to
492 // create, we assume they only want the JIT, and we fail if they only want
495 if (WhichEngine & EngineKind::JIT)
496 WhichEngine = EngineKind::JIT;
499 *ErrorStr = "Cannot create an interpreter with a memory manager.";
504 if (MCJMM && ! UseMCJIT) {
507 "Cannot create a legacy JIT with a runtime dyld memory "
512 // Unless the interpreter was explicitly selected or the JIT is not linked,
514 if ((WhichEngine & EngineKind::JIT) && TheTM) {
515 Triple TT(M->getTargetTriple());
516 if (!TM->getTarget().hasJIT()) {
517 errs() << "WARNING: This target JIT is not designed for the host"
518 << " you are running. If bad things happen, please choose"
519 << " a different -march switch.\n";
522 ExecutionEngine *EE = nullptr;
523 if (UseMCJIT && ExecutionEngine::MCJITCtor)
524 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
525 AllocateGVsWithCode, TheTM.release());
526 else if (ExecutionEngine::JITCtor)
527 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
528 AllocateGVsWithCode, TheTM.release());
531 EE->setVerifyModules(VerifyModules);
536 // If we can't make a JIT and we didn't request one specifically, try making
537 // an interpreter instead.
538 if (WhichEngine & EngineKind::Interpreter) {
539 if (ExecutionEngine::InterpCtor)
540 return ExecutionEngine::InterpCtor(M, ErrorStr);
542 *ErrorStr = "Interpreter has not been linked in.";
546 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
547 !ExecutionEngine::MCJITCtor) {
549 *ErrorStr = "JIT has not been linked in.";
555 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
556 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
557 return getPointerToFunction(F);
559 MutexGuard locked(lock);
560 if (void *P = EEState.getGlobalAddressMap()[GV])
563 // Global variable might have been added since interpreter started.
564 if (GlobalVariable *GVar =
565 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
566 EmitGlobalVariable(GVar);
568 llvm_unreachable("Global hasn't had an address allocated yet!");
570 return EEState.getGlobalAddressMap()[GV];
573 /// \brief Converts a Constant* into a GenericValue, including handling of
574 /// ConstantExpr values.
575 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
576 // If its undefined, return the garbage.
577 if (isa<UndefValue>(C)) {
579 switch (C->getType()->getTypeID()) {
582 case Type::IntegerTyID:
583 case Type::X86_FP80TyID:
584 case Type::FP128TyID:
585 case Type::PPC_FP128TyID:
586 // Although the value is undefined, we still have to construct an APInt
587 // with the correct bit width.
588 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
590 case Type::StructTyID: {
591 // if the whole struct is 'undef' just reserve memory for the value.
592 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
593 unsigned int elemNum = STy->getNumElements();
594 Result.AggregateVal.resize(elemNum);
595 for (unsigned int i = 0; i < elemNum; ++i) {
596 Type *ElemTy = STy->getElementType(i);
597 if (ElemTy->isIntegerTy())
598 Result.AggregateVal[i].IntVal =
599 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
600 else if (ElemTy->isAggregateType()) {
601 const Constant *ElemUndef = UndefValue::get(ElemTy);
602 Result.AggregateVal[i] = getConstantValue(ElemUndef);
608 case Type::VectorTyID:
609 // if the whole vector is 'undef' just reserve memory for the value.
610 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
611 const Type *ElemTy = VTy->getElementType();
612 unsigned int elemNum = VTy->getNumElements();
613 Result.AggregateVal.resize(elemNum);
614 if (ElemTy->isIntegerTy())
615 for (unsigned int i = 0; i < elemNum; ++i)
616 Result.AggregateVal[i].IntVal =
617 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
623 // Otherwise, if the value is a ConstantExpr...
624 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
625 Constant *Op0 = CE->getOperand(0);
626 switch (CE->getOpcode()) {
627 case Instruction::GetElementPtr: {
629 GenericValue Result = getConstantValue(Op0);
630 APInt Offset(DL->getPointerSizeInBits(), 0);
631 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
633 char* tmp = (char*) Result.PointerVal;
634 Result = PTOGV(tmp + Offset.getSExtValue());
637 case Instruction::Trunc: {
638 GenericValue GV = getConstantValue(Op0);
639 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
640 GV.IntVal = GV.IntVal.trunc(BitWidth);
643 case Instruction::ZExt: {
644 GenericValue GV = getConstantValue(Op0);
645 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
646 GV.IntVal = GV.IntVal.zext(BitWidth);
649 case Instruction::SExt: {
650 GenericValue GV = getConstantValue(Op0);
651 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
652 GV.IntVal = GV.IntVal.sext(BitWidth);
655 case Instruction::FPTrunc: {
657 GenericValue GV = getConstantValue(Op0);
658 GV.FloatVal = float(GV.DoubleVal);
661 case Instruction::FPExt:{
663 GenericValue GV = getConstantValue(Op0);
664 GV.DoubleVal = double(GV.FloatVal);
667 case Instruction::UIToFP: {
668 GenericValue GV = getConstantValue(Op0);
669 if (CE->getType()->isFloatTy())
670 GV.FloatVal = float(GV.IntVal.roundToDouble());
671 else if (CE->getType()->isDoubleTy())
672 GV.DoubleVal = GV.IntVal.roundToDouble();
673 else if (CE->getType()->isX86_FP80Ty()) {
674 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
675 (void)apf.convertFromAPInt(GV.IntVal,
677 APFloat::rmNearestTiesToEven);
678 GV.IntVal = apf.bitcastToAPInt();
682 case Instruction::SIToFP: {
683 GenericValue GV = getConstantValue(Op0);
684 if (CE->getType()->isFloatTy())
685 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
686 else if (CE->getType()->isDoubleTy())
687 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
688 else if (CE->getType()->isX86_FP80Ty()) {
689 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
690 (void)apf.convertFromAPInt(GV.IntVal,
692 APFloat::rmNearestTiesToEven);
693 GV.IntVal = apf.bitcastToAPInt();
697 case Instruction::FPToUI: // double->APInt conversion handles sign
698 case Instruction::FPToSI: {
699 GenericValue GV = getConstantValue(Op0);
700 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
701 if (Op0->getType()->isFloatTy())
702 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
703 else if (Op0->getType()->isDoubleTy())
704 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
705 else if (Op0->getType()->isX86_FP80Ty()) {
706 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
709 (void)apf.convertToInteger(&v, BitWidth,
710 CE->getOpcode()==Instruction::FPToSI,
711 APFloat::rmTowardZero, &ignored);
712 GV.IntVal = v; // endian?
716 case Instruction::PtrToInt: {
717 GenericValue GV = getConstantValue(Op0);
718 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
719 assert(PtrWidth <= 64 && "Bad pointer width");
720 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
721 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
722 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
725 case Instruction::IntToPtr: {
726 GenericValue GV = getConstantValue(Op0);
727 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
728 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
729 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
730 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
733 case Instruction::BitCast: {
734 GenericValue GV = getConstantValue(Op0);
735 Type* DestTy = CE->getType();
736 switch (Op0->getType()->getTypeID()) {
737 default: llvm_unreachable("Invalid bitcast operand");
738 case Type::IntegerTyID:
739 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
740 if (DestTy->isFloatTy())
741 GV.FloatVal = GV.IntVal.bitsToFloat();
742 else if (DestTy->isDoubleTy())
743 GV.DoubleVal = GV.IntVal.bitsToDouble();
745 case Type::FloatTyID:
746 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
747 GV.IntVal = APInt::floatToBits(GV.FloatVal);
749 case Type::DoubleTyID:
750 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
751 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
753 case Type::PointerTyID:
754 assert(DestTy->isPointerTy() && "Invalid bitcast");
755 break; // getConstantValue(Op0) above already converted it
759 case Instruction::Add:
760 case Instruction::FAdd:
761 case Instruction::Sub:
762 case Instruction::FSub:
763 case Instruction::Mul:
764 case Instruction::FMul:
765 case Instruction::UDiv:
766 case Instruction::SDiv:
767 case Instruction::URem:
768 case Instruction::SRem:
769 case Instruction::And:
770 case Instruction::Or:
771 case Instruction::Xor: {
772 GenericValue LHS = getConstantValue(Op0);
773 GenericValue RHS = getConstantValue(CE->getOperand(1));
775 switch (CE->getOperand(0)->getType()->getTypeID()) {
776 default: llvm_unreachable("Bad add type!");
777 case Type::IntegerTyID:
778 switch (CE->getOpcode()) {
779 default: llvm_unreachable("Invalid integer opcode");
780 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
781 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
782 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
783 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
784 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
785 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
786 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
787 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
788 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
789 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
792 case Type::FloatTyID:
793 switch (CE->getOpcode()) {
794 default: llvm_unreachable("Invalid float opcode");
795 case Instruction::FAdd:
796 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
797 case Instruction::FSub:
798 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
799 case Instruction::FMul:
800 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
801 case Instruction::FDiv:
802 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
803 case Instruction::FRem:
804 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
807 case Type::DoubleTyID:
808 switch (CE->getOpcode()) {
809 default: llvm_unreachable("Invalid double opcode");
810 case Instruction::FAdd:
811 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
812 case Instruction::FSub:
813 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
814 case Instruction::FMul:
815 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
816 case Instruction::FDiv:
817 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
818 case Instruction::FRem:
819 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
822 case Type::X86_FP80TyID:
823 case Type::PPC_FP128TyID:
824 case Type::FP128TyID: {
825 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
826 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
827 switch (CE->getOpcode()) {
828 default: llvm_unreachable("Invalid long double opcode");
829 case Instruction::FAdd:
830 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
831 GV.IntVal = apfLHS.bitcastToAPInt();
833 case Instruction::FSub:
834 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
835 APFloat::rmNearestTiesToEven);
836 GV.IntVal = apfLHS.bitcastToAPInt();
838 case Instruction::FMul:
839 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
840 APFloat::rmNearestTiesToEven);
841 GV.IntVal = apfLHS.bitcastToAPInt();
843 case Instruction::FDiv:
844 apfLHS.divide(APFloat(Sem, RHS.IntVal),
845 APFloat::rmNearestTiesToEven);
846 GV.IntVal = apfLHS.bitcastToAPInt();
848 case Instruction::FRem:
849 apfLHS.mod(APFloat(Sem, RHS.IntVal),
850 APFloat::rmNearestTiesToEven);
851 GV.IntVal = apfLHS.bitcastToAPInt();
863 SmallString<256> Msg;
864 raw_svector_ostream OS(Msg);
865 OS << "ConstantExpr not handled: " << *CE;
866 report_fatal_error(OS.str());
869 // Otherwise, we have a simple constant.
871 switch (C->getType()->getTypeID()) {
872 case Type::FloatTyID:
873 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
875 case Type::DoubleTyID:
876 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
878 case Type::X86_FP80TyID:
879 case Type::FP128TyID:
880 case Type::PPC_FP128TyID:
881 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
883 case Type::IntegerTyID:
884 Result.IntVal = cast<ConstantInt>(C)->getValue();
886 case Type::PointerTyID:
887 if (isa<ConstantPointerNull>(C))
888 Result.PointerVal = nullptr;
889 else if (const Function *F = dyn_cast<Function>(C))
890 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
891 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
892 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
893 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
894 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
895 BA->getBasicBlock())));
897 llvm_unreachable("Unknown constant pointer type!");
899 case Type::VectorTyID: {
902 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
903 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
904 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
907 elemNum = CDV->getNumElements();
908 ElemTy = CDV->getElementType();
909 } else if (CV || CAZ) {
910 VectorType* VTy = dyn_cast<VectorType>(C->getType());
911 elemNum = VTy->getNumElements();
912 ElemTy = VTy->getElementType();
914 llvm_unreachable("Unknown constant vector type!");
917 Result.AggregateVal.resize(elemNum);
918 // Check if vector holds floats.
919 if(ElemTy->isFloatTy()) {
921 GenericValue floatZero;
922 floatZero.FloatVal = 0.f;
923 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
928 for (unsigned i = 0; i < elemNum; ++i)
929 if (!isa<UndefValue>(CV->getOperand(i)))
930 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
931 CV->getOperand(i))->getValueAPF().convertToFloat();
935 for (unsigned i = 0; i < elemNum; ++i)
936 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
940 // Check if vector holds doubles.
941 if (ElemTy->isDoubleTy()) {
943 GenericValue doubleZero;
944 doubleZero.DoubleVal = 0.0;
945 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
950 for (unsigned i = 0; i < elemNum; ++i)
951 if (!isa<UndefValue>(CV->getOperand(i)))
952 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
953 CV->getOperand(i))->getValueAPF().convertToDouble();
957 for (unsigned i = 0; i < elemNum; ++i)
958 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
962 // Check if vector holds integers.
963 if (ElemTy->isIntegerTy()) {
965 GenericValue intZero;
966 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
967 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
972 for (unsigned i = 0; i < elemNum; ++i)
973 if (!isa<UndefValue>(CV->getOperand(i)))
974 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
975 CV->getOperand(i))->getValue();
977 Result.AggregateVal[i].IntVal =
978 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
983 for (unsigned i = 0; i < elemNum; ++i)
984 Result.AggregateVal[i].IntVal = APInt(
985 CDV->getElementType()->getPrimitiveSizeInBits(),
986 CDV->getElementAsInteger(i));
990 llvm_unreachable("Unknown constant pointer type!");
995 SmallString<256> Msg;
996 raw_svector_ostream OS(Msg);
997 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
998 report_fatal_error(OS.str());
1004 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1005 /// with the integer held in IntVal.
1006 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1007 unsigned StoreBytes) {
1008 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1009 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1011 if (sys::IsLittleEndianHost) {
1012 // Little-endian host - the source is ordered from LSB to MSB. Order the
1013 // destination from LSB to MSB: Do a straight copy.
1014 memcpy(Dst, Src, StoreBytes);
1016 // Big-endian host - the source is an array of 64 bit words ordered from
1017 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1018 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1019 while (StoreBytes > sizeof(uint64_t)) {
1020 StoreBytes -= sizeof(uint64_t);
1021 // May not be aligned so use memcpy.
1022 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1023 Src += sizeof(uint64_t);
1026 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1030 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1031 GenericValue *Ptr, Type *Ty) {
1032 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1034 switch (Ty->getTypeID()) {
1036 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1038 case Type::IntegerTyID:
1039 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1041 case Type::FloatTyID:
1042 *((float*)Ptr) = Val.FloatVal;
1044 case Type::DoubleTyID:
1045 *((double*)Ptr) = Val.DoubleVal;
1047 case Type::X86_FP80TyID:
1048 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1050 case Type::PointerTyID:
1051 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1052 if (StoreBytes != sizeof(PointerTy))
1053 memset(&(Ptr->PointerVal), 0, StoreBytes);
1055 *((PointerTy*)Ptr) = Val.PointerVal;
1057 case Type::VectorTyID:
1058 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1059 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1060 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1061 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1062 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1063 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1064 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1065 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1066 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1072 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1073 // Host and target are different endian - reverse the stored bytes.
1074 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1077 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1078 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1079 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1080 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1081 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1082 const_cast<uint64_t *>(IntVal.getRawData()));
1084 if (sys::IsLittleEndianHost)
1085 // Little-endian host - the destination must be ordered from LSB to MSB.
1086 // The source is ordered from LSB to MSB: Do a straight copy.
1087 memcpy(Dst, Src, LoadBytes);
1089 // Big-endian - the destination is an array of 64 bit words ordered from
1090 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1091 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1093 while (LoadBytes > sizeof(uint64_t)) {
1094 LoadBytes -= sizeof(uint64_t);
1095 // May not be aligned so use memcpy.
1096 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1097 Dst += sizeof(uint64_t);
1100 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1106 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1109 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1111 switch (Ty->getTypeID()) {
1112 case Type::IntegerTyID:
1113 // An APInt with all words initially zero.
1114 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1115 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1117 case Type::FloatTyID:
1118 Result.FloatVal = *((float*)Ptr);
1120 case Type::DoubleTyID:
1121 Result.DoubleVal = *((double*)Ptr);
1123 case Type::PointerTyID:
1124 Result.PointerVal = *((PointerTy*)Ptr);
1126 case Type::X86_FP80TyID: {
1127 // This is endian dependent, but it will only work on x86 anyway.
1128 // FIXME: Will not trap if loading a signaling NaN.
1131 Result.IntVal = APInt(80, y);
1134 case Type::VectorTyID: {
1135 const VectorType *VT = cast<VectorType>(Ty);
1136 const Type *ElemT = VT->getElementType();
1137 const unsigned numElems = VT->getNumElements();
1138 if (ElemT->isFloatTy()) {
1139 Result.AggregateVal.resize(numElems);
1140 for (unsigned i = 0; i < numElems; ++i)
1141 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1143 if (ElemT->isDoubleTy()) {
1144 Result.AggregateVal.resize(numElems);
1145 for (unsigned i = 0; i < numElems; ++i)
1146 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1148 if (ElemT->isIntegerTy()) {
1149 GenericValue intZero;
1150 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1151 intZero.IntVal = APInt(elemBitWidth, 0);
1152 Result.AggregateVal.resize(numElems, intZero);
1153 for (unsigned i = 0; i < numElems; ++i)
1154 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1155 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1160 SmallString<256> Msg;
1161 raw_svector_ostream OS(Msg);
1162 OS << "Cannot load value of type " << *Ty << "!";
1163 report_fatal_error(OS.str());
1167 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1168 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1169 DEBUG(Init->dump());
1170 if (isa<UndefValue>(Init))
1173 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1174 unsigned ElementSize =
1175 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1176 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1177 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1181 if (isa<ConstantAggregateZero>(Init)) {
1182 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1186 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1187 unsigned ElementSize =
1188 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1189 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1190 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1194 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1195 const StructLayout *SL =
1196 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1197 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1198 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1202 if (const ConstantDataSequential *CDS =
1203 dyn_cast<ConstantDataSequential>(Init)) {
1204 // CDS is already laid out in host memory order.
1205 StringRef Data = CDS->getRawDataValues();
1206 memcpy(Addr, Data.data(), Data.size());
1210 if (Init->getType()->isFirstClassType()) {
1211 GenericValue Val = getConstantValue(Init);
1212 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1216 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1217 llvm_unreachable("Unknown constant type to initialize memory with!");
1220 /// EmitGlobals - Emit all of the global variables to memory, storing their
1221 /// addresses into GlobalAddress. This must make sure to copy the contents of
1222 /// their initializers into the memory.
1223 void ExecutionEngine::emitGlobals() {
1224 // Loop over all of the global variables in the program, allocating the memory
1225 // to hold them. If there is more than one module, do a prepass over globals
1226 // to figure out how the different modules should link together.
1227 std::map<std::pair<std::string, Type*>,
1228 const GlobalValue*> LinkedGlobalsMap;
1230 if (Modules.size() != 1) {
1231 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1232 Module &M = *Modules[m];
1233 for (const auto &GV : M.globals()) {
1234 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1235 GV.hasAppendingLinkage() || !GV.hasName())
1236 continue;// Ignore external globals and globals with internal linkage.
1238 const GlobalValue *&GVEntry =
1239 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1241 // If this is the first time we've seen this global, it is the canonical
1248 // If the existing global is strong, never replace it.
1249 if (GVEntry->hasExternalLinkage())
1252 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1253 // symbol. FIXME is this right for common?
1254 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1260 std::vector<const GlobalValue*> NonCanonicalGlobals;
1261 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1262 Module &M = *Modules[m];
1263 for (const auto &GV : M.globals()) {
1264 // In the multi-module case, see what this global maps to.
1265 if (!LinkedGlobalsMap.empty()) {
1266 if (const GlobalValue *GVEntry =
1267 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1268 // If something else is the canonical global, ignore this one.
1269 if (GVEntry != &GV) {
1270 NonCanonicalGlobals.push_back(&GV);
1276 if (!GV.isDeclaration()) {
1277 addGlobalMapping(&GV, getMemoryForGV(&GV));
1279 // External variable reference. Try to use the dynamic loader to
1280 // get a pointer to it.
1282 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1283 addGlobalMapping(&GV, SymAddr);
1285 report_fatal_error("Could not resolve external global address: "
1291 // If there are multiple modules, map the non-canonical globals to their
1292 // canonical location.
1293 if (!NonCanonicalGlobals.empty()) {
1294 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1295 const GlobalValue *GV = NonCanonicalGlobals[i];
1296 const GlobalValue *CGV =
1297 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1298 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1299 assert(Ptr && "Canonical global wasn't codegen'd!");
1300 addGlobalMapping(GV, Ptr);
1304 // Now that all of the globals are set up in memory, loop through them all
1305 // and initialize their contents.
1306 for (const auto &GV : M.globals()) {
1307 if (!GV.isDeclaration()) {
1308 if (!LinkedGlobalsMap.empty()) {
1309 if (const GlobalValue *GVEntry =
1310 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1311 if (GVEntry != &GV) // Not the canonical variable.
1314 EmitGlobalVariable(&GV);
1320 // EmitGlobalVariable - This method emits the specified global variable to the
1321 // address specified in GlobalAddresses, or allocates new memory if it's not
1322 // already in the map.
1323 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1324 void *GA = getPointerToGlobalIfAvailable(GV);
1327 // If it's not already specified, allocate memory for the global.
1328 GA = getMemoryForGV(GV);
1330 // If we failed to allocate memory for this global, return.
1333 addGlobalMapping(GV, GA);
1336 // Don't initialize if it's thread local, let the client do it.
1337 if (!GV->isThreadLocal())
1338 InitializeMemory(GV->getInitializer(), GA);
1340 Type *ElTy = GV->getType()->getElementType();
1341 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1342 NumInitBytes += (unsigned)GVSize;
1346 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1347 : EE(EE), GlobalAddressMap(this) {
1351 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1352 return &EES->EE.lock;
1355 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1356 const GlobalValue *Old) {
1357 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1358 EES->GlobalAddressReverseMap.erase(OldVal);
1361 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1362 const GlobalValue *,
1363 const GlobalValue *) {
1364 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1365 " RAUW on a value it has a global mapping for.");