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/Support/Debug.h"
28 #include "llvm/Support/DynamicLibrary.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/MutexGuard.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
39 #define DEBUG_TYPE "jit"
41 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
42 STATISTIC(NumGlobals , "Number of global vars initialized");
44 // Pin the vtable to this file.
45 void ObjectCache::anchor() {}
46 void ObjectBuffer::anchor() {}
47 void ObjectBufferStream::anchor() {}
49 ExecutionEngine *(*ExecutionEngine::JITCtor)(
51 std::string *ErrorStr,
52 JITMemoryManager *JMM,
54 TargetMachine *TM) = nullptr;
55 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
57 std::string *ErrorStr,
58 RTDyldMemoryManager *MCJMM,
60 TargetMachine *TM) = nullptr;
61 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
62 std::string *ErrorStr) =nullptr;
64 ExecutionEngine::ExecutionEngine(Module *M)
66 LazyFunctionCreator(nullptr) {
67 CompilingLazily = false;
68 GVCompilationDisabled = false;
69 SymbolSearchingDisabled = false;
71 // IR module verification is enabled by default in debug builds, and disabled
72 // by default in release builds.
76 VerifyModules = false;
80 assert(M && "Module is null?");
83 ExecutionEngine::~ExecutionEngine() {
84 clearAllGlobalMappings();
85 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
90 /// \brief Helper class which uses a value handler to automatically deletes the
91 /// memory block when the GlobalVariable is destroyed.
92 class GVMemoryBlock : public CallbackVH {
93 GVMemoryBlock(const GlobalVariable *GV)
94 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
97 /// \brief Returns the address the GlobalVariable should be written into. The
98 /// GVMemoryBlock object prefixes that.
99 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
100 Type *ElTy = GV->getType()->getElementType();
101 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
102 void *RawMemory = ::operator new(
103 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
104 TD.getPreferredAlignment(GV))
106 new(RawMemory) GVMemoryBlock(GV);
107 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
110 void deleted() override {
111 // We allocated with operator new and with some extra memory hanging off the
112 // end, so don't just delete this. I'm not sure if this is actually
114 this->~GVMemoryBlock();
115 ::operator delete(this);
118 } // anonymous namespace
120 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
121 return GVMemoryBlock::Create(GV, *getDataLayout());
124 bool ExecutionEngine::removeModule(Module *M) {
125 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
126 E = Modules.end(); I != E; ++I) {
130 clearGlobalMappingsFromModule(M);
137 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
138 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
139 if (Function *F = Modules[i]->getFunction(FnName))
146 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
147 const GlobalValue *ToUnmap) {
148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
153 if (I == GlobalAddressMap.end())
157 GlobalAddressMap.erase(I);
160 GlobalAddressReverseMap.erase(OldVal);
164 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
165 MutexGuard locked(lock);
167 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
168 << "\' to [" << Addr << "]\n";);
169 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
170 assert((!CurVal || !Addr) && "GlobalMapping already established!");
173 // If we are using the reverse mapping, add it too.
174 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
175 AssertingVH<const GlobalValue> &V =
176 EEState.getGlobalAddressReverseMap(locked)[Addr];
177 assert((!V || !GV) && "GlobalMapping already established!");
182 void ExecutionEngine::clearAllGlobalMappings() {
183 MutexGuard locked(lock);
185 EEState.getGlobalAddressMap(locked).clear();
186 EEState.getGlobalAddressReverseMap(locked).clear();
189 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
192 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
193 EEState.RemoveMapping(locked, FI);
194 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
196 EEState.RemoveMapping(locked, GI);
199 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
200 MutexGuard locked(lock);
202 ExecutionEngineState::GlobalAddressMapTy &Map =
203 EEState.getGlobalAddressMap(locked);
205 // Deleting from the mapping?
207 return EEState.RemoveMapping(locked, GV);
209 void *&CurVal = Map[GV];
210 void *OldVal = CurVal;
212 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
213 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
216 // If we are using the reverse mapping, add it too.
217 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
218 AssertingVH<const GlobalValue> &V =
219 EEState.getGlobalAddressReverseMap(locked)[Addr];
220 assert((!V || !GV) && "GlobalMapping already established!");
226 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
227 MutexGuard locked(lock);
229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
230 EEState.getGlobalAddressMap(locked).find(GV);
231 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
234 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
235 MutexGuard locked(lock);
237 // If we haven't computed the reverse mapping yet, do so first.
238 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
239 for (ExecutionEngineState::GlobalAddressMapTy::iterator
240 I = EEState.getGlobalAddressMap(locked).begin(),
241 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
242 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
243 I->second, I->first));
246 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
247 EEState.getGlobalAddressReverseMap(locked).find(Addr);
248 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
254 std::vector<char*> Values;
256 ArgvArray() : Array(nullptr) {}
257 ~ArgvArray() { clear(); }
261 for (size_t I = 0, E = Values.size(); I != E; ++I) {
266 /// Turn a vector of strings into a nice argv style array of pointers to null
267 /// terminated strings.
268 void *reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv);
271 } // anonymous namespace
272 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv) {
274 clear(); // Free the old contents.
275 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
276 Array = new char[(InputArgv.size()+1)*PtrSize];
278 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
279 Type *SBytePtr = Type::getInt8PtrTy(C);
281 for (unsigned i = 0; i != InputArgv.size(); ++i) {
282 unsigned Size = InputArgv[i].size()+1;
283 char *Dest = new char[Size];
284 Values.push_back(Dest);
285 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
287 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
290 // Endian safe: Array[i] = (PointerTy)Dest;
291 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
296 EE->StoreValueToMemory(PTOGV(nullptr),
297 (GenericValue*)(Array+InputArgv.size()*PtrSize),
302 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
304 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
305 GlobalVariable *GV = module->getNamedGlobal(Name);
307 // If this global has internal linkage, or if it has a use, then it must be
308 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
309 // this is the case, don't execute any of the global ctors, __main will do
311 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
313 // Should be an array of '{ i32, void ()* }' structs. The first value is
314 // the init priority, which we ignore.
315 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
318 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
319 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
322 Constant *FP = CS->getOperand(1);
323 if (FP->isNullValue())
324 continue; // Found a sentinal value, ignore.
326 // Strip off constant expression casts.
327 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
329 FP = CE->getOperand(0);
331 // Execute the ctor/dtor function!
332 if (Function *F = dyn_cast<Function>(FP))
333 runFunction(F, std::vector<GenericValue>());
335 // FIXME: It is marginally lame that we just do nothing here if we see an
336 // entry we don't recognize. It might not be unreasonable for the verifier
337 // to not even allow this and just assert here.
341 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
342 // Execute global ctors/dtors for each module in the program.
343 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
344 runStaticConstructorsDestructors(Modules[i], isDtors);
348 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
349 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
350 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
351 for (unsigned i = 0; i < PtrSize; ++i)
352 if (*(i + (uint8_t*)Loc))
358 int ExecutionEngine::runFunctionAsMain(Function *Fn,
359 const std::vector<std::string> &argv,
360 const char * const * envp) {
361 std::vector<GenericValue> GVArgs;
363 GVArgc.IntVal = APInt(32, argv.size());
366 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
367 FunctionType *FTy = Fn->getFunctionType();
368 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
370 // Check the argument types.
372 report_fatal_error("Invalid number of arguments of main() supplied");
373 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
374 report_fatal_error("Invalid type for third argument of main() supplied");
375 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
376 report_fatal_error("Invalid type for second argument of main() supplied");
377 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
378 report_fatal_error("Invalid type for first argument of main() supplied");
379 if (!FTy->getReturnType()->isIntegerTy() &&
380 !FTy->getReturnType()->isVoidTy())
381 report_fatal_error("Invalid return type of main() supplied");
386 GVArgs.push_back(GVArgc); // Arg #0 = argc.
389 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
390 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
391 "argv[0] was null after CreateArgv");
393 std::vector<std::string> EnvVars;
394 for (unsigned i = 0; envp[i]; ++i)
395 EnvVars.push_back(envp[i]);
397 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
402 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
405 ExecutionEngine *ExecutionEngine::create(Module *M,
406 bool ForceInterpreter,
407 std::string *ErrorStr,
408 CodeGenOpt::Level OptLevel,
410 EngineBuilder EB = EngineBuilder(M)
411 .setEngineKind(ForceInterpreter
412 ? EngineKind::Interpreter
414 .setErrorStr(ErrorStr)
415 .setOptLevel(OptLevel)
416 .setAllocateGVsWithCode(GVsWithCode);
421 /// createJIT - This is the factory method for creating a JIT for the current
422 /// machine, it does not fall back to the interpreter. This takes ownership
424 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
425 std::string *ErrorStr,
426 JITMemoryManager *JMM,
427 CodeGenOpt::Level OL,
430 CodeModel::Model CMM) {
431 if (!ExecutionEngine::JITCtor) {
433 *ErrorStr = "JIT has not been linked in.";
437 // Use the defaults for extra parameters. Users can use EngineBuilder to
440 EB.setEngineKind(EngineKind::JIT);
441 EB.setErrorStr(ErrorStr);
442 EB.setRelocationModel(RM);
443 EB.setCodeModel(CMM);
444 EB.setAllocateGVsWithCode(GVsWithCode);
446 EB.setJITMemoryManager(JMM);
448 // TODO: permit custom TargetOptions here
449 TargetMachine *TM = EB.selectTarget();
450 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
452 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
455 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
456 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
458 // Make sure we can resolve symbols in the program as well. The zero arg
459 // to the function tells DynamicLibrary to load the program, not a library.
460 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
463 assert(!(JMM && MCJMM));
465 // If the user specified a memory manager but didn't specify which engine to
466 // create, we assume they only want the JIT, and we fail if they only want
469 if (WhichEngine & EngineKind::JIT)
470 WhichEngine = EngineKind::JIT;
473 *ErrorStr = "Cannot create an interpreter with a memory manager.";
478 if (MCJMM && ! UseMCJIT) {
481 "Cannot create a legacy JIT with a runtime dyld memory "
486 // Unless the interpreter was explicitly selected or the JIT is not linked,
488 if ((WhichEngine & EngineKind::JIT) && TheTM) {
489 Triple TT(M->getTargetTriple());
490 if (!TM->getTarget().hasJIT()) {
491 errs() << "WARNING: This target JIT is not designed for the host"
492 << " you are running. If bad things happen, please choose"
493 << " a different -march switch.\n";
496 ExecutionEngine *EE = nullptr;
497 if (UseMCJIT && ExecutionEngine::MCJITCtor)
498 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
499 AllocateGVsWithCode, TheTM.release());
500 else if (ExecutionEngine::JITCtor)
501 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
502 AllocateGVsWithCode, TheTM.release());
505 EE->setVerifyModules(VerifyModules);
510 // If we can't make a JIT and we didn't request one specifically, try making
511 // an interpreter instead.
512 if (WhichEngine & EngineKind::Interpreter) {
513 if (ExecutionEngine::InterpCtor)
514 return ExecutionEngine::InterpCtor(M, ErrorStr);
516 *ErrorStr = "Interpreter has not been linked in.";
520 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
521 !ExecutionEngine::MCJITCtor) {
523 *ErrorStr = "JIT has not been linked in.";
529 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
530 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
531 return getPointerToFunction(F);
533 MutexGuard locked(lock);
534 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
537 // Global variable might have been added since interpreter started.
538 if (GlobalVariable *GVar =
539 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
540 EmitGlobalVariable(GVar);
542 llvm_unreachable("Global hasn't had an address allocated yet!");
544 return EEState.getGlobalAddressMap(locked)[GV];
547 /// \brief Converts a Constant* into a GenericValue, including handling of
548 /// ConstantExpr values.
549 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
550 // If its undefined, return the garbage.
551 if (isa<UndefValue>(C)) {
553 switch (C->getType()->getTypeID()) {
556 case Type::IntegerTyID:
557 case Type::X86_FP80TyID:
558 case Type::FP128TyID:
559 case Type::PPC_FP128TyID:
560 // Although the value is undefined, we still have to construct an APInt
561 // with the correct bit width.
562 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
564 case Type::StructTyID: {
565 // if the whole struct is 'undef' just reserve memory for the value.
566 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
567 unsigned int elemNum = STy->getNumElements();
568 Result.AggregateVal.resize(elemNum);
569 for (unsigned int i = 0; i < elemNum; ++i) {
570 Type *ElemTy = STy->getElementType(i);
571 if (ElemTy->isIntegerTy())
572 Result.AggregateVal[i].IntVal =
573 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
574 else if (ElemTy->isAggregateType()) {
575 const Constant *ElemUndef = UndefValue::get(ElemTy);
576 Result.AggregateVal[i] = getConstantValue(ElemUndef);
582 case Type::VectorTyID:
583 // if the whole vector is 'undef' just reserve memory for the value.
584 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
585 const Type *ElemTy = VTy->getElementType();
586 unsigned int elemNum = VTy->getNumElements();
587 Result.AggregateVal.resize(elemNum);
588 if (ElemTy->isIntegerTy())
589 for (unsigned int i = 0; i < elemNum; ++i)
590 Result.AggregateVal[i].IntVal =
591 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
597 // Otherwise, if the value is a ConstantExpr...
598 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
599 Constant *Op0 = CE->getOperand(0);
600 switch (CE->getOpcode()) {
601 case Instruction::GetElementPtr: {
603 GenericValue Result = getConstantValue(Op0);
604 APInt Offset(DL->getPointerSizeInBits(), 0);
605 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
607 char* tmp = (char*) Result.PointerVal;
608 Result = PTOGV(tmp + Offset.getSExtValue());
611 case Instruction::Trunc: {
612 GenericValue GV = getConstantValue(Op0);
613 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
614 GV.IntVal = GV.IntVal.trunc(BitWidth);
617 case Instruction::ZExt: {
618 GenericValue GV = getConstantValue(Op0);
619 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
620 GV.IntVal = GV.IntVal.zext(BitWidth);
623 case Instruction::SExt: {
624 GenericValue GV = getConstantValue(Op0);
625 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
626 GV.IntVal = GV.IntVal.sext(BitWidth);
629 case Instruction::FPTrunc: {
631 GenericValue GV = getConstantValue(Op0);
632 GV.FloatVal = float(GV.DoubleVal);
635 case Instruction::FPExt:{
637 GenericValue GV = getConstantValue(Op0);
638 GV.DoubleVal = double(GV.FloatVal);
641 case Instruction::UIToFP: {
642 GenericValue GV = getConstantValue(Op0);
643 if (CE->getType()->isFloatTy())
644 GV.FloatVal = float(GV.IntVal.roundToDouble());
645 else if (CE->getType()->isDoubleTy())
646 GV.DoubleVal = GV.IntVal.roundToDouble();
647 else if (CE->getType()->isX86_FP80Ty()) {
648 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
649 (void)apf.convertFromAPInt(GV.IntVal,
651 APFloat::rmNearestTiesToEven);
652 GV.IntVal = apf.bitcastToAPInt();
656 case Instruction::SIToFP: {
657 GenericValue GV = getConstantValue(Op0);
658 if (CE->getType()->isFloatTy())
659 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
660 else if (CE->getType()->isDoubleTy())
661 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
662 else if (CE->getType()->isX86_FP80Ty()) {
663 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
664 (void)apf.convertFromAPInt(GV.IntVal,
666 APFloat::rmNearestTiesToEven);
667 GV.IntVal = apf.bitcastToAPInt();
671 case Instruction::FPToUI: // double->APInt conversion handles sign
672 case Instruction::FPToSI: {
673 GenericValue GV = getConstantValue(Op0);
674 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
675 if (Op0->getType()->isFloatTy())
676 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
677 else if (Op0->getType()->isDoubleTy())
678 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
679 else if (Op0->getType()->isX86_FP80Ty()) {
680 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
683 (void)apf.convertToInteger(&v, BitWidth,
684 CE->getOpcode()==Instruction::FPToSI,
685 APFloat::rmTowardZero, &ignored);
686 GV.IntVal = v; // endian?
690 case Instruction::PtrToInt: {
691 GenericValue GV = getConstantValue(Op0);
692 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
693 assert(PtrWidth <= 64 && "Bad pointer width");
694 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
695 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
696 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
699 case Instruction::IntToPtr: {
700 GenericValue GV = getConstantValue(Op0);
701 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
702 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
703 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
704 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
707 case Instruction::BitCast: {
708 GenericValue GV = getConstantValue(Op0);
709 Type* DestTy = CE->getType();
710 switch (Op0->getType()->getTypeID()) {
711 default: llvm_unreachable("Invalid bitcast operand");
712 case Type::IntegerTyID:
713 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
714 if (DestTy->isFloatTy())
715 GV.FloatVal = GV.IntVal.bitsToFloat();
716 else if (DestTy->isDoubleTy())
717 GV.DoubleVal = GV.IntVal.bitsToDouble();
719 case Type::FloatTyID:
720 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
721 GV.IntVal = APInt::floatToBits(GV.FloatVal);
723 case Type::DoubleTyID:
724 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
725 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
727 case Type::PointerTyID:
728 assert(DestTy->isPointerTy() && "Invalid bitcast");
729 break; // getConstantValue(Op0) above already converted it
733 case Instruction::Add:
734 case Instruction::FAdd:
735 case Instruction::Sub:
736 case Instruction::FSub:
737 case Instruction::Mul:
738 case Instruction::FMul:
739 case Instruction::UDiv:
740 case Instruction::SDiv:
741 case Instruction::URem:
742 case Instruction::SRem:
743 case Instruction::And:
744 case Instruction::Or:
745 case Instruction::Xor: {
746 GenericValue LHS = getConstantValue(Op0);
747 GenericValue RHS = getConstantValue(CE->getOperand(1));
749 switch (CE->getOperand(0)->getType()->getTypeID()) {
750 default: llvm_unreachable("Bad add type!");
751 case Type::IntegerTyID:
752 switch (CE->getOpcode()) {
753 default: llvm_unreachable("Invalid integer opcode");
754 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
755 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
756 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
757 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
758 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
759 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
760 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
761 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
762 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
763 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
766 case Type::FloatTyID:
767 switch (CE->getOpcode()) {
768 default: llvm_unreachable("Invalid float opcode");
769 case Instruction::FAdd:
770 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
771 case Instruction::FSub:
772 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
773 case Instruction::FMul:
774 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
775 case Instruction::FDiv:
776 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
777 case Instruction::FRem:
778 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
781 case Type::DoubleTyID:
782 switch (CE->getOpcode()) {
783 default: llvm_unreachable("Invalid double opcode");
784 case Instruction::FAdd:
785 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
786 case Instruction::FSub:
787 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
788 case Instruction::FMul:
789 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
790 case Instruction::FDiv:
791 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
792 case Instruction::FRem:
793 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
796 case Type::X86_FP80TyID:
797 case Type::PPC_FP128TyID:
798 case Type::FP128TyID: {
799 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
800 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
801 switch (CE->getOpcode()) {
802 default: llvm_unreachable("Invalid long double opcode");
803 case Instruction::FAdd:
804 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
805 GV.IntVal = apfLHS.bitcastToAPInt();
807 case Instruction::FSub:
808 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
809 APFloat::rmNearestTiesToEven);
810 GV.IntVal = apfLHS.bitcastToAPInt();
812 case Instruction::FMul:
813 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
814 APFloat::rmNearestTiesToEven);
815 GV.IntVal = apfLHS.bitcastToAPInt();
817 case Instruction::FDiv:
818 apfLHS.divide(APFloat(Sem, RHS.IntVal),
819 APFloat::rmNearestTiesToEven);
820 GV.IntVal = apfLHS.bitcastToAPInt();
822 case Instruction::FRem:
823 apfLHS.mod(APFloat(Sem, RHS.IntVal),
824 APFloat::rmNearestTiesToEven);
825 GV.IntVal = apfLHS.bitcastToAPInt();
837 SmallString<256> Msg;
838 raw_svector_ostream OS(Msg);
839 OS << "ConstantExpr not handled: " << *CE;
840 report_fatal_error(OS.str());
843 // Otherwise, we have a simple constant.
845 switch (C->getType()->getTypeID()) {
846 case Type::FloatTyID:
847 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
849 case Type::DoubleTyID:
850 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
852 case Type::X86_FP80TyID:
853 case Type::FP128TyID:
854 case Type::PPC_FP128TyID:
855 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
857 case Type::IntegerTyID:
858 Result.IntVal = cast<ConstantInt>(C)->getValue();
860 case Type::PointerTyID:
861 if (isa<ConstantPointerNull>(C))
862 Result.PointerVal = nullptr;
863 else if (const Function *F = dyn_cast<Function>(C))
864 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
865 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
866 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
867 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
868 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
869 BA->getBasicBlock())));
871 llvm_unreachable("Unknown constant pointer type!");
873 case Type::VectorTyID: {
876 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
877 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
878 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
881 elemNum = CDV->getNumElements();
882 ElemTy = CDV->getElementType();
883 } else if (CV || CAZ) {
884 VectorType* VTy = dyn_cast<VectorType>(C->getType());
885 elemNum = VTy->getNumElements();
886 ElemTy = VTy->getElementType();
888 llvm_unreachable("Unknown constant vector type!");
891 Result.AggregateVal.resize(elemNum);
892 // Check if vector holds floats.
893 if(ElemTy->isFloatTy()) {
895 GenericValue floatZero;
896 floatZero.FloatVal = 0.f;
897 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
902 for (unsigned i = 0; i < elemNum; ++i)
903 if (!isa<UndefValue>(CV->getOperand(i)))
904 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
905 CV->getOperand(i))->getValueAPF().convertToFloat();
909 for (unsigned i = 0; i < elemNum; ++i)
910 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
914 // Check if vector holds doubles.
915 if (ElemTy->isDoubleTy()) {
917 GenericValue doubleZero;
918 doubleZero.DoubleVal = 0.0;
919 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
924 for (unsigned i = 0; i < elemNum; ++i)
925 if (!isa<UndefValue>(CV->getOperand(i)))
926 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
927 CV->getOperand(i))->getValueAPF().convertToDouble();
931 for (unsigned i = 0; i < elemNum; ++i)
932 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
936 // Check if vector holds integers.
937 if (ElemTy->isIntegerTy()) {
939 GenericValue intZero;
940 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
941 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
946 for (unsigned i = 0; i < elemNum; ++i)
947 if (!isa<UndefValue>(CV->getOperand(i)))
948 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
949 CV->getOperand(i))->getValue();
951 Result.AggregateVal[i].IntVal =
952 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
957 for (unsigned i = 0; i < elemNum; ++i)
958 Result.AggregateVal[i].IntVal = APInt(
959 CDV->getElementType()->getPrimitiveSizeInBits(),
960 CDV->getElementAsInteger(i));
964 llvm_unreachable("Unknown constant pointer type!");
969 SmallString<256> Msg;
970 raw_svector_ostream OS(Msg);
971 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
972 report_fatal_error(OS.str());
978 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
979 /// with the integer held in IntVal.
980 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
981 unsigned StoreBytes) {
982 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
983 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
985 if (sys::IsLittleEndianHost) {
986 // Little-endian host - the source is ordered from LSB to MSB. Order the
987 // destination from LSB to MSB: Do a straight copy.
988 memcpy(Dst, Src, StoreBytes);
990 // Big-endian host - the source is an array of 64 bit words ordered from
991 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
992 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
993 while (StoreBytes > sizeof(uint64_t)) {
994 StoreBytes -= sizeof(uint64_t);
995 // May not be aligned so use memcpy.
996 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
997 Src += sizeof(uint64_t);
1000 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1004 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1005 GenericValue *Ptr, Type *Ty) {
1006 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
1008 switch (Ty->getTypeID()) {
1010 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1012 case Type::IntegerTyID:
1013 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1015 case Type::FloatTyID:
1016 *((float*)Ptr) = Val.FloatVal;
1018 case Type::DoubleTyID:
1019 *((double*)Ptr) = Val.DoubleVal;
1021 case Type::X86_FP80TyID:
1022 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1024 case Type::PointerTyID:
1025 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1026 if (StoreBytes != sizeof(PointerTy))
1027 memset(&(Ptr->PointerVal), 0, StoreBytes);
1029 *((PointerTy*)Ptr) = Val.PointerVal;
1031 case Type::VectorTyID:
1032 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1033 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1034 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1035 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1036 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1037 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1038 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1039 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1040 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1046 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1047 // Host and target are different endian - reverse the stored bytes.
1048 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1051 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1052 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1053 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1054 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1055 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1056 const_cast<uint64_t *>(IntVal.getRawData()));
1058 if (sys::IsLittleEndianHost)
1059 // Little-endian host - the destination must be ordered from LSB to MSB.
1060 // The source is ordered from LSB to MSB: Do a straight copy.
1061 memcpy(Dst, Src, LoadBytes);
1063 // Big-endian - the destination is an array of 64 bit words ordered from
1064 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1065 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1067 while (LoadBytes > sizeof(uint64_t)) {
1068 LoadBytes -= sizeof(uint64_t);
1069 // May not be aligned so use memcpy.
1070 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1071 Dst += sizeof(uint64_t);
1074 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1080 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1083 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1085 switch (Ty->getTypeID()) {
1086 case Type::IntegerTyID:
1087 // An APInt with all words initially zero.
1088 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1089 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1091 case Type::FloatTyID:
1092 Result.FloatVal = *((float*)Ptr);
1094 case Type::DoubleTyID:
1095 Result.DoubleVal = *((double*)Ptr);
1097 case Type::PointerTyID:
1098 Result.PointerVal = *((PointerTy*)Ptr);
1100 case Type::X86_FP80TyID: {
1101 // This is endian dependent, but it will only work on x86 anyway.
1102 // FIXME: Will not trap if loading a signaling NaN.
1105 Result.IntVal = APInt(80, y);
1108 case Type::VectorTyID: {
1109 const VectorType *VT = cast<VectorType>(Ty);
1110 const Type *ElemT = VT->getElementType();
1111 const unsigned numElems = VT->getNumElements();
1112 if (ElemT->isFloatTy()) {
1113 Result.AggregateVal.resize(numElems);
1114 for (unsigned i = 0; i < numElems; ++i)
1115 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1117 if (ElemT->isDoubleTy()) {
1118 Result.AggregateVal.resize(numElems);
1119 for (unsigned i = 0; i < numElems; ++i)
1120 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1122 if (ElemT->isIntegerTy()) {
1123 GenericValue intZero;
1124 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1125 intZero.IntVal = APInt(elemBitWidth, 0);
1126 Result.AggregateVal.resize(numElems, intZero);
1127 for (unsigned i = 0; i < numElems; ++i)
1128 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1129 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1134 SmallString<256> Msg;
1135 raw_svector_ostream OS(Msg);
1136 OS << "Cannot load value of type " << *Ty << "!";
1137 report_fatal_error(OS.str());
1141 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1142 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1143 DEBUG(Init->dump());
1144 if (isa<UndefValue>(Init))
1147 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1148 unsigned ElementSize =
1149 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1150 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1151 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1155 if (isa<ConstantAggregateZero>(Init)) {
1156 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1160 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1161 unsigned ElementSize =
1162 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1163 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1164 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1168 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1169 const StructLayout *SL =
1170 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1171 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1172 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1176 if (const ConstantDataSequential *CDS =
1177 dyn_cast<ConstantDataSequential>(Init)) {
1178 // CDS is already laid out in host memory order.
1179 StringRef Data = CDS->getRawDataValues();
1180 memcpy(Addr, Data.data(), Data.size());
1184 if (Init->getType()->isFirstClassType()) {
1185 GenericValue Val = getConstantValue(Init);
1186 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1190 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1191 llvm_unreachable("Unknown constant type to initialize memory with!");
1194 /// EmitGlobals - Emit all of the global variables to memory, storing their
1195 /// addresses into GlobalAddress. This must make sure to copy the contents of
1196 /// their initializers into the memory.
1197 void ExecutionEngine::emitGlobals() {
1198 // Loop over all of the global variables in the program, allocating the memory
1199 // to hold them. If there is more than one module, do a prepass over globals
1200 // to figure out how the different modules should link together.
1201 std::map<std::pair<std::string, Type*>,
1202 const GlobalValue*> LinkedGlobalsMap;
1204 if (Modules.size() != 1) {
1205 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1206 Module &M = *Modules[m];
1207 for (Module::const_global_iterator I = M.global_begin(),
1208 E = M.global_end(); I != E; ++I) {
1209 const GlobalValue *GV = I;
1210 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1211 GV->hasAppendingLinkage() || !GV->hasName())
1212 continue;// Ignore external globals and globals with internal linkage.
1214 const GlobalValue *&GVEntry =
1215 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1217 // If this is the first time we've seen this global, it is the canonical
1224 // If the existing global is strong, never replace it.
1225 if (GVEntry->hasExternalLinkage())
1228 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1229 // symbol. FIXME is this right for common?
1230 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1236 std::vector<const GlobalValue*> NonCanonicalGlobals;
1237 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1238 Module &M = *Modules[m];
1239 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1241 // In the multi-module case, see what this global maps to.
1242 if (!LinkedGlobalsMap.empty()) {
1243 if (const GlobalValue *GVEntry =
1244 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1245 // If something else is the canonical global, ignore this one.
1246 if (GVEntry != &*I) {
1247 NonCanonicalGlobals.push_back(I);
1253 if (!I->isDeclaration()) {
1254 addGlobalMapping(I, getMemoryForGV(I));
1256 // External variable reference. Try to use the dynamic loader to
1257 // get a pointer to it.
1259 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1260 addGlobalMapping(I, SymAddr);
1262 report_fatal_error("Could not resolve external global address: "
1268 // If there are multiple modules, map the non-canonical globals to their
1269 // canonical location.
1270 if (!NonCanonicalGlobals.empty()) {
1271 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1272 const GlobalValue *GV = NonCanonicalGlobals[i];
1273 const GlobalValue *CGV =
1274 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1275 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1276 assert(Ptr && "Canonical global wasn't codegen'd!");
1277 addGlobalMapping(GV, Ptr);
1281 // Now that all of the globals are set up in memory, loop through them all
1282 // and initialize their contents.
1283 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1285 if (!I->isDeclaration()) {
1286 if (!LinkedGlobalsMap.empty()) {
1287 if (const GlobalValue *GVEntry =
1288 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1289 if (GVEntry != &*I) // Not the canonical variable.
1292 EmitGlobalVariable(I);
1298 // EmitGlobalVariable - This method emits the specified global variable to the
1299 // address specified in GlobalAddresses, or allocates new memory if it's not
1300 // already in the map.
1301 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1302 void *GA = getPointerToGlobalIfAvailable(GV);
1305 // If it's not already specified, allocate memory for the global.
1306 GA = getMemoryForGV(GV);
1308 // If we failed to allocate memory for this global, return.
1311 addGlobalMapping(GV, GA);
1314 // Don't initialize if it's thread local, let the client do it.
1315 if (!GV->isThreadLocal())
1316 InitializeMemory(GV->getInitializer(), GA);
1318 Type *ElTy = GV->getType()->getElementType();
1319 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1320 NumInitBytes += (unsigned)GVSize;
1324 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1325 : EE(EE), GlobalAddressMap(this) {
1329 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1330 return &EES->EE.lock;
1333 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1334 const GlobalValue *Old) {
1335 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1336 EES->GlobalAddressReverseMap.erase(OldVal);
1339 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1340 const GlobalValue *,
1341 const GlobalValue *) {
1342 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1343 " RAUW on a value it has a global mapping for.");