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/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ExecutionEngine/GenericValue.h"
20 #include "llvm/ExecutionEngine/JITEventListener.h"
21 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Object/Archive.h"
30 #include "llvm/Object/ObjectFile.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/DynamicLibrary.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MutexGuard.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
43 #define DEBUG_TYPE "jit"
45 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
46 STATISTIC(NumGlobals , "Number of global vars initialized");
48 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
49 std::unique_ptr<Module> M, std::string *ErrorStr,
50 std::shared_ptr<MCJITMemoryManager> MemMgr,
51 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
52 std::unique_ptr<TargetMachine> TM) = nullptr;
54 ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
55 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
56 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
57 std::unique_ptr<TargetMachine> TM) = nullptr;
59 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
60 std::string *ErrorStr) =nullptr;
62 void JITEventListener::anchor() {}
64 ExecutionEngine::ExecutionEngine(const DataLayout DL, std::unique_ptr<Module> M)
65 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
66 CompilingLazily = false;
67 GVCompilationDisabled = false;
68 SymbolSearchingDisabled = false;
70 // IR module verification is enabled by default in debug builds, and disabled
71 // by default in release builds.
75 VerifyModules = false;
78 assert(M && "Module is null?");
79 Modules.push_back(std::move(M));
82 ExecutionEngine::~ExecutionEngine() {
83 clearAllGlobalMappings();
87 /// \brief Helper class which uses a value handler to automatically deletes the
88 /// memory block when the GlobalVariable is destroyed.
89 class GVMemoryBlock : public CallbackVH {
90 GVMemoryBlock(const GlobalVariable *GV)
91 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
94 /// \brief Returns the address the GlobalVariable should be written into. The
95 /// GVMemoryBlock object prefixes that.
96 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
97 Type *ElTy = GV->getType()->getElementType();
98 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
99 void *RawMemory = ::operator new(
100 RoundUpToAlignment(sizeof(GVMemoryBlock),
101 TD.getPreferredAlignment(GV))
103 new(RawMemory) GVMemoryBlock(GV);
104 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
107 void deleted() override {
108 // We allocated with operator new and with some extra memory hanging off the
109 // end, so don't just delete this. I'm not sure if this is actually
111 this->~GVMemoryBlock();
112 ::operator delete(this);
115 } // anonymous namespace
117 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
118 return GVMemoryBlock::Create(GV, getDataLayout());
121 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
122 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
126 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
127 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
130 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
131 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
134 bool ExecutionEngine::removeModule(Module *M) {
135 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
136 Module *Found = I->get();
140 clearGlobalMappingsFromModule(M);
147 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
148 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
149 Function *F = Modules[i]->getFunction(FnName);
150 if (F && !F->isDeclaration())
156 GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
157 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
158 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
159 if (GV && !GV->isDeclaration())
165 uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
166 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
169 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
171 if (I == GlobalAddressMap.end())
174 GlobalAddressReverseMap.erase(I->second);
176 GlobalAddressMap.erase(I);
182 std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
183 MutexGuard locked(lock);
185 SmallString<128> FullName;
186 Mang.getNameWithPrefix(FullName, GV, false);
187 return FullName.str();
190 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
191 MutexGuard locked(lock);
192 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
195 void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
196 MutexGuard locked(lock);
198 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
200 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
201 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
202 assert((!CurVal || !Addr) && "GlobalMapping already established!");
205 // If we are using the reverse mapping, add it too.
206 if (!EEState.getGlobalAddressReverseMap().empty()) {
207 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
208 assert((!V.empty() || !Name.empty()) &&
209 "GlobalMapping already established!");
214 void ExecutionEngine::clearAllGlobalMappings() {
215 MutexGuard locked(lock);
217 EEState.getGlobalAddressMap().clear();
218 EEState.getGlobalAddressReverseMap().clear();
221 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
222 MutexGuard locked(lock);
224 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
225 EEState.RemoveMapping(getMangledName(FI));
226 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
228 EEState.RemoveMapping(getMangledName(GI));
231 uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
233 MutexGuard locked(lock);
234 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
237 uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
238 MutexGuard locked(lock);
240 ExecutionEngineState::GlobalAddressMapTy &Map =
241 EEState.getGlobalAddressMap();
243 // Deleting from the mapping?
245 return EEState.RemoveMapping(Name);
247 uint64_t &CurVal = Map[Name];
248 uint64_t OldVal = CurVal;
250 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
251 EEState.getGlobalAddressReverseMap().erase(CurVal);
254 // If we are using the reverse mapping, add it too.
255 if (!EEState.getGlobalAddressReverseMap().empty()) {
256 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
257 assert((!V.empty() || !Name.empty()) &&
258 "GlobalMapping already established!");
264 uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
265 MutexGuard locked(lock);
266 uint64_t Address = 0;
267 ExecutionEngineState::GlobalAddressMapTy::iterator I =
268 EEState.getGlobalAddressMap().find(S);
269 if (I != EEState.getGlobalAddressMap().end())
275 void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
276 MutexGuard locked(lock);
277 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
282 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
283 MutexGuard locked(lock);
284 return getPointerToGlobalIfAvailable(getMangledName(GV));
287 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
288 MutexGuard locked(lock);
290 // If we haven't computed the reverse mapping yet, do so first.
291 if (EEState.getGlobalAddressReverseMap().empty()) {
292 for (ExecutionEngineState::GlobalAddressMapTy::iterator
293 I = EEState.getGlobalAddressMap().begin(),
294 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
295 StringRef Name = I->first();
296 uint64_t Addr = I->second;
297 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
302 std::map<uint64_t, std::string>::iterator I =
303 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
305 if (I != EEState.getGlobalAddressReverseMap().end()) {
306 StringRef Name = I->second;
307 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
308 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
316 std::unique_ptr<char[]> Array;
317 std::vector<std::unique_ptr<char[]>> Values;
319 /// Turn a vector of strings into a nice argv style array of pointers to null
320 /// terminated strings.
321 void *reset(LLVMContext &C, ExecutionEngine *EE,
322 const std::vector<std::string> &InputArgv);
324 } // anonymous namespace
325 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
326 const std::vector<std::string> &InputArgv) {
327 Values.clear(); // Free the old contents.
328 Values.reserve(InputArgv.size());
329 unsigned PtrSize = EE->getDataLayout().getPointerSize();
330 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
332 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
333 Type *SBytePtr = Type::getInt8PtrTy(C);
335 for (unsigned i = 0; i != InputArgv.size(); ++i) {
336 unsigned Size = InputArgv[i].size()+1;
337 auto Dest = make_unique<char[]>(Size);
338 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
340 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
343 // Endian safe: Array[i] = (PointerTy)Dest;
344 EE->StoreValueToMemory(PTOGV(Dest.get()),
345 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
346 Values.push_back(std::move(Dest));
350 EE->StoreValueToMemory(PTOGV(nullptr),
351 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
356 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
358 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
359 GlobalVariable *GV = module.getNamedGlobal(Name);
361 // If this global has internal linkage, or if it has a use, then it must be
362 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
363 // this is the case, don't execute any of the global ctors, __main will do
365 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
367 // Should be an array of '{ i32, void ()* }' structs. The first value is
368 // the init priority, which we ignore.
369 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
372 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
373 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
376 Constant *FP = CS->getOperand(1);
377 if (FP->isNullValue())
378 continue; // Found a sentinal value, ignore.
380 // Strip off constant expression casts.
381 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
383 FP = CE->getOperand(0);
385 // Execute the ctor/dtor function!
386 if (Function *F = dyn_cast<Function>(FP))
387 runFunction(F, None);
389 // FIXME: It is marginally lame that we just do nothing here if we see an
390 // entry we don't recognize. It might not be unreasonable for the verifier
391 // to not even allow this and just assert here.
395 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
396 // Execute global ctors/dtors for each module in the program.
397 for (std::unique_ptr<Module> &M : Modules)
398 runStaticConstructorsDestructors(*M, isDtors);
402 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
403 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
404 unsigned PtrSize = EE->getDataLayout().getPointerSize();
405 for (unsigned i = 0; i < PtrSize; ++i)
406 if (*(i + (uint8_t*)Loc))
412 int ExecutionEngine::runFunctionAsMain(Function *Fn,
413 const std::vector<std::string> &argv,
414 const char * const * envp) {
415 std::vector<GenericValue> GVArgs;
417 GVArgc.IntVal = APInt(32, argv.size());
420 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
421 FunctionType *FTy = Fn->getFunctionType();
422 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
424 // Check the argument types.
426 report_fatal_error("Invalid number of arguments of main() supplied");
427 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
428 report_fatal_error("Invalid type for third argument of main() supplied");
429 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
430 report_fatal_error("Invalid type for second argument of main() supplied");
431 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
432 report_fatal_error("Invalid type for first argument of main() supplied");
433 if (!FTy->getReturnType()->isIntegerTy() &&
434 !FTy->getReturnType()->isVoidTy())
435 report_fatal_error("Invalid return type of main() supplied");
440 GVArgs.push_back(GVArgc); // Arg #0 = argc.
443 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
444 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
445 "argv[0] was null after CreateArgv");
447 std::vector<std::string> EnvVars;
448 for (unsigned i = 0; envp[i]; ++i)
449 EnvVars.emplace_back(envp[i]);
451 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
456 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
459 EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
461 EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
462 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
463 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
464 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
465 UseOrcMCJITReplacement(false) {
466 // IR module verification is enabled by default in debug builds, and disabled
467 // by default in release builds.
469 VerifyModules = true;
471 VerifyModules = false;
475 EngineBuilder::~EngineBuilder() = default;
477 EngineBuilder &EngineBuilder::setMCJITMemoryManager(
478 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
479 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
486 EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
487 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
492 EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
493 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
497 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
498 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
500 // Make sure we can resolve symbols in the program as well. The zero arg
501 // to the function tells DynamicLibrary to load the program, not a library.
502 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
505 // If the user specified a memory manager but didn't specify which engine to
506 // create, we assume they only want the JIT, and we fail if they only want
509 if (WhichEngine & EngineKind::JIT)
510 WhichEngine = EngineKind::JIT;
513 *ErrorStr = "Cannot create an interpreter with a memory manager.";
518 // Unless the interpreter was explicitly selected or the JIT is not linked,
520 if ((WhichEngine & EngineKind::JIT) && TheTM) {
521 Triple TT(M->getTargetTriple());
522 if (!TM->getTarget().hasJIT()) {
523 errs() << "WARNING: This target JIT is not designed for the host"
524 << " you are running. If bad things happen, please choose"
525 << " a different -march switch.\n";
528 ExecutionEngine *EE = nullptr;
529 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
530 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
533 EE->addModule(std::move(M));
534 } else if (ExecutionEngine::MCJITCtor)
535 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
536 std::move(Resolver), std::move(TheTM));
539 EE->setVerifyModules(VerifyModules);
544 // If we can't make a JIT and we didn't request one specifically, try making
545 // an interpreter instead.
546 if (WhichEngine & EngineKind::Interpreter) {
547 if (ExecutionEngine::InterpCtor)
548 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
550 *ErrorStr = "Interpreter has not been linked in.";
554 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
556 *ErrorStr = "JIT has not been linked in.";
562 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
563 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
564 return getPointerToFunction(F);
566 MutexGuard locked(lock);
567 if (void* P = getPointerToGlobalIfAvailable(GV))
570 // Global variable might have been added since interpreter started.
571 if (GlobalVariable *GVar =
572 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
573 EmitGlobalVariable(GVar);
575 llvm_unreachable("Global hasn't had an address allocated yet!");
577 return getPointerToGlobalIfAvailable(GV);
580 /// \brief Converts a Constant* into a GenericValue, including handling of
581 /// ConstantExpr values.
582 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
583 // If its undefined, return the garbage.
584 if (isa<UndefValue>(C)) {
586 switch (C->getType()->getTypeID()) {
589 case Type::IntegerTyID:
590 case Type::X86_FP80TyID:
591 case Type::FP128TyID:
592 case Type::PPC_FP128TyID:
593 // Although the value is undefined, we still have to construct an APInt
594 // with the correct bit width.
595 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
597 case Type::StructTyID: {
598 // if the whole struct is 'undef' just reserve memory for the value.
599 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
600 unsigned int elemNum = STy->getNumElements();
601 Result.AggregateVal.resize(elemNum);
602 for (unsigned int i = 0; i < elemNum; ++i) {
603 Type *ElemTy = STy->getElementType(i);
604 if (ElemTy->isIntegerTy())
605 Result.AggregateVal[i].IntVal =
606 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
607 else if (ElemTy->isAggregateType()) {
608 const Constant *ElemUndef = UndefValue::get(ElemTy);
609 Result.AggregateVal[i] = getConstantValue(ElemUndef);
615 case Type::VectorTyID:
616 // if the whole vector is 'undef' just reserve memory for the value.
617 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
618 const Type *ElemTy = VTy->getElementType();
619 unsigned int elemNum = VTy->getNumElements();
620 Result.AggregateVal.resize(elemNum);
621 if (ElemTy->isIntegerTy())
622 for (unsigned int i = 0; i < elemNum; ++i)
623 Result.AggregateVal[i].IntVal =
624 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
630 // Otherwise, if the value is a ConstantExpr...
631 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
632 Constant *Op0 = CE->getOperand(0);
633 switch (CE->getOpcode()) {
634 case Instruction::GetElementPtr: {
636 GenericValue Result = getConstantValue(Op0);
637 APInt Offset(DL.getPointerSizeInBits(), 0);
638 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
640 char* tmp = (char*) Result.PointerVal;
641 Result = PTOGV(tmp + Offset.getSExtValue());
644 case Instruction::Trunc: {
645 GenericValue GV = getConstantValue(Op0);
646 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
647 GV.IntVal = GV.IntVal.trunc(BitWidth);
650 case Instruction::ZExt: {
651 GenericValue GV = getConstantValue(Op0);
652 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
653 GV.IntVal = GV.IntVal.zext(BitWidth);
656 case Instruction::SExt: {
657 GenericValue GV = getConstantValue(Op0);
658 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
659 GV.IntVal = GV.IntVal.sext(BitWidth);
662 case Instruction::FPTrunc: {
664 GenericValue GV = getConstantValue(Op0);
665 GV.FloatVal = float(GV.DoubleVal);
668 case Instruction::FPExt:{
670 GenericValue GV = getConstantValue(Op0);
671 GV.DoubleVal = double(GV.FloatVal);
674 case Instruction::UIToFP: {
675 GenericValue GV = getConstantValue(Op0);
676 if (CE->getType()->isFloatTy())
677 GV.FloatVal = float(GV.IntVal.roundToDouble());
678 else if (CE->getType()->isDoubleTy())
679 GV.DoubleVal = GV.IntVal.roundToDouble();
680 else if (CE->getType()->isX86_FP80Ty()) {
681 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
682 (void)apf.convertFromAPInt(GV.IntVal,
684 APFloat::rmNearestTiesToEven);
685 GV.IntVal = apf.bitcastToAPInt();
689 case Instruction::SIToFP: {
690 GenericValue GV = getConstantValue(Op0);
691 if (CE->getType()->isFloatTy())
692 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
693 else if (CE->getType()->isDoubleTy())
694 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
695 else if (CE->getType()->isX86_FP80Ty()) {
696 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
697 (void)apf.convertFromAPInt(GV.IntVal,
699 APFloat::rmNearestTiesToEven);
700 GV.IntVal = apf.bitcastToAPInt();
704 case Instruction::FPToUI: // double->APInt conversion handles sign
705 case Instruction::FPToSI: {
706 GenericValue GV = getConstantValue(Op0);
707 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
708 if (Op0->getType()->isFloatTy())
709 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
710 else if (Op0->getType()->isDoubleTy())
711 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
712 else if (Op0->getType()->isX86_FP80Ty()) {
713 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
716 (void)apf.convertToInteger(&v, BitWidth,
717 CE->getOpcode()==Instruction::FPToSI,
718 APFloat::rmTowardZero, &ignored);
719 GV.IntVal = v; // endian?
723 case Instruction::PtrToInt: {
724 GenericValue GV = getConstantValue(Op0);
725 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
726 assert(PtrWidth <= 64 && "Bad pointer width");
727 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
728 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
729 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
732 case Instruction::IntToPtr: {
733 GenericValue GV = getConstantValue(Op0);
734 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
735 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
736 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
737 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
740 case Instruction::BitCast: {
741 GenericValue GV = getConstantValue(Op0);
742 Type* DestTy = CE->getType();
743 switch (Op0->getType()->getTypeID()) {
744 default: llvm_unreachable("Invalid bitcast operand");
745 case Type::IntegerTyID:
746 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
747 if (DestTy->isFloatTy())
748 GV.FloatVal = GV.IntVal.bitsToFloat();
749 else if (DestTy->isDoubleTy())
750 GV.DoubleVal = GV.IntVal.bitsToDouble();
752 case Type::FloatTyID:
753 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
754 GV.IntVal = APInt::floatToBits(GV.FloatVal);
756 case Type::DoubleTyID:
757 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
758 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
760 case Type::PointerTyID:
761 assert(DestTy->isPointerTy() && "Invalid bitcast");
762 break; // getConstantValue(Op0) above already converted it
766 case Instruction::Add:
767 case Instruction::FAdd:
768 case Instruction::Sub:
769 case Instruction::FSub:
770 case Instruction::Mul:
771 case Instruction::FMul:
772 case Instruction::UDiv:
773 case Instruction::SDiv:
774 case Instruction::URem:
775 case Instruction::SRem:
776 case Instruction::And:
777 case Instruction::Or:
778 case Instruction::Xor: {
779 GenericValue LHS = getConstantValue(Op0);
780 GenericValue RHS = getConstantValue(CE->getOperand(1));
782 switch (CE->getOperand(0)->getType()->getTypeID()) {
783 default: llvm_unreachable("Bad add type!");
784 case Type::IntegerTyID:
785 switch (CE->getOpcode()) {
786 default: llvm_unreachable("Invalid integer opcode");
787 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
788 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
789 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
790 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
791 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
792 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
793 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
794 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
795 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
796 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
799 case Type::FloatTyID:
800 switch (CE->getOpcode()) {
801 default: llvm_unreachable("Invalid float opcode");
802 case Instruction::FAdd:
803 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
804 case Instruction::FSub:
805 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
806 case Instruction::FMul:
807 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
808 case Instruction::FDiv:
809 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
810 case Instruction::FRem:
811 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
814 case Type::DoubleTyID:
815 switch (CE->getOpcode()) {
816 default: llvm_unreachable("Invalid double opcode");
817 case Instruction::FAdd:
818 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
819 case Instruction::FSub:
820 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
821 case Instruction::FMul:
822 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
823 case Instruction::FDiv:
824 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
825 case Instruction::FRem:
826 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
829 case Type::X86_FP80TyID:
830 case Type::PPC_FP128TyID:
831 case Type::FP128TyID: {
832 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
833 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
834 switch (CE->getOpcode()) {
835 default: llvm_unreachable("Invalid long double opcode");
836 case Instruction::FAdd:
837 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
838 GV.IntVal = apfLHS.bitcastToAPInt();
840 case Instruction::FSub:
841 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
842 APFloat::rmNearestTiesToEven);
843 GV.IntVal = apfLHS.bitcastToAPInt();
845 case Instruction::FMul:
846 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
847 APFloat::rmNearestTiesToEven);
848 GV.IntVal = apfLHS.bitcastToAPInt();
850 case Instruction::FDiv:
851 apfLHS.divide(APFloat(Sem, RHS.IntVal),
852 APFloat::rmNearestTiesToEven);
853 GV.IntVal = apfLHS.bitcastToAPInt();
855 case Instruction::FRem:
856 apfLHS.mod(APFloat(Sem, RHS.IntVal),
857 APFloat::rmNearestTiesToEven);
858 GV.IntVal = apfLHS.bitcastToAPInt();
870 SmallString<256> Msg;
871 raw_svector_ostream OS(Msg);
872 OS << "ConstantExpr not handled: " << *CE;
873 report_fatal_error(OS.str());
876 // Otherwise, we have a simple constant.
878 switch (C->getType()->getTypeID()) {
879 case Type::FloatTyID:
880 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
882 case Type::DoubleTyID:
883 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
885 case Type::X86_FP80TyID:
886 case Type::FP128TyID:
887 case Type::PPC_FP128TyID:
888 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
890 case Type::IntegerTyID:
891 Result.IntVal = cast<ConstantInt>(C)->getValue();
893 case Type::PointerTyID:
894 if (isa<ConstantPointerNull>(C))
895 Result.PointerVal = nullptr;
896 else if (const Function *F = dyn_cast<Function>(C))
897 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
898 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
899 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
901 llvm_unreachable("Unknown constant pointer type!");
903 case Type::VectorTyID: {
906 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
907 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
908 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
911 elemNum = CDV->getNumElements();
912 ElemTy = CDV->getElementType();
913 } else if (CV || CAZ) {
914 VectorType* VTy = dyn_cast<VectorType>(C->getType());
915 elemNum = VTy->getNumElements();
916 ElemTy = VTy->getElementType();
918 llvm_unreachable("Unknown constant vector type!");
921 Result.AggregateVal.resize(elemNum);
922 // Check if vector holds floats.
923 if(ElemTy->isFloatTy()) {
925 GenericValue floatZero;
926 floatZero.FloatVal = 0.f;
927 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
932 for (unsigned i = 0; i < elemNum; ++i)
933 if (!isa<UndefValue>(CV->getOperand(i)))
934 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
935 CV->getOperand(i))->getValueAPF().convertToFloat();
939 for (unsigned i = 0; i < elemNum; ++i)
940 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
944 // Check if vector holds doubles.
945 if (ElemTy->isDoubleTy()) {
947 GenericValue doubleZero;
948 doubleZero.DoubleVal = 0.0;
949 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
954 for (unsigned i = 0; i < elemNum; ++i)
955 if (!isa<UndefValue>(CV->getOperand(i)))
956 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
957 CV->getOperand(i))->getValueAPF().convertToDouble();
961 for (unsigned i = 0; i < elemNum; ++i)
962 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
966 // Check if vector holds integers.
967 if (ElemTy->isIntegerTy()) {
969 GenericValue intZero;
970 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
971 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
976 for (unsigned i = 0; i < elemNum; ++i)
977 if (!isa<UndefValue>(CV->getOperand(i)))
978 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
979 CV->getOperand(i))->getValue();
981 Result.AggregateVal[i].IntVal =
982 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
987 for (unsigned i = 0; i < elemNum; ++i)
988 Result.AggregateVal[i].IntVal = APInt(
989 CDV->getElementType()->getPrimitiveSizeInBits(),
990 CDV->getElementAsInteger(i));
994 llvm_unreachable("Unknown constant pointer type!");
999 SmallString<256> Msg;
1000 raw_svector_ostream OS(Msg);
1001 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1002 report_fatal_error(OS.str());
1008 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1009 /// with the integer held in IntVal.
1010 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1011 unsigned StoreBytes) {
1012 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1013 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1015 if (sys::IsLittleEndianHost) {
1016 // Little-endian host - the source is ordered from LSB to MSB. Order the
1017 // destination from LSB to MSB: Do a straight copy.
1018 memcpy(Dst, Src, StoreBytes);
1020 // Big-endian host - the source is an array of 64 bit words ordered from
1021 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1022 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1023 while (StoreBytes > sizeof(uint64_t)) {
1024 StoreBytes -= sizeof(uint64_t);
1025 // May not be aligned so use memcpy.
1026 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1027 Src += sizeof(uint64_t);
1030 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1034 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1035 GenericValue *Ptr, Type *Ty) {
1036 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
1038 switch (Ty->getTypeID()) {
1040 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1042 case Type::IntegerTyID:
1043 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1045 case Type::FloatTyID:
1046 *((float*)Ptr) = Val.FloatVal;
1048 case Type::DoubleTyID:
1049 *((double*)Ptr) = Val.DoubleVal;
1051 case Type::X86_FP80TyID:
1052 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1054 case Type::PointerTyID:
1055 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1056 if (StoreBytes != sizeof(PointerTy))
1057 memset(&(Ptr->PointerVal), 0, StoreBytes);
1059 *((PointerTy*)Ptr) = Val.PointerVal;
1061 case Type::VectorTyID:
1062 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1063 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1064 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1065 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1066 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1067 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1068 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1069 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1070 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1076 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
1077 // Host and target are different endian - reverse the stored bytes.
1078 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1081 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1082 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1083 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1084 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1085 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1086 const_cast<uint64_t *>(IntVal.getRawData()));
1088 if (sys::IsLittleEndianHost)
1089 // Little-endian host - the destination must be ordered from LSB to MSB.
1090 // The source is ordered from LSB to MSB: Do a straight copy.
1091 memcpy(Dst, Src, LoadBytes);
1093 // Big-endian - the destination is an array of 64 bit words ordered from
1094 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1095 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1097 while (LoadBytes > sizeof(uint64_t)) {
1098 LoadBytes -= sizeof(uint64_t);
1099 // May not be aligned so use memcpy.
1100 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1101 Dst += sizeof(uint64_t);
1104 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1110 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1113 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
1115 switch (Ty->getTypeID()) {
1116 case Type::IntegerTyID:
1117 // An APInt with all words initially zero.
1118 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1119 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1121 case Type::FloatTyID:
1122 Result.FloatVal = *((float*)Ptr);
1124 case Type::DoubleTyID:
1125 Result.DoubleVal = *((double*)Ptr);
1127 case Type::PointerTyID:
1128 Result.PointerVal = *((PointerTy*)Ptr);
1130 case Type::X86_FP80TyID: {
1131 // This is endian dependent, but it will only work on x86 anyway.
1132 // FIXME: Will not trap if loading a signaling NaN.
1135 Result.IntVal = APInt(80, y);
1138 case Type::VectorTyID: {
1139 const VectorType *VT = cast<VectorType>(Ty);
1140 const Type *ElemT = VT->getElementType();
1141 const unsigned numElems = VT->getNumElements();
1142 if (ElemT->isFloatTy()) {
1143 Result.AggregateVal.resize(numElems);
1144 for (unsigned i = 0; i < numElems; ++i)
1145 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1147 if (ElemT->isDoubleTy()) {
1148 Result.AggregateVal.resize(numElems);
1149 for (unsigned i = 0; i < numElems; ++i)
1150 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1152 if (ElemT->isIntegerTy()) {
1153 GenericValue intZero;
1154 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1155 intZero.IntVal = APInt(elemBitWidth, 0);
1156 Result.AggregateVal.resize(numElems, intZero);
1157 for (unsigned i = 0; i < numElems; ++i)
1158 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1159 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1164 SmallString<256> Msg;
1165 raw_svector_ostream OS(Msg);
1166 OS << "Cannot load value of type " << *Ty << "!";
1167 report_fatal_error(OS.str());
1171 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1172 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1173 DEBUG(Init->dump());
1174 if (isa<UndefValue>(Init))
1177 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1178 unsigned ElementSize =
1179 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
1180 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1181 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1185 if (isa<ConstantAggregateZero>(Init)) {
1186 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
1190 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1191 unsigned ElementSize =
1192 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
1193 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1194 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1198 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1199 const StructLayout *SL =
1200 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
1201 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1202 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1206 if (const ConstantDataSequential *CDS =
1207 dyn_cast<ConstantDataSequential>(Init)) {
1208 // CDS is already laid out in host memory order.
1209 StringRef Data = CDS->getRawDataValues();
1210 memcpy(Addr, Data.data(), Data.size());
1214 if (Init->getType()->isFirstClassType()) {
1215 GenericValue Val = getConstantValue(Init);
1216 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1220 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1221 llvm_unreachable("Unknown constant type to initialize memory with!");
1224 /// EmitGlobals - Emit all of the global variables to memory, storing their
1225 /// addresses into GlobalAddress. This must make sure to copy the contents of
1226 /// their initializers into the memory.
1227 void ExecutionEngine::emitGlobals() {
1228 // Loop over all of the global variables in the program, allocating the memory
1229 // to hold them. If there is more than one module, do a prepass over globals
1230 // to figure out how the different modules should link together.
1231 std::map<std::pair<std::string, Type*>,
1232 const GlobalValue*> LinkedGlobalsMap;
1234 if (Modules.size() != 1) {
1235 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1236 Module &M = *Modules[m];
1237 for (const auto &GV : M.globals()) {
1238 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1239 GV.hasAppendingLinkage() || !GV.hasName())
1240 continue;// Ignore external globals and globals with internal linkage.
1242 const GlobalValue *&GVEntry =
1243 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1245 // If this is the first time we've seen this global, it is the canonical
1252 // If the existing global is strong, never replace it.
1253 if (GVEntry->hasExternalLinkage())
1256 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1257 // symbol. FIXME is this right for common?
1258 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1264 std::vector<const GlobalValue*> NonCanonicalGlobals;
1265 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1266 Module &M = *Modules[m];
1267 for (const auto &GV : M.globals()) {
1268 // In the multi-module case, see what this global maps to.
1269 if (!LinkedGlobalsMap.empty()) {
1270 if (const GlobalValue *GVEntry =
1271 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1272 // If something else is the canonical global, ignore this one.
1273 if (GVEntry != &GV) {
1274 NonCanonicalGlobals.push_back(&GV);
1280 if (!GV.isDeclaration()) {
1281 addGlobalMapping(&GV, getMemoryForGV(&GV));
1283 // External variable reference. Try to use the dynamic loader to
1284 // get a pointer to it.
1286 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1287 addGlobalMapping(&GV, SymAddr);
1289 report_fatal_error("Could not resolve external global address: "
1295 // If there are multiple modules, map the non-canonical globals to their
1296 // canonical location.
1297 if (!NonCanonicalGlobals.empty()) {
1298 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1299 const GlobalValue *GV = NonCanonicalGlobals[i];
1300 const GlobalValue *CGV =
1301 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1302 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1303 assert(Ptr && "Canonical global wasn't codegen'd!");
1304 addGlobalMapping(GV, Ptr);
1308 // Now that all of the globals are set up in memory, loop through them all
1309 // and initialize their contents.
1310 for (const auto &GV : M.globals()) {
1311 if (!GV.isDeclaration()) {
1312 if (!LinkedGlobalsMap.empty()) {
1313 if (const GlobalValue *GVEntry =
1314 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1315 if (GVEntry != &GV) // Not the canonical variable.
1318 EmitGlobalVariable(&GV);
1324 // EmitGlobalVariable - This method emits the specified global variable to the
1325 // address specified in GlobalAddresses, or allocates new memory if it's not
1326 // already in the map.
1327 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1328 void *GA = getPointerToGlobalIfAvailable(GV);
1331 // If it's not already specified, allocate memory for the global.
1332 GA = getMemoryForGV(GV);
1334 // If we failed to allocate memory for this global, return.
1337 addGlobalMapping(GV, GA);
1340 // Don't initialize if it's thread local, let the client do it.
1341 if (!GV->isThreadLocal())
1342 InitializeMemory(GV->getInitializer(), GA);
1344 Type *ElTy = GV->getType()->getElementType();
1345 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
1346 NumInitBytes += (unsigned)GVSize;