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 MutexGuard &,
152 const GlobalValue *ToUnmap) {
153 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
156 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
158 if (I == GlobalAddressMap.end())
162 GlobalAddressMap.erase(I);
165 GlobalAddressReverseMap.erase(OldVal);
169 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
170 MutexGuard locked(lock);
172 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
173 << "\' to [" << Addr << "]\n";);
174 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
175 assert((!CurVal || !Addr) && "GlobalMapping already established!");
178 // If we are using the reverse mapping, add it too.
179 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
180 AssertingVH<const GlobalValue> &V =
181 EEState.getGlobalAddressReverseMap(locked)[Addr];
182 assert((!V || !GV) && "GlobalMapping already established!");
187 void ExecutionEngine::clearAllGlobalMappings() {
188 MutexGuard locked(lock);
190 EEState.getGlobalAddressMap(locked).clear();
191 EEState.getGlobalAddressReverseMap(locked).clear();
194 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
195 MutexGuard locked(lock);
197 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
198 EEState.RemoveMapping(locked, FI);
199 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
201 EEState.RemoveMapping(locked, GI);
204 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
205 MutexGuard locked(lock);
207 ExecutionEngineState::GlobalAddressMapTy &Map =
208 EEState.getGlobalAddressMap(locked);
210 // Deleting from the mapping?
212 return EEState.RemoveMapping(locked, GV);
214 void *&CurVal = Map[GV];
215 void *OldVal = CurVal;
217 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
218 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
221 // If we are using the reverse mapping, add it too.
222 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
223 AssertingVH<const GlobalValue> &V =
224 EEState.getGlobalAddressReverseMap(locked)[Addr];
225 assert((!V || !GV) && "GlobalMapping already established!");
231 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
232 MutexGuard locked(lock);
234 ExecutionEngineState::GlobalAddressMapTy::iterator I =
235 EEState.getGlobalAddressMap(locked).find(GV);
236 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
239 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
240 MutexGuard locked(lock);
242 // If we haven't computed the reverse mapping yet, do so first.
243 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
244 for (ExecutionEngineState::GlobalAddressMapTy::iterator
245 I = EEState.getGlobalAddressMap(locked).begin(),
246 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
247 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
248 I->second, I->first));
251 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
252 EEState.getGlobalAddressReverseMap(locked).find(Addr);
253 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
259 std::vector<char*> Values;
261 ArgvArray() : Array(nullptr) {}
262 ~ArgvArray() { clear(); }
266 for (size_t I = 0, E = Values.size(); I != E; ++I) {
271 /// Turn a vector of strings into a nice argv style array of pointers to null
272 /// terminated strings.
273 void *reset(LLVMContext &C, ExecutionEngine *EE,
274 const std::vector<std::string> &InputArgv);
276 } // anonymous namespace
277 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
278 const std::vector<std::string> &InputArgv) {
279 clear(); // Free the old contents.
280 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
281 Array = new char[(InputArgv.size()+1)*PtrSize];
283 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
284 Type *SBytePtr = Type::getInt8PtrTy(C);
286 for (unsigned i = 0; i != InputArgv.size(); ++i) {
287 unsigned Size = InputArgv[i].size()+1;
288 char *Dest = new char[Size];
289 Values.push_back(Dest);
290 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
292 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
295 // Endian safe: Array[i] = (PointerTy)Dest;
296 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
301 EE->StoreValueToMemory(PTOGV(nullptr),
302 (GenericValue*)(Array+InputArgv.size()*PtrSize),
307 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
309 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
310 GlobalVariable *GV = module->getNamedGlobal(Name);
312 // If this global has internal linkage, or if it has a use, then it must be
313 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
314 // this is the case, don't execute any of the global ctors, __main will do
316 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
318 // Should be an array of '{ i32, void ()* }' structs. The first value is
319 // the init priority, which we ignore.
320 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
323 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
324 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
327 Constant *FP = CS->getOperand(1);
328 if (FP->isNullValue())
329 continue; // Found a sentinal value, ignore.
331 // Strip off constant expression casts.
332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
334 FP = CE->getOperand(0);
336 // Execute the ctor/dtor function!
337 if (Function *F = dyn_cast<Function>(FP))
338 runFunction(F, std::vector<GenericValue>());
340 // FIXME: It is marginally lame that we just do nothing here if we see an
341 // entry we don't recognize. It might not be unreasonable for the verifier
342 // to not even allow this and just assert here.
346 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
347 // Execute global ctors/dtors for each module in the program.
348 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
349 runStaticConstructorsDestructors(Modules[i], isDtors);
353 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
354 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
355 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
356 for (unsigned i = 0; i < PtrSize; ++i)
357 if (*(i + (uint8_t*)Loc))
363 int ExecutionEngine::runFunctionAsMain(Function *Fn,
364 const std::vector<std::string> &argv,
365 const char * const * envp) {
366 std::vector<GenericValue> GVArgs;
368 GVArgc.IntVal = APInt(32, argv.size());
371 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
372 FunctionType *FTy = Fn->getFunctionType();
373 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
375 // Check the argument types.
377 report_fatal_error("Invalid number of arguments of main() supplied");
378 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
379 report_fatal_error("Invalid type for third argument of main() supplied");
380 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
381 report_fatal_error("Invalid type for second argument of main() supplied");
382 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
383 report_fatal_error("Invalid type for first argument of main() supplied");
384 if (!FTy->getReturnType()->isIntegerTy() &&
385 !FTy->getReturnType()->isVoidTy())
386 report_fatal_error("Invalid return type of main() supplied");
391 GVArgs.push_back(GVArgc); // Arg #0 = argc.
394 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
395 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
396 "argv[0] was null after CreateArgv");
398 std::vector<std::string> EnvVars;
399 for (unsigned i = 0; envp[i]; ++i)
400 EnvVars.push_back(envp[i]);
402 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
407 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
410 ExecutionEngine *ExecutionEngine::create(Module *M,
411 bool ForceInterpreter,
412 std::string *ErrorStr,
413 CodeGenOpt::Level OptLevel,
415 EngineBuilder EB = EngineBuilder(M)
416 .setEngineKind(ForceInterpreter
417 ? EngineKind::Interpreter
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 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
461 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
463 // Make sure we can resolve symbols in the program as well. The zero arg
464 // to the function tells DynamicLibrary to load the program, not a library.
465 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
468 assert(!(JMM && MCJMM));
470 // If the user specified a memory manager but didn't specify which engine to
471 // create, we assume they only want the JIT, and we fail if they only want
474 if (WhichEngine & EngineKind::JIT)
475 WhichEngine = EngineKind::JIT;
478 *ErrorStr = "Cannot create an interpreter with a memory manager.";
483 if (MCJMM && ! UseMCJIT) {
486 "Cannot create a legacy JIT with a runtime dyld memory "
491 // Unless the interpreter was explicitly selected or the JIT is not linked,
493 if ((WhichEngine & EngineKind::JIT) && TheTM) {
494 Triple TT(M->getTargetTriple());
495 if (!TM->getTarget().hasJIT()) {
496 errs() << "WARNING: This target JIT is not designed for the host"
497 << " you are running. If bad things happen, please choose"
498 << " a different -march switch.\n";
501 ExecutionEngine *EE = nullptr;
502 if (UseMCJIT && ExecutionEngine::MCJITCtor)
503 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
504 AllocateGVsWithCode, TheTM.release());
505 else if (ExecutionEngine::JITCtor)
506 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
507 AllocateGVsWithCode, TheTM.release());
510 EE->setVerifyModules(VerifyModules);
515 // If we can't make a JIT and we didn't request one specifically, try making
516 // an interpreter instead.
517 if (WhichEngine & EngineKind::Interpreter) {
518 if (ExecutionEngine::InterpCtor)
519 return ExecutionEngine::InterpCtor(M, ErrorStr);
521 *ErrorStr = "Interpreter has not been linked in.";
525 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
526 !ExecutionEngine::MCJITCtor) {
528 *ErrorStr = "JIT has not been linked in.";
534 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
535 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
536 return getPointerToFunction(F);
538 MutexGuard locked(lock);
539 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
542 // Global variable might have been added since interpreter started.
543 if (GlobalVariable *GVar =
544 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
545 EmitGlobalVariable(GVar);
547 llvm_unreachable("Global hasn't had an address allocated yet!");
549 return EEState.getGlobalAddressMap(locked)[GV];
552 /// \brief Converts a Constant* into a GenericValue, including handling of
553 /// ConstantExpr values.
554 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
555 // If its undefined, return the garbage.
556 if (isa<UndefValue>(C)) {
558 switch (C->getType()->getTypeID()) {
561 case Type::IntegerTyID:
562 case Type::X86_FP80TyID:
563 case Type::FP128TyID:
564 case Type::PPC_FP128TyID:
565 // Although the value is undefined, we still have to construct an APInt
566 // with the correct bit width.
567 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
569 case Type::StructTyID: {
570 // if the whole struct is 'undef' just reserve memory for the value.
571 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
572 unsigned int elemNum = STy->getNumElements();
573 Result.AggregateVal.resize(elemNum);
574 for (unsigned int i = 0; i < elemNum; ++i) {
575 Type *ElemTy = STy->getElementType(i);
576 if (ElemTy->isIntegerTy())
577 Result.AggregateVal[i].IntVal =
578 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
579 else if (ElemTy->isAggregateType()) {
580 const Constant *ElemUndef = UndefValue::get(ElemTy);
581 Result.AggregateVal[i] = getConstantValue(ElemUndef);
587 case Type::VectorTyID:
588 // if the whole vector is 'undef' just reserve memory for the value.
589 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
590 const Type *ElemTy = VTy->getElementType();
591 unsigned int elemNum = VTy->getNumElements();
592 Result.AggregateVal.resize(elemNum);
593 if (ElemTy->isIntegerTy())
594 for (unsigned int i = 0; i < elemNum; ++i)
595 Result.AggregateVal[i].IntVal =
596 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
602 // Otherwise, if the value is a ConstantExpr...
603 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
604 Constant *Op0 = CE->getOperand(0);
605 switch (CE->getOpcode()) {
606 case Instruction::GetElementPtr: {
608 GenericValue Result = getConstantValue(Op0);
609 APInt Offset(DL->getPointerSizeInBits(), 0);
610 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
612 char* tmp = (char*) Result.PointerVal;
613 Result = PTOGV(tmp + Offset.getSExtValue());
616 case Instruction::Trunc: {
617 GenericValue GV = getConstantValue(Op0);
618 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
619 GV.IntVal = GV.IntVal.trunc(BitWidth);
622 case Instruction::ZExt: {
623 GenericValue GV = getConstantValue(Op0);
624 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
625 GV.IntVal = GV.IntVal.zext(BitWidth);
628 case Instruction::SExt: {
629 GenericValue GV = getConstantValue(Op0);
630 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
631 GV.IntVal = GV.IntVal.sext(BitWidth);
634 case Instruction::FPTrunc: {
636 GenericValue GV = getConstantValue(Op0);
637 GV.FloatVal = float(GV.DoubleVal);
640 case Instruction::FPExt:{
642 GenericValue GV = getConstantValue(Op0);
643 GV.DoubleVal = double(GV.FloatVal);
646 case Instruction::UIToFP: {
647 GenericValue GV = getConstantValue(Op0);
648 if (CE->getType()->isFloatTy())
649 GV.FloatVal = float(GV.IntVal.roundToDouble());
650 else if (CE->getType()->isDoubleTy())
651 GV.DoubleVal = GV.IntVal.roundToDouble();
652 else if (CE->getType()->isX86_FP80Ty()) {
653 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
654 (void)apf.convertFromAPInt(GV.IntVal,
656 APFloat::rmNearestTiesToEven);
657 GV.IntVal = apf.bitcastToAPInt();
661 case Instruction::SIToFP: {
662 GenericValue GV = getConstantValue(Op0);
663 if (CE->getType()->isFloatTy())
664 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
665 else if (CE->getType()->isDoubleTy())
666 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
667 else if (CE->getType()->isX86_FP80Ty()) {
668 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
669 (void)apf.convertFromAPInt(GV.IntVal,
671 APFloat::rmNearestTiesToEven);
672 GV.IntVal = apf.bitcastToAPInt();
676 case Instruction::FPToUI: // double->APInt conversion handles sign
677 case Instruction::FPToSI: {
678 GenericValue GV = getConstantValue(Op0);
679 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
680 if (Op0->getType()->isFloatTy())
681 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
682 else if (Op0->getType()->isDoubleTy())
683 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
684 else if (Op0->getType()->isX86_FP80Ty()) {
685 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
688 (void)apf.convertToInteger(&v, BitWidth,
689 CE->getOpcode()==Instruction::FPToSI,
690 APFloat::rmTowardZero, &ignored);
691 GV.IntVal = v; // endian?
695 case Instruction::PtrToInt: {
696 GenericValue GV = getConstantValue(Op0);
697 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
698 assert(PtrWidth <= 64 && "Bad pointer width");
699 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
700 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
701 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
704 case Instruction::IntToPtr: {
705 GenericValue GV = getConstantValue(Op0);
706 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
707 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
708 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
709 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
712 case Instruction::BitCast: {
713 GenericValue GV = getConstantValue(Op0);
714 Type* DestTy = CE->getType();
715 switch (Op0->getType()->getTypeID()) {
716 default: llvm_unreachable("Invalid bitcast operand");
717 case Type::IntegerTyID:
718 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
719 if (DestTy->isFloatTy())
720 GV.FloatVal = GV.IntVal.bitsToFloat();
721 else if (DestTy->isDoubleTy())
722 GV.DoubleVal = GV.IntVal.bitsToDouble();
724 case Type::FloatTyID:
725 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
726 GV.IntVal = APInt::floatToBits(GV.FloatVal);
728 case Type::DoubleTyID:
729 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
730 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
732 case Type::PointerTyID:
733 assert(DestTy->isPointerTy() && "Invalid bitcast");
734 break; // getConstantValue(Op0) above already converted it
738 case Instruction::Add:
739 case Instruction::FAdd:
740 case Instruction::Sub:
741 case Instruction::FSub:
742 case Instruction::Mul:
743 case Instruction::FMul:
744 case Instruction::UDiv:
745 case Instruction::SDiv:
746 case Instruction::URem:
747 case Instruction::SRem:
748 case Instruction::And:
749 case Instruction::Or:
750 case Instruction::Xor: {
751 GenericValue LHS = getConstantValue(Op0);
752 GenericValue RHS = getConstantValue(CE->getOperand(1));
754 switch (CE->getOperand(0)->getType()->getTypeID()) {
755 default: llvm_unreachable("Bad add type!");
756 case Type::IntegerTyID:
757 switch (CE->getOpcode()) {
758 default: llvm_unreachable("Invalid integer opcode");
759 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
760 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
761 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
762 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
763 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
764 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
765 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
766 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
767 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
768 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
771 case Type::FloatTyID:
772 switch (CE->getOpcode()) {
773 default: llvm_unreachable("Invalid float opcode");
774 case Instruction::FAdd:
775 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
776 case Instruction::FSub:
777 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
778 case Instruction::FMul:
779 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
780 case Instruction::FDiv:
781 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
782 case Instruction::FRem:
783 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
786 case Type::DoubleTyID:
787 switch (CE->getOpcode()) {
788 default: llvm_unreachable("Invalid double opcode");
789 case Instruction::FAdd:
790 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
791 case Instruction::FSub:
792 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
793 case Instruction::FMul:
794 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
795 case Instruction::FDiv:
796 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
797 case Instruction::FRem:
798 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
801 case Type::X86_FP80TyID:
802 case Type::PPC_FP128TyID:
803 case Type::FP128TyID: {
804 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
805 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
806 switch (CE->getOpcode()) {
807 default: llvm_unreachable("Invalid long double opcode");
808 case Instruction::FAdd:
809 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
810 GV.IntVal = apfLHS.bitcastToAPInt();
812 case Instruction::FSub:
813 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
814 APFloat::rmNearestTiesToEven);
815 GV.IntVal = apfLHS.bitcastToAPInt();
817 case Instruction::FMul:
818 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
819 APFloat::rmNearestTiesToEven);
820 GV.IntVal = apfLHS.bitcastToAPInt();
822 case Instruction::FDiv:
823 apfLHS.divide(APFloat(Sem, RHS.IntVal),
824 APFloat::rmNearestTiesToEven);
825 GV.IntVal = apfLHS.bitcastToAPInt();
827 case Instruction::FRem:
828 apfLHS.mod(APFloat(Sem, RHS.IntVal),
829 APFloat::rmNearestTiesToEven);
830 GV.IntVal = apfLHS.bitcastToAPInt();
842 SmallString<256> Msg;
843 raw_svector_ostream OS(Msg);
844 OS << "ConstantExpr not handled: " << *CE;
845 report_fatal_error(OS.str());
848 // Otherwise, we have a simple constant.
850 switch (C->getType()->getTypeID()) {
851 case Type::FloatTyID:
852 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
854 case Type::DoubleTyID:
855 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
857 case Type::X86_FP80TyID:
858 case Type::FP128TyID:
859 case Type::PPC_FP128TyID:
860 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
862 case Type::IntegerTyID:
863 Result.IntVal = cast<ConstantInt>(C)->getValue();
865 case Type::PointerTyID:
866 if (isa<ConstantPointerNull>(C))
867 Result.PointerVal = nullptr;
868 else if (const Function *F = dyn_cast<Function>(C))
869 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
870 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
871 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
872 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
873 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
874 BA->getBasicBlock())));
876 llvm_unreachable("Unknown constant pointer type!");
878 case Type::VectorTyID: {
881 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
882 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
883 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
886 elemNum = CDV->getNumElements();
887 ElemTy = CDV->getElementType();
888 } else if (CV || CAZ) {
889 VectorType* VTy = dyn_cast<VectorType>(C->getType());
890 elemNum = VTy->getNumElements();
891 ElemTy = VTy->getElementType();
893 llvm_unreachable("Unknown constant vector type!");
896 Result.AggregateVal.resize(elemNum);
897 // Check if vector holds floats.
898 if(ElemTy->isFloatTy()) {
900 GenericValue floatZero;
901 floatZero.FloatVal = 0.f;
902 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
907 for (unsigned i = 0; i < elemNum; ++i)
908 if (!isa<UndefValue>(CV->getOperand(i)))
909 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
910 CV->getOperand(i))->getValueAPF().convertToFloat();
914 for (unsigned i = 0; i < elemNum; ++i)
915 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
919 // Check if vector holds doubles.
920 if (ElemTy->isDoubleTy()) {
922 GenericValue doubleZero;
923 doubleZero.DoubleVal = 0.0;
924 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
929 for (unsigned i = 0; i < elemNum; ++i)
930 if (!isa<UndefValue>(CV->getOperand(i)))
931 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
932 CV->getOperand(i))->getValueAPF().convertToDouble();
936 for (unsigned i = 0; i < elemNum; ++i)
937 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
941 // Check if vector holds integers.
942 if (ElemTy->isIntegerTy()) {
944 GenericValue intZero;
945 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
946 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
951 for (unsigned i = 0; i < elemNum; ++i)
952 if (!isa<UndefValue>(CV->getOperand(i)))
953 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
954 CV->getOperand(i))->getValue();
956 Result.AggregateVal[i].IntVal =
957 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
962 for (unsigned i = 0; i < elemNum; ++i)
963 Result.AggregateVal[i].IntVal = APInt(
964 CDV->getElementType()->getPrimitiveSizeInBits(),
965 CDV->getElementAsInteger(i));
969 llvm_unreachable("Unknown constant pointer type!");
974 SmallString<256> Msg;
975 raw_svector_ostream OS(Msg);
976 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
977 report_fatal_error(OS.str());
983 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
984 /// with the integer held in IntVal.
985 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
986 unsigned StoreBytes) {
987 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
988 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
990 if (sys::IsLittleEndianHost) {
991 // Little-endian host - the source is ordered from LSB to MSB. Order the
992 // destination from LSB to MSB: Do a straight copy.
993 memcpy(Dst, Src, StoreBytes);
995 // Big-endian host - the source is an array of 64 bit words ordered from
996 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
997 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
998 while (StoreBytes > sizeof(uint64_t)) {
999 StoreBytes -= sizeof(uint64_t);
1000 // May not be aligned so use memcpy.
1001 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1002 Src += sizeof(uint64_t);
1005 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1009 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1010 GenericValue *Ptr, Type *Ty) {
1011 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1013 switch (Ty->getTypeID()) {
1015 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1017 case Type::IntegerTyID:
1018 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1020 case Type::FloatTyID:
1021 *((float*)Ptr) = Val.FloatVal;
1023 case Type::DoubleTyID:
1024 *((double*)Ptr) = Val.DoubleVal;
1026 case Type::X86_FP80TyID:
1027 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1029 case Type::PointerTyID:
1030 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1031 if (StoreBytes != sizeof(PointerTy))
1032 memset(&(Ptr->PointerVal), 0, StoreBytes);
1034 *((PointerTy*)Ptr) = Val.PointerVal;
1036 case Type::VectorTyID:
1037 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1038 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1039 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1040 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1041 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1042 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1043 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1044 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1045 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1051 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1052 // Host and target are different endian - reverse the stored bytes.
1053 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1056 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1057 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1058 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1059 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1060 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1061 const_cast<uint64_t *>(IntVal.getRawData()));
1063 if (sys::IsLittleEndianHost)
1064 // Little-endian host - the destination must be ordered from LSB to MSB.
1065 // The source is ordered from LSB to MSB: Do a straight copy.
1066 memcpy(Dst, Src, LoadBytes);
1068 // Big-endian - the destination is an array of 64 bit words ordered from
1069 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1070 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1072 while (LoadBytes > sizeof(uint64_t)) {
1073 LoadBytes -= sizeof(uint64_t);
1074 // May not be aligned so use memcpy.
1075 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1076 Dst += sizeof(uint64_t);
1079 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1085 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1088 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1090 switch (Ty->getTypeID()) {
1091 case Type::IntegerTyID:
1092 // An APInt with all words initially zero.
1093 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1094 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1096 case Type::FloatTyID:
1097 Result.FloatVal = *((float*)Ptr);
1099 case Type::DoubleTyID:
1100 Result.DoubleVal = *((double*)Ptr);
1102 case Type::PointerTyID:
1103 Result.PointerVal = *((PointerTy*)Ptr);
1105 case Type::X86_FP80TyID: {
1106 // This is endian dependent, but it will only work on x86 anyway.
1107 // FIXME: Will not trap if loading a signaling NaN.
1110 Result.IntVal = APInt(80, y);
1113 case Type::VectorTyID: {
1114 const VectorType *VT = cast<VectorType>(Ty);
1115 const Type *ElemT = VT->getElementType();
1116 const unsigned numElems = VT->getNumElements();
1117 if (ElemT->isFloatTy()) {
1118 Result.AggregateVal.resize(numElems);
1119 for (unsigned i = 0; i < numElems; ++i)
1120 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1122 if (ElemT->isDoubleTy()) {
1123 Result.AggregateVal.resize(numElems);
1124 for (unsigned i = 0; i < numElems; ++i)
1125 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1127 if (ElemT->isIntegerTy()) {
1128 GenericValue intZero;
1129 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1130 intZero.IntVal = APInt(elemBitWidth, 0);
1131 Result.AggregateVal.resize(numElems, intZero);
1132 for (unsigned i = 0; i < numElems; ++i)
1133 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1134 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1139 SmallString<256> Msg;
1140 raw_svector_ostream OS(Msg);
1141 OS << "Cannot load value of type " << *Ty << "!";
1142 report_fatal_error(OS.str());
1146 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1147 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1148 DEBUG(Init->dump());
1149 if (isa<UndefValue>(Init))
1152 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1153 unsigned ElementSize =
1154 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1155 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1156 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1160 if (isa<ConstantAggregateZero>(Init)) {
1161 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1165 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1166 unsigned ElementSize =
1167 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1168 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1169 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1173 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1174 const StructLayout *SL =
1175 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1176 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1177 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1181 if (const ConstantDataSequential *CDS =
1182 dyn_cast<ConstantDataSequential>(Init)) {
1183 // CDS is already laid out in host memory order.
1184 StringRef Data = CDS->getRawDataValues();
1185 memcpy(Addr, Data.data(), Data.size());
1189 if (Init->getType()->isFirstClassType()) {
1190 GenericValue Val = getConstantValue(Init);
1191 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1195 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1196 llvm_unreachable("Unknown constant type to initialize memory with!");
1199 /// EmitGlobals - Emit all of the global variables to memory, storing their
1200 /// addresses into GlobalAddress. This must make sure to copy the contents of
1201 /// their initializers into the memory.
1202 void ExecutionEngine::emitGlobals() {
1203 // Loop over all of the global variables in the program, allocating the memory
1204 // to hold them. If there is more than one module, do a prepass over globals
1205 // to figure out how the different modules should link together.
1206 std::map<std::pair<std::string, Type*>,
1207 const GlobalValue*> LinkedGlobalsMap;
1209 if (Modules.size() != 1) {
1210 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1211 Module &M = *Modules[m];
1212 for (Module::const_global_iterator I = M.global_begin(),
1213 E = M.global_end(); I != E; ++I) {
1214 const GlobalValue *GV = I;
1215 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1216 GV->hasAppendingLinkage() || !GV->hasName())
1217 continue;// Ignore external globals and globals with internal linkage.
1219 const GlobalValue *&GVEntry =
1220 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1222 // If this is the first time we've seen this global, it is the canonical
1229 // If the existing global is strong, never replace it.
1230 if (GVEntry->hasExternalLinkage())
1233 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1234 // symbol. FIXME is this right for common?
1235 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1241 std::vector<const GlobalValue*> NonCanonicalGlobals;
1242 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1243 Module &M = *Modules[m];
1244 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1246 // In the multi-module case, see what this global maps to.
1247 if (!LinkedGlobalsMap.empty()) {
1248 if (const GlobalValue *GVEntry =
1249 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1250 // If something else is the canonical global, ignore this one.
1251 if (GVEntry != &*I) {
1252 NonCanonicalGlobals.push_back(I);
1258 if (!I->isDeclaration()) {
1259 addGlobalMapping(I, getMemoryForGV(I));
1261 // External variable reference. Try to use the dynamic loader to
1262 // get a pointer to it.
1264 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1265 addGlobalMapping(I, SymAddr);
1267 report_fatal_error("Could not resolve external global address: "
1273 // If there are multiple modules, map the non-canonical globals to their
1274 // canonical location.
1275 if (!NonCanonicalGlobals.empty()) {
1276 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1277 const GlobalValue *GV = NonCanonicalGlobals[i];
1278 const GlobalValue *CGV =
1279 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1280 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1281 assert(Ptr && "Canonical global wasn't codegen'd!");
1282 addGlobalMapping(GV, Ptr);
1286 // Now that all of the globals are set up in memory, loop through them all
1287 // and initialize their contents.
1288 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1290 if (!I->isDeclaration()) {
1291 if (!LinkedGlobalsMap.empty()) {
1292 if (const GlobalValue *GVEntry =
1293 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1294 if (GVEntry != &*I) // Not the canonical variable.
1297 EmitGlobalVariable(I);
1303 // EmitGlobalVariable - This method emits the specified global variable to the
1304 // address specified in GlobalAddresses, or allocates new memory if it's not
1305 // already in the map.
1306 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1307 void *GA = getPointerToGlobalIfAvailable(GV);
1310 // If it's not already specified, allocate memory for the global.
1311 GA = getMemoryForGV(GV);
1313 // If we failed to allocate memory for this global, return.
1316 addGlobalMapping(GV, GA);
1319 // Don't initialize if it's thread local, let the client do it.
1320 if (!GV->isThreadLocal())
1321 InitializeMemory(GV->getInitializer(), GA);
1323 Type *ElTy = GV->getType()->getElementType();
1324 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1325 NumInitBytes += (unsigned)GVSize;
1329 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1330 : EE(EE), GlobalAddressMap(this) {
1334 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1335 return &EES->EE.lock;
1338 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1339 const GlobalValue *Old) {
1340 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1341 EES->GlobalAddressReverseMap.erase(OldVal);
1344 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1345 const GlobalValue *,
1346 const GlobalValue *) {
1347 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1348 " RAUW on a value it has a global mapping for.");