1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ExecutionEngine/JITMemoryManager.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ExecutionEngine/GenericValue.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/Support/Debug.h"
27 #include "llvm/Support/DynamicLibrary.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/MutexGuard.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/ValueHandle.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
39 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
40 STATISTIC(NumGlobals , "Number of global vars initialized");
42 ExecutionEngine *(*ExecutionEngine::JITCtor)(
44 std::string *ErrorStr,
45 JITMemoryManager *JMM,
47 TargetMachine *TM) = 0;
48 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 std::string *ErrorStr,
51 RTDyldMemoryManager *MCJMM,
53 TargetMachine *TM) = 0;
54 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55 std::string *ErrorStr) = 0;
57 ExecutionEngine::ExecutionEngine(Module *M)
59 LazyFunctionCreator(0),
60 ExceptionTableRegister(0),
61 ExceptionTableDeregister(0) {
62 CompilingLazily = false;
63 GVCompilationDisabled = false;
64 SymbolSearchingDisabled = false;
66 assert(M && "Module is null?");
69 ExecutionEngine::~ExecutionEngine() {
70 clearAllGlobalMappings();
71 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
75 void ExecutionEngine::DeregisterAllTables() {
76 if (ExceptionTableDeregister) {
77 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79 for (; it != ite; ++it)
80 ExceptionTableDeregister(it->second);
81 AllExceptionTables.clear();
86 /// \brief Helper class which uses a value handler to automatically deletes the
87 /// memory block when the GlobalVariable is destroyed.
88 class GVMemoryBlock : public CallbackVH {
89 GVMemoryBlock(const GlobalVariable *GV)
90 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
93 /// \brief Returns the address the GlobalVariable should be written into. The
94 /// GVMemoryBlock object prefixes that.
95 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
96 Type *ElTy = GV->getType()->getElementType();
97 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98 void *RawMemory = ::operator new(
99 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
100 TD.getPreferredAlignment(GV))
102 new(RawMemory) GVMemoryBlock(GV);
103 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
106 virtual void deleted() {
107 // We allocated with operator new and with some extra memory hanging off the
108 // end, so don't just delete this. I'm not sure if this is actually
110 this->~GVMemoryBlock();
111 ::operator delete(this);
114 } // anonymous namespace
116 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117 return GVMemoryBlock::Create(GV, *getDataLayout());
120 bool ExecutionEngine::removeModule(Module *M) {
121 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
122 E = Modules.end(); I != E; ++I) {
126 clearGlobalMappingsFromModule(M);
133 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
134 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135 if (Function *F = Modules[i]->getFunction(FnName))
142 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143 const GlobalValue *ToUnmap) {
144 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
147 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
149 if (I == GlobalAddressMap.end())
153 GlobalAddressMap.erase(I);
156 GlobalAddressReverseMap.erase(OldVal);
160 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161 MutexGuard locked(lock);
163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
164 << "\' to [" << Addr << "]\n";);
165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
169 // If we are using the reverse mapping, add it too.
170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
171 AssertingVH<const GlobalValue> &V =
172 EEState.getGlobalAddressReverseMap(locked)[Addr];
173 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
178 void ExecutionEngine::clearAllGlobalMappings() {
179 MutexGuard locked(lock);
181 EEState.getGlobalAddressMap(locked).clear();
182 EEState.getGlobalAddressReverseMap(locked).clear();
185 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
186 MutexGuard locked(lock);
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189 EEState.RemoveMapping(locked, FI);
190 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
192 EEState.RemoveMapping(locked, GI);
195 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
196 MutexGuard locked(lock);
198 ExecutionEngineState::GlobalAddressMapTy &Map =
199 EEState.getGlobalAddressMap(locked);
201 // Deleting from the mapping?
203 return EEState.RemoveMapping(locked, GV);
205 void *&CurVal = Map[GV];
206 void *OldVal = CurVal;
208 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
212 // If we are using the reverse mapping, add it too.
213 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
214 AssertingVH<const GlobalValue> &V =
215 EEState.getGlobalAddressReverseMap(locked)[Addr];
216 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
222 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
223 MutexGuard locked(lock);
225 ExecutionEngineState::GlobalAddressMapTy::iterator I =
226 EEState.getGlobalAddressMap(locked).find(GV);
227 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
230 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
231 MutexGuard locked(lock);
233 // If we haven't computed the reverse mapping yet, do so first.
234 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235 for (ExecutionEngineState::GlobalAddressMapTy::iterator
236 I = EEState.getGlobalAddressMap(locked).begin(),
237 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239 I->second, I->first));
242 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243 EEState.getGlobalAddressReverseMap(locked).find(Addr);
244 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
250 std::vector<char*> Values;
252 ArgvArray() : Array(NULL) {}
253 ~ArgvArray() { clear(); }
257 for (size_t I = 0, E = Values.size(); I != E; ++I) {
262 /// Turn a vector of strings into a nice argv style array of pointers to null
263 /// terminated strings.
264 void *reset(LLVMContext &C, ExecutionEngine *EE,
265 const std::vector<std::string> &InputArgv);
267 } // anonymous namespace
268 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv) {
270 clear(); // Free the old contents.
271 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
272 Array = new char[(InputArgv.size()+1)*PtrSize];
274 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275 Type *SBytePtr = Type::getInt8PtrTy(C);
277 for (unsigned i = 0; i != InputArgv.size(); ++i) {
278 unsigned Size = InputArgv[i].size()+1;
279 char *Dest = new char[Size];
280 Values.push_back(Dest);
281 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
283 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
286 // Endian safe: Array[i] = (PointerTy)Dest;
287 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
292 EE->StoreValueToMemory(PTOGV(0),
293 (GenericValue*)(Array+InputArgv.size()*PtrSize),
298 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
300 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
301 GlobalVariable *GV = module->getNamedGlobal(Name);
303 // If this global has internal linkage, or if it has a use, then it must be
304 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
305 // this is the case, don't execute any of the global ctors, __main will do
307 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
309 // Should be an array of '{ i32, void ()* }' structs. The first value is
310 // the init priority, which we ignore.
311 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
315 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
316 if (CS == 0) continue;
318 Constant *FP = CS->getOperand(1);
319 if (FP->isNullValue())
320 continue; // Found a sentinal value, ignore.
322 // Strip off constant expression casts.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
325 FP = CE->getOperand(0);
327 // Execute the ctor/dtor function!
328 if (Function *F = dyn_cast<Function>(FP))
329 runFunction(F, std::vector<GenericValue>());
331 // FIXME: It is marginally lame that we just do nothing here if we see an
332 // entry we don't recognize. It might not be unreasonable for the verifier
333 // to not even allow this and just assert here.
337 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
338 // Execute global ctors/dtors for each module in the program.
339 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
340 runStaticConstructorsDestructors(Modules[i], isDtors);
344 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
345 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
346 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
347 for (unsigned i = 0; i < PtrSize; ++i)
348 if (*(i + (uint8_t*)Loc))
354 int ExecutionEngine::runFunctionAsMain(Function *Fn,
355 const std::vector<std::string> &argv,
356 const char * const * envp) {
357 std::vector<GenericValue> GVArgs;
359 GVArgc.IntVal = APInt(32, argv.size());
362 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
363 FunctionType *FTy = Fn->getFunctionType();
364 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
366 // Check the argument types.
368 report_fatal_error("Invalid number of arguments of main() supplied");
369 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
370 report_fatal_error("Invalid type for third argument of main() supplied");
371 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
372 report_fatal_error("Invalid type for second argument of main() supplied");
373 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
374 report_fatal_error("Invalid type for first argument of main() supplied");
375 if (!FTy->getReturnType()->isIntegerTy() &&
376 !FTy->getReturnType()->isVoidTy())
377 report_fatal_error("Invalid return type of main() supplied");
382 GVArgs.push_back(GVArgc); // Arg #0 = argc.
385 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
386 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
387 "argv[0] was null after CreateArgv");
389 std::vector<std::string> EnvVars;
390 for (unsigned i = 0; envp[i]; ++i)
391 EnvVars.push_back(envp[i]);
393 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
398 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
401 ExecutionEngine *ExecutionEngine::create(Module *M,
402 bool ForceInterpreter,
403 std::string *ErrorStr,
404 CodeGenOpt::Level OptLevel,
406 EngineBuilder EB = EngineBuilder(M)
407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode);
417 /// createJIT - This is the factory method for creating a JIT for the current
418 /// machine, it does not fall back to the interpreter. This takes ownership
420 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
421 std::string *ErrorStr,
422 JITMemoryManager *JMM,
423 CodeGenOpt::Level OL,
426 CodeModel::Model CMM) {
427 if (ExecutionEngine::JITCtor == 0) {
429 *ErrorStr = "JIT has not been linked in.";
433 // Use the defaults for extra parameters. Users can use EngineBuilder to
436 EB.setEngineKind(EngineKind::JIT);
437 EB.setErrorStr(ErrorStr);
438 EB.setRelocationModel(RM);
439 EB.setCodeModel(CMM);
440 EB.setAllocateGVsWithCode(GVsWithCode);
442 EB.setJITMemoryManager(JMM);
444 // TODO: permit custom TargetOptions here
445 TargetMachine *TM = EB.selectTarget();
446 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
448 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
451 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
452 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
454 // Make sure we can resolve symbols in the program as well. The zero arg
455 // to the function tells DynamicLibrary to load the program, not a library.
456 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
459 assert(!(JMM && MCJMM));
461 // If the user specified a memory manager but didn't specify which engine to
462 // create, we assume they only want the JIT, and we fail if they only want
465 if (WhichEngine & EngineKind::JIT)
466 WhichEngine = EngineKind::JIT;
469 *ErrorStr = "Cannot create an interpreter with a memory manager.";
474 if (MCJMM && ! UseMCJIT) {
477 "Cannot create a legacy JIT with a runtime dyld memory "
482 // Unless the interpreter was explicitly selected or the JIT is not linked,
484 if ((WhichEngine & EngineKind::JIT) && TheTM) {
485 Triple TT(M->getTargetTriple());
486 if (!TM->getTarget().hasJIT()) {
487 errs() << "WARNING: This target JIT is not designed for the host"
488 << " you are running. If bad things happen, please choose"
489 << " a different -march switch.\n";
492 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
493 ExecutionEngine *EE =
494 ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
495 AllocateGVsWithCode, TheTM.take());
497 } else if (ExecutionEngine::JITCtor) {
498 ExecutionEngine *EE =
499 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
500 AllocateGVsWithCode, TheTM.take());
505 // If we can't make a JIT and we didn't request one specifically, try making
506 // an interpreter instead.
507 if (WhichEngine & EngineKind::Interpreter) {
508 if (ExecutionEngine::InterpCtor)
509 return ExecutionEngine::InterpCtor(M, ErrorStr);
511 *ErrorStr = "Interpreter has not been linked in.";
515 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
516 ExecutionEngine::MCJITCtor == 0) {
518 *ErrorStr = "JIT has not been linked in.";
524 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
525 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
526 return getPointerToFunction(F);
528 MutexGuard locked(lock);
529 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
532 // Global variable might have been added since interpreter started.
533 if (GlobalVariable *GVar =
534 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
535 EmitGlobalVariable(GVar);
537 llvm_unreachable("Global hasn't had an address allocated yet!");
539 return EEState.getGlobalAddressMap(locked)[GV];
542 /// \brief Converts a Constant* into a GenericValue, including handling of
543 /// ConstantExpr values.
544 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
545 // If its undefined, return the garbage.
546 if (isa<UndefValue>(C)) {
548 switch (C->getType()->getTypeID()) {
551 case Type::IntegerTyID:
552 case Type::X86_FP80TyID:
553 case Type::FP128TyID:
554 case Type::PPC_FP128TyID:
555 // Although the value is undefined, we still have to construct an APInt
556 // with the correct bit width.
557 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
559 case Type::StructTyID: {
560 // if the whole struct is 'undef' just reserve memory for the value.
561 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
562 unsigned int elemNum = STy->getNumElements();
563 Result.AggregateVal.resize(elemNum);
564 for (unsigned int i = 0; i < elemNum; ++i) {
565 Type *ElemTy = STy->getElementType(i);
566 if (ElemTy->isIntegerTy())
567 Result.AggregateVal[i].IntVal =
568 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
569 else if (ElemTy->isAggregateType()) {
570 const Constant *ElemUndef = UndefValue::get(ElemTy);
571 Result.AggregateVal[i] = getConstantValue(ElemUndef);
577 case Type::VectorTyID:
578 // if the whole vector is 'undef' just reserve memory for the value.
579 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
580 const Type *ElemTy = VTy->getElementType();
581 unsigned int elemNum = VTy->getNumElements();
582 Result.AggregateVal.resize(elemNum);
583 if (ElemTy->isIntegerTy())
584 for (unsigned int i = 0; i < elemNum; ++i)
585 Result.AggregateVal[i].IntVal =
586 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
592 // Otherwise, if the value is a ConstantExpr...
593 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
594 Constant *Op0 = CE->getOperand(0);
595 switch (CE->getOpcode()) {
596 case Instruction::GetElementPtr: {
598 GenericValue Result = getConstantValue(Op0);
599 APInt Offset(TD->getPointerSizeInBits(), 0);
600 cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
602 char* tmp = (char*) Result.PointerVal;
603 Result = PTOGV(tmp + Offset.getSExtValue());
606 case Instruction::Trunc: {
607 GenericValue GV = getConstantValue(Op0);
608 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
609 GV.IntVal = GV.IntVal.trunc(BitWidth);
612 case Instruction::ZExt: {
613 GenericValue GV = getConstantValue(Op0);
614 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
615 GV.IntVal = GV.IntVal.zext(BitWidth);
618 case Instruction::SExt: {
619 GenericValue GV = getConstantValue(Op0);
620 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
621 GV.IntVal = GV.IntVal.sext(BitWidth);
624 case Instruction::FPTrunc: {
626 GenericValue GV = getConstantValue(Op0);
627 GV.FloatVal = float(GV.DoubleVal);
630 case Instruction::FPExt:{
632 GenericValue GV = getConstantValue(Op0);
633 GV.DoubleVal = double(GV.FloatVal);
636 case Instruction::UIToFP: {
637 GenericValue GV = getConstantValue(Op0);
638 if (CE->getType()->isFloatTy())
639 GV.FloatVal = float(GV.IntVal.roundToDouble());
640 else if (CE->getType()->isDoubleTy())
641 GV.DoubleVal = GV.IntVal.roundToDouble();
642 else if (CE->getType()->isX86_FP80Ty()) {
643 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
644 (void)apf.convertFromAPInt(GV.IntVal,
646 APFloat::rmNearestTiesToEven);
647 GV.IntVal = apf.bitcastToAPInt();
651 case Instruction::SIToFP: {
652 GenericValue GV = getConstantValue(Op0);
653 if (CE->getType()->isFloatTy())
654 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
655 else if (CE->getType()->isDoubleTy())
656 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
657 else if (CE->getType()->isX86_FP80Ty()) {
658 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
659 (void)apf.convertFromAPInt(GV.IntVal,
661 APFloat::rmNearestTiesToEven);
662 GV.IntVal = apf.bitcastToAPInt();
666 case Instruction::FPToUI: // double->APInt conversion handles sign
667 case Instruction::FPToSI: {
668 GenericValue GV = getConstantValue(Op0);
669 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
670 if (Op0->getType()->isFloatTy())
671 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
672 else if (Op0->getType()->isDoubleTy())
673 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
674 else if (Op0->getType()->isX86_FP80Ty()) {
675 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
678 (void)apf.convertToInteger(&v, BitWidth,
679 CE->getOpcode()==Instruction::FPToSI,
680 APFloat::rmTowardZero, &ignored);
681 GV.IntVal = v; // endian?
685 case Instruction::PtrToInt: {
686 GenericValue GV = getConstantValue(Op0);
687 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
688 assert(PtrWidth <= 64 && "Bad pointer width");
689 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
690 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
691 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
694 case Instruction::IntToPtr: {
695 GenericValue GV = getConstantValue(Op0);
696 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
697 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
698 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
699 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
702 case Instruction::BitCast: {
703 GenericValue GV = getConstantValue(Op0);
704 Type* DestTy = CE->getType();
705 switch (Op0->getType()->getTypeID()) {
706 default: llvm_unreachable("Invalid bitcast operand");
707 case Type::IntegerTyID:
708 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
709 if (DestTy->isFloatTy())
710 GV.FloatVal = GV.IntVal.bitsToFloat();
711 else if (DestTy->isDoubleTy())
712 GV.DoubleVal = GV.IntVal.bitsToDouble();
714 case Type::FloatTyID:
715 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
716 GV.IntVal = APInt::floatToBits(GV.FloatVal);
718 case Type::DoubleTyID:
719 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
720 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
722 case Type::PointerTyID:
723 assert(DestTy->isPointerTy() && "Invalid bitcast");
724 break; // getConstantValue(Op0) above already converted it
728 case Instruction::Add:
729 case Instruction::FAdd:
730 case Instruction::Sub:
731 case Instruction::FSub:
732 case Instruction::Mul:
733 case Instruction::FMul:
734 case Instruction::UDiv:
735 case Instruction::SDiv:
736 case Instruction::URem:
737 case Instruction::SRem:
738 case Instruction::And:
739 case Instruction::Or:
740 case Instruction::Xor: {
741 GenericValue LHS = getConstantValue(Op0);
742 GenericValue RHS = getConstantValue(CE->getOperand(1));
744 switch (CE->getOperand(0)->getType()->getTypeID()) {
745 default: llvm_unreachable("Bad add type!");
746 case Type::IntegerTyID:
747 switch (CE->getOpcode()) {
748 default: llvm_unreachable("Invalid integer opcode");
749 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
750 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
751 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
752 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
753 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
754 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
755 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
756 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
757 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
758 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
761 case Type::FloatTyID:
762 switch (CE->getOpcode()) {
763 default: llvm_unreachable("Invalid float opcode");
764 case Instruction::FAdd:
765 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
766 case Instruction::FSub:
767 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
768 case Instruction::FMul:
769 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
770 case Instruction::FDiv:
771 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
772 case Instruction::FRem:
773 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
776 case Type::DoubleTyID:
777 switch (CE->getOpcode()) {
778 default: llvm_unreachable("Invalid double opcode");
779 case Instruction::FAdd:
780 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
781 case Instruction::FSub:
782 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
783 case Instruction::FMul:
784 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
785 case Instruction::FDiv:
786 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
787 case Instruction::FRem:
788 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
791 case Type::X86_FP80TyID:
792 case Type::PPC_FP128TyID:
793 case Type::FP128TyID: {
794 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
795 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
796 switch (CE->getOpcode()) {
797 default: llvm_unreachable("Invalid long double opcode");
798 case Instruction::FAdd:
799 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
800 GV.IntVal = apfLHS.bitcastToAPInt();
802 case Instruction::FSub:
803 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
804 APFloat::rmNearestTiesToEven);
805 GV.IntVal = apfLHS.bitcastToAPInt();
807 case Instruction::FMul:
808 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
809 APFloat::rmNearestTiesToEven);
810 GV.IntVal = apfLHS.bitcastToAPInt();
812 case Instruction::FDiv:
813 apfLHS.divide(APFloat(Sem, RHS.IntVal),
814 APFloat::rmNearestTiesToEven);
815 GV.IntVal = apfLHS.bitcastToAPInt();
817 case Instruction::FRem:
818 apfLHS.mod(APFloat(Sem, RHS.IntVal),
819 APFloat::rmNearestTiesToEven);
820 GV.IntVal = apfLHS.bitcastToAPInt();
832 SmallString<256> Msg;
833 raw_svector_ostream OS(Msg);
834 OS << "ConstantExpr not handled: " << *CE;
835 report_fatal_error(OS.str());
838 // Otherwise, we have a simple constant.
840 switch (C->getType()->getTypeID()) {
841 case Type::FloatTyID:
842 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
844 case Type::DoubleTyID:
845 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
847 case Type::X86_FP80TyID:
848 case Type::FP128TyID:
849 case Type::PPC_FP128TyID:
850 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
852 case Type::IntegerTyID:
853 Result.IntVal = cast<ConstantInt>(C)->getValue();
855 case Type::PointerTyID:
856 if (isa<ConstantPointerNull>(C))
857 Result.PointerVal = 0;
858 else if (const Function *F = dyn_cast<Function>(C))
859 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
860 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
861 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
862 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
863 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
864 BA->getBasicBlock())));
866 llvm_unreachable("Unknown constant pointer type!");
868 case Type::VectorTyID: {
871 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
872 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
873 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
876 elemNum = CDV->getNumElements();
877 ElemTy = CDV->getElementType();
878 } else if (CV || CAZ) {
879 VectorType* VTy = dyn_cast<VectorType>(C->getType());
880 elemNum = VTy->getNumElements();
881 ElemTy = VTy->getElementType();
883 llvm_unreachable("Unknown constant vector type!");
886 Result.AggregateVal.resize(elemNum);
887 // Check if vector holds floats.
888 if(ElemTy->isFloatTy()) {
890 GenericValue floatZero;
891 floatZero.FloatVal = 0.f;
892 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
897 for (unsigned i = 0; i < elemNum; ++i)
898 if (!isa<UndefValue>(CV->getOperand(i)))
899 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
900 CV->getOperand(i))->getValueAPF().convertToFloat();
904 for (unsigned i = 0; i < elemNum; ++i)
905 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
909 // Check if vector holds doubles.
910 if (ElemTy->isDoubleTy()) {
912 GenericValue doubleZero;
913 doubleZero.DoubleVal = 0.0;
914 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
919 for (unsigned i = 0; i < elemNum; ++i)
920 if (!isa<UndefValue>(CV->getOperand(i)))
921 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
922 CV->getOperand(i))->getValueAPF().convertToDouble();
926 for (unsigned i = 0; i < elemNum; ++i)
927 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
931 // Check if vector holds integers.
932 if (ElemTy->isIntegerTy()) {
934 GenericValue intZero;
935 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
936 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
941 for (unsigned i = 0; i < elemNum; ++i)
942 if (!isa<UndefValue>(CV->getOperand(i)))
943 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
944 CV->getOperand(i))->getValue();
946 Result.AggregateVal[i].IntVal =
947 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
952 for (unsigned i = 0; i < elemNum; ++i)
953 Result.AggregateVal[i].IntVal = APInt(
954 CDV->getElementType()->getPrimitiveSizeInBits(),
955 CDV->getElementAsInteger(i));
959 llvm_unreachable("Unknown constant pointer type!");
964 SmallString<256> Msg;
965 raw_svector_ostream OS(Msg);
966 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
967 report_fatal_error(OS.str());
973 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
974 /// with the integer held in IntVal.
975 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
976 unsigned StoreBytes) {
977 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
978 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
980 if (sys::IsLittleEndianHost) {
981 // Little-endian host - the source is ordered from LSB to MSB. Order the
982 // destination from LSB to MSB: Do a straight copy.
983 memcpy(Dst, Src, StoreBytes);
985 // Big-endian host - the source is an array of 64 bit words ordered from
986 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
987 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
988 while (StoreBytes > sizeof(uint64_t)) {
989 StoreBytes -= sizeof(uint64_t);
990 // May not be aligned so use memcpy.
991 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
992 Src += sizeof(uint64_t);
995 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
999 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1000 GenericValue *Ptr, Type *Ty) {
1001 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1003 switch (Ty->getTypeID()) {
1005 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1007 case Type::IntegerTyID:
1008 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1010 case Type::FloatTyID:
1011 *((float*)Ptr) = Val.FloatVal;
1013 case Type::DoubleTyID:
1014 *((double*)Ptr) = Val.DoubleVal;
1016 case Type::X86_FP80TyID:
1017 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1019 case Type::PointerTyID:
1020 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1021 if (StoreBytes != sizeof(PointerTy))
1022 memset(&(Ptr->PointerVal), 0, StoreBytes);
1024 *((PointerTy*)Ptr) = Val.PointerVal;
1026 case Type::VectorTyID:
1027 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1028 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1029 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1030 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1031 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1032 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1033 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1034 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1035 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1041 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1042 // Host and target are different endian - reverse the stored bytes.
1043 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1046 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1047 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1048 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1049 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1050 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1051 const_cast<uint64_t *>(IntVal.getRawData()));
1053 if (sys::IsLittleEndianHost)
1054 // Little-endian host - the destination must be ordered from LSB to MSB.
1055 // The source is ordered from LSB to MSB: Do a straight copy.
1056 memcpy(Dst, Src, LoadBytes);
1058 // Big-endian - the destination is an array of 64 bit words ordered from
1059 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1060 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1062 while (LoadBytes > sizeof(uint64_t)) {
1063 LoadBytes -= sizeof(uint64_t);
1064 // May not be aligned so use memcpy.
1065 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1066 Dst += sizeof(uint64_t);
1069 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1075 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1078 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1080 switch (Ty->getTypeID()) {
1081 case Type::IntegerTyID:
1082 // An APInt with all words initially zero.
1083 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1084 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1086 case Type::FloatTyID:
1087 Result.FloatVal = *((float*)Ptr);
1089 case Type::DoubleTyID:
1090 Result.DoubleVal = *((double*)Ptr);
1092 case Type::PointerTyID:
1093 Result.PointerVal = *((PointerTy*)Ptr);
1095 case Type::X86_FP80TyID: {
1096 // This is endian dependent, but it will only work on x86 anyway.
1097 // FIXME: Will not trap if loading a signaling NaN.
1100 Result.IntVal = APInt(80, y);
1103 case Type::VectorTyID: {
1104 const VectorType *VT = cast<VectorType>(Ty);
1105 const Type *ElemT = VT->getElementType();
1106 const unsigned numElems = VT->getNumElements();
1107 if (ElemT->isFloatTy()) {
1108 Result.AggregateVal.resize(numElems);
1109 for (unsigned i = 0; i < numElems; ++i)
1110 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1112 if (ElemT->isDoubleTy()) {
1113 Result.AggregateVal.resize(numElems);
1114 for (unsigned i = 0; i < numElems; ++i)
1115 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1117 if (ElemT->isIntegerTy()) {
1118 GenericValue intZero;
1119 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1120 intZero.IntVal = APInt(elemBitWidth, 0);
1121 Result.AggregateVal.resize(numElems, intZero);
1122 for (unsigned i = 0; i < numElems; ++i)
1123 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1124 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1129 SmallString<256> Msg;
1130 raw_svector_ostream OS(Msg);
1131 OS << "Cannot load value of type " << *Ty << "!";
1132 report_fatal_error(OS.str());
1136 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1137 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1138 DEBUG(Init->dump());
1139 if (isa<UndefValue>(Init))
1142 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1143 unsigned ElementSize =
1144 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1145 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1146 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1150 if (isa<ConstantAggregateZero>(Init)) {
1151 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1155 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1156 unsigned ElementSize =
1157 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1158 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1159 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1163 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1164 const StructLayout *SL =
1165 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1166 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1167 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1171 if (const ConstantDataSequential *CDS =
1172 dyn_cast<ConstantDataSequential>(Init)) {
1173 // CDS is already laid out in host memory order.
1174 StringRef Data = CDS->getRawDataValues();
1175 memcpy(Addr, Data.data(), Data.size());
1179 if (Init->getType()->isFirstClassType()) {
1180 GenericValue Val = getConstantValue(Init);
1181 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1185 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1186 llvm_unreachable("Unknown constant type to initialize memory with!");
1189 /// EmitGlobals - Emit all of the global variables to memory, storing their
1190 /// addresses into GlobalAddress. This must make sure to copy the contents of
1191 /// their initializers into the memory.
1192 void ExecutionEngine::emitGlobals() {
1193 // Loop over all of the global variables in the program, allocating the memory
1194 // to hold them. If there is more than one module, do a prepass over globals
1195 // to figure out how the different modules should link together.
1196 std::map<std::pair<std::string, Type*>,
1197 const GlobalValue*> LinkedGlobalsMap;
1199 if (Modules.size() != 1) {
1200 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1201 Module &M = *Modules[m];
1202 for (Module::const_global_iterator I = M.global_begin(),
1203 E = M.global_end(); I != E; ++I) {
1204 const GlobalValue *GV = I;
1205 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1206 GV->hasAppendingLinkage() || !GV->hasName())
1207 continue;// Ignore external globals and globals with internal linkage.
1209 const GlobalValue *&GVEntry =
1210 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1212 // If this is the first time we've seen this global, it is the canonical
1219 // If the existing global is strong, never replace it.
1220 if (GVEntry->hasExternalLinkage() ||
1221 GVEntry->hasDLLImportLinkage() ||
1222 GVEntry->hasDLLExportLinkage())
1225 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1226 // symbol. FIXME is this right for common?
1227 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1233 std::vector<const GlobalValue*> NonCanonicalGlobals;
1234 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1235 Module &M = *Modules[m];
1236 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1238 // In the multi-module case, see what this global maps to.
1239 if (!LinkedGlobalsMap.empty()) {
1240 if (const GlobalValue *GVEntry =
1241 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1242 // If something else is the canonical global, ignore this one.
1243 if (GVEntry != &*I) {
1244 NonCanonicalGlobals.push_back(I);
1250 if (!I->isDeclaration()) {
1251 addGlobalMapping(I, getMemoryForGV(I));
1253 // External variable reference. Try to use the dynamic loader to
1254 // get a pointer to it.
1256 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1257 addGlobalMapping(I, SymAddr);
1259 report_fatal_error("Could not resolve external global address: "
1265 // If there are multiple modules, map the non-canonical globals to their
1266 // canonical location.
1267 if (!NonCanonicalGlobals.empty()) {
1268 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1269 const GlobalValue *GV = NonCanonicalGlobals[i];
1270 const GlobalValue *CGV =
1271 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1272 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1273 assert(Ptr && "Canonical global wasn't codegen'd!");
1274 addGlobalMapping(GV, Ptr);
1278 // Now that all of the globals are set up in memory, loop through them all
1279 // and initialize their contents.
1280 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1282 if (!I->isDeclaration()) {
1283 if (!LinkedGlobalsMap.empty()) {
1284 if (const GlobalValue *GVEntry =
1285 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1286 if (GVEntry != &*I) // Not the canonical variable.
1289 EmitGlobalVariable(I);
1295 // EmitGlobalVariable - This method emits the specified global variable to the
1296 // address specified in GlobalAddresses, or allocates new memory if it's not
1297 // already in the map.
1298 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1299 void *GA = getPointerToGlobalIfAvailable(GV);
1302 // If it's not already specified, allocate memory for the global.
1303 GA = getMemoryForGV(GV);
1304 addGlobalMapping(GV, GA);
1307 // Don't initialize if it's thread local, let the client do it.
1308 if (!GV->isThreadLocal())
1309 InitializeMemory(GV->getInitializer(), GA);
1311 Type *ElTy = GV->getType()->getElementType();
1312 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1313 NumInitBytes += (unsigned)GVSize;
1317 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1318 : EE(EE), GlobalAddressMap(this) {
1322 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1323 return &EES->EE.lock;
1326 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1327 const GlobalValue *Old) {
1328 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1329 EES->GlobalAddressReverseMap.erase(OldVal);
1332 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1333 const GlobalValue *,
1334 const GlobalValue *) {
1335 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1336 " RAUW on a value it has a global mapping for.");