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 CompilingLazily = false;
61 GVCompilationDisabled = false;
62 SymbolSearchingDisabled = false;
64 assert(M && "Module is null?");
67 ExecutionEngine::~ExecutionEngine() {
68 clearAllGlobalMappings();
69 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
74 /// \brief Helper class which uses a value handler to automatically deletes the
75 /// memory block when the GlobalVariable is destroyed.
76 class GVMemoryBlock : public CallbackVH {
77 GVMemoryBlock(const GlobalVariable *GV)
78 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
81 /// \brief Returns the address the GlobalVariable should be written into. The
82 /// GVMemoryBlock object prefixes that.
83 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
84 Type *ElTy = GV->getType()->getElementType();
85 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
86 void *RawMemory = ::operator new(
87 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
88 TD.getPreferredAlignment(GV))
90 new(RawMemory) GVMemoryBlock(GV);
91 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
94 virtual void deleted() {
95 // We allocated with operator new and with some extra memory hanging off the
96 // end, so don't just delete this. I'm not sure if this is actually
98 this->~GVMemoryBlock();
99 ::operator delete(this);
102 } // anonymous namespace
104 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
105 return GVMemoryBlock::Create(GV, *getDataLayout());
108 bool ExecutionEngine::removeModule(Module *M) {
109 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
110 E = Modules.end(); I != E; ++I) {
114 clearGlobalMappingsFromModule(M);
121 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
122 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
123 if (Function *F = Modules[i]->getFunction(FnName))
130 void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
131 const GlobalValue *ToUnmap) {
132 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
135 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
137 if (I == GlobalAddressMap.end())
141 GlobalAddressMap.erase(I);
144 GlobalAddressReverseMap.erase(OldVal);
148 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
149 MutexGuard locked(lock);
151 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
152 << "\' to [" << Addr << "]\n";);
153 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
154 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
157 // If we are using the reverse mapping, add it too.
158 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
159 AssertingVH<const GlobalValue> &V =
160 EEState.getGlobalAddressReverseMap(locked)[Addr];
161 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
166 void ExecutionEngine::clearAllGlobalMappings() {
167 MutexGuard locked(lock);
169 EEState.getGlobalAddressMap(locked).clear();
170 EEState.getGlobalAddressReverseMap(locked).clear();
173 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
174 MutexGuard locked(lock);
176 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
177 EEState.RemoveMapping(locked, FI);
178 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
180 EEState.RemoveMapping(locked, GI);
183 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
184 MutexGuard locked(lock);
186 ExecutionEngineState::GlobalAddressMapTy &Map =
187 EEState.getGlobalAddressMap(locked);
189 // Deleting from the mapping?
191 return EEState.RemoveMapping(locked, GV);
193 void *&CurVal = Map[GV];
194 void *OldVal = CurVal;
196 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
197 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
200 // If we are using the reverse mapping, add it too.
201 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
202 AssertingVH<const GlobalValue> &V =
203 EEState.getGlobalAddressReverseMap(locked)[Addr];
204 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
210 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
211 MutexGuard locked(lock);
213 ExecutionEngineState::GlobalAddressMapTy::iterator I =
214 EEState.getGlobalAddressMap(locked).find(GV);
215 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
218 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
219 MutexGuard locked(lock);
221 // If we haven't computed the reverse mapping yet, do so first.
222 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
223 for (ExecutionEngineState::GlobalAddressMapTy::iterator
224 I = EEState.getGlobalAddressMap(locked).begin(),
225 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
226 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
227 I->second, I->first));
230 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
231 EEState.getGlobalAddressReverseMap(locked).find(Addr);
232 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
238 std::vector<char*> Values;
240 ArgvArray() : Array(NULL) {}
241 ~ArgvArray() { clear(); }
245 for (size_t I = 0, E = Values.size(); I != E; ++I) {
250 /// Turn a vector of strings into a nice argv style array of pointers to null
251 /// terminated strings.
252 void *reset(LLVMContext &C, ExecutionEngine *EE,
253 const std::vector<std::string> &InputArgv);
255 } // anonymous namespace
256 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
257 const std::vector<std::string> &InputArgv) {
258 clear(); // Free the old contents.
259 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
260 Array = new char[(InputArgv.size()+1)*PtrSize];
262 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
263 Type *SBytePtr = Type::getInt8PtrTy(C);
265 for (unsigned i = 0; i != InputArgv.size(); ++i) {
266 unsigned Size = InputArgv[i].size()+1;
267 char *Dest = new char[Size];
268 Values.push_back(Dest);
269 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
271 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
274 // Endian safe: Array[i] = (PointerTy)Dest;
275 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
280 EE->StoreValueToMemory(PTOGV(0),
281 (GenericValue*)(Array+InputArgv.size()*PtrSize),
286 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
288 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
289 GlobalVariable *GV = module->getNamedGlobal(Name);
291 // If this global has internal linkage, or if it has a use, then it must be
292 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
293 // this is the case, don't execute any of the global ctors, __main will do
295 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
297 // Should be an array of '{ i32, void ()* }' structs. The first value is
298 // the init priority, which we ignore.
299 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
302 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
303 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
304 if (CS == 0) continue;
306 Constant *FP = CS->getOperand(1);
307 if (FP->isNullValue())
308 continue; // Found a sentinal value, ignore.
310 // Strip off constant expression casts.
311 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
313 FP = CE->getOperand(0);
315 // Execute the ctor/dtor function!
316 if (Function *F = dyn_cast<Function>(FP))
317 runFunction(F, std::vector<GenericValue>());
319 // FIXME: It is marginally lame that we just do nothing here if we see an
320 // entry we don't recognize. It might not be unreasonable for the verifier
321 // to not even allow this and just assert here.
325 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
326 // Execute global ctors/dtors for each module in the program.
327 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
328 runStaticConstructorsDestructors(Modules[i], isDtors);
332 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
333 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
334 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
335 for (unsigned i = 0; i < PtrSize; ++i)
336 if (*(i + (uint8_t*)Loc))
342 int ExecutionEngine::runFunctionAsMain(Function *Fn,
343 const std::vector<std::string> &argv,
344 const char * const * envp) {
345 std::vector<GenericValue> GVArgs;
347 GVArgc.IntVal = APInt(32, argv.size());
350 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
351 FunctionType *FTy = Fn->getFunctionType();
352 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
354 // Check the argument types.
356 report_fatal_error("Invalid number of arguments of main() supplied");
357 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
358 report_fatal_error("Invalid type for third argument of main() supplied");
359 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
360 report_fatal_error("Invalid type for second argument of main() supplied");
361 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
362 report_fatal_error("Invalid type for first argument of main() supplied");
363 if (!FTy->getReturnType()->isIntegerTy() &&
364 !FTy->getReturnType()->isVoidTy())
365 report_fatal_error("Invalid return type of main() supplied");
370 GVArgs.push_back(GVArgc); // Arg #0 = argc.
373 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
374 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
375 "argv[0] was null after CreateArgv");
377 std::vector<std::string> EnvVars;
378 for (unsigned i = 0; envp[i]; ++i)
379 EnvVars.push_back(envp[i]);
381 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
386 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
389 ExecutionEngine *ExecutionEngine::create(Module *M,
390 bool ForceInterpreter,
391 std::string *ErrorStr,
392 CodeGenOpt::Level OptLevel,
394 EngineBuilder EB = EngineBuilder(M)
395 .setEngineKind(ForceInterpreter
396 ? EngineKind::Interpreter
398 .setErrorStr(ErrorStr)
399 .setOptLevel(OptLevel)
400 .setAllocateGVsWithCode(GVsWithCode);
405 /// createJIT - This is the factory method for creating a JIT for the current
406 /// machine, it does not fall back to the interpreter. This takes ownership
408 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
409 std::string *ErrorStr,
410 JITMemoryManager *JMM,
411 CodeGenOpt::Level OL,
414 CodeModel::Model CMM) {
415 if (ExecutionEngine::JITCtor == 0) {
417 *ErrorStr = "JIT has not been linked in.";
421 // Use the defaults for extra parameters. Users can use EngineBuilder to
424 EB.setEngineKind(EngineKind::JIT);
425 EB.setErrorStr(ErrorStr);
426 EB.setRelocationModel(RM);
427 EB.setCodeModel(CMM);
428 EB.setAllocateGVsWithCode(GVsWithCode);
430 EB.setJITMemoryManager(JMM);
432 // TODO: permit custom TargetOptions here
433 TargetMachine *TM = EB.selectTarget();
434 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
436 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
439 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
440 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
442 // Make sure we can resolve symbols in the program as well. The zero arg
443 // to the function tells DynamicLibrary to load the program, not a library.
444 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
447 assert(!(JMM && MCJMM));
449 // If the user specified a memory manager but didn't specify which engine to
450 // create, we assume they only want the JIT, and we fail if they only want
453 if (WhichEngine & EngineKind::JIT)
454 WhichEngine = EngineKind::JIT;
457 *ErrorStr = "Cannot create an interpreter with a memory manager.";
462 if (MCJMM && ! UseMCJIT) {
465 "Cannot create a legacy JIT with a runtime dyld memory "
470 // Unless the interpreter was explicitly selected or the JIT is not linked,
472 if ((WhichEngine & EngineKind::JIT) && TheTM) {
473 Triple TT(M->getTargetTriple());
474 if (!TM->getTarget().hasJIT()) {
475 errs() << "WARNING: This target JIT is not designed for the host"
476 << " you are running. If bad things happen, please choose"
477 << " a different -march switch.\n";
480 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
481 ExecutionEngine *EE =
482 ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
483 AllocateGVsWithCode, TheTM.take());
485 } else if (ExecutionEngine::JITCtor) {
486 ExecutionEngine *EE =
487 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
488 AllocateGVsWithCode, TheTM.take());
493 // If we can't make a JIT and we didn't request one specifically, try making
494 // an interpreter instead.
495 if (WhichEngine & EngineKind::Interpreter) {
496 if (ExecutionEngine::InterpCtor)
497 return ExecutionEngine::InterpCtor(M, ErrorStr);
499 *ErrorStr = "Interpreter has not been linked in.";
503 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
504 ExecutionEngine::MCJITCtor == 0) {
506 *ErrorStr = "JIT has not been linked in.";
512 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
513 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
514 return getPointerToFunction(F);
516 MutexGuard locked(lock);
517 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
520 // Global variable might have been added since interpreter started.
521 if (GlobalVariable *GVar =
522 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
523 EmitGlobalVariable(GVar);
525 llvm_unreachable("Global hasn't had an address allocated yet!");
527 return EEState.getGlobalAddressMap(locked)[GV];
530 /// \brief Converts a Constant* into a GenericValue, including handling of
531 /// ConstantExpr values.
532 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
533 // If its undefined, return the garbage.
534 if (isa<UndefValue>(C)) {
536 switch (C->getType()->getTypeID()) {
539 case Type::IntegerTyID:
540 case Type::X86_FP80TyID:
541 case Type::FP128TyID:
542 case Type::PPC_FP128TyID:
543 // Although the value is undefined, we still have to construct an APInt
544 // with the correct bit width.
545 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
547 case Type::StructTyID: {
548 // if the whole struct is 'undef' just reserve memory for the value.
549 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
550 unsigned int elemNum = STy->getNumElements();
551 Result.AggregateVal.resize(elemNum);
552 for (unsigned int i = 0; i < elemNum; ++i) {
553 Type *ElemTy = STy->getElementType(i);
554 if (ElemTy->isIntegerTy())
555 Result.AggregateVal[i].IntVal =
556 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
557 else if (ElemTy->isAggregateType()) {
558 const Constant *ElemUndef = UndefValue::get(ElemTy);
559 Result.AggregateVal[i] = getConstantValue(ElemUndef);
565 case Type::VectorTyID:
566 // if the whole vector is 'undef' just reserve memory for the value.
567 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
568 const Type *ElemTy = VTy->getElementType();
569 unsigned int elemNum = VTy->getNumElements();
570 Result.AggregateVal.resize(elemNum);
571 if (ElemTy->isIntegerTy())
572 for (unsigned int i = 0; i < elemNum; ++i)
573 Result.AggregateVal[i].IntVal =
574 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
580 // Otherwise, if the value is a ConstantExpr...
581 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
582 Constant *Op0 = CE->getOperand(0);
583 switch (CE->getOpcode()) {
584 case Instruction::GetElementPtr: {
586 GenericValue Result = getConstantValue(Op0);
587 APInt Offset(TD->getPointerSizeInBits(), 0);
588 cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
590 char* tmp = (char*) Result.PointerVal;
591 Result = PTOGV(tmp + Offset.getSExtValue());
594 case Instruction::Trunc: {
595 GenericValue GV = getConstantValue(Op0);
596 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
597 GV.IntVal = GV.IntVal.trunc(BitWidth);
600 case Instruction::ZExt: {
601 GenericValue GV = getConstantValue(Op0);
602 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
603 GV.IntVal = GV.IntVal.zext(BitWidth);
606 case Instruction::SExt: {
607 GenericValue GV = getConstantValue(Op0);
608 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
609 GV.IntVal = GV.IntVal.sext(BitWidth);
612 case Instruction::FPTrunc: {
614 GenericValue GV = getConstantValue(Op0);
615 GV.FloatVal = float(GV.DoubleVal);
618 case Instruction::FPExt:{
620 GenericValue GV = getConstantValue(Op0);
621 GV.DoubleVal = double(GV.FloatVal);
624 case Instruction::UIToFP: {
625 GenericValue GV = getConstantValue(Op0);
626 if (CE->getType()->isFloatTy())
627 GV.FloatVal = float(GV.IntVal.roundToDouble());
628 else if (CE->getType()->isDoubleTy())
629 GV.DoubleVal = GV.IntVal.roundToDouble();
630 else if (CE->getType()->isX86_FP80Ty()) {
631 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
632 (void)apf.convertFromAPInt(GV.IntVal,
634 APFloat::rmNearestTiesToEven);
635 GV.IntVal = apf.bitcastToAPInt();
639 case Instruction::SIToFP: {
640 GenericValue GV = getConstantValue(Op0);
641 if (CE->getType()->isFloatTy())
642 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
643 else if (CE->getType()->isDoubleTy())
644 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
645 else if (CE->getType()->isX86_FP80Ty()) {
646 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
647 (void)apf.convertFromAPInt(GV.IntVal,
649 APFloat::rmNearestTiesToEven);
650 GV.IntVal = apf.bitcastToAPInt();
654 case Instruction::FPToUI: // double->APInt conversion handles sign
655 case Instruction::FPToSI: {
656 GenericValue GV = getConstantValue(Op0);
657 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
658 if (Op0->getType()->isFloatTy())
659 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
660 else if (Op0->getType()->isDoubleTy())
661 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
662 else if (Op0->getType()->isX86_FP80Ty()) {
663 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
666 (void)apf.convertToInteger(&v, BitWidth,
667 CE->getOpcode()==Instruction::FPToSI,
668 APFloat::rmTowardZero, &ignored);
669 GV.IntVal = v; // endian?
673 case Instruction::PtrToInt: {
674 GenericValue GV = getConstantValue(Op0);
675 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
676 assert(PtrWidth <= 64 && "Bad pointer width");
677 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
678 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
679 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
682 case Instruction::IntToPtr: {
683 GenericValue GV = getConstantValue(Op0);
684 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
685 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
686 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
687 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
690 case Instruction::BitCast: {
691 GenericValue GV = getConstantValue(Op0);
692 Type* DestTy = CE->getType();
693 switch (Op0->getType()->getTypeID()) {
694 default: llvm_unreachable("Invalid bitcast operand");
695 case Type::IntegerTyID:
696 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
697 if (DestTy->isFloatTy())
698 GV.FloatVal = GV.IntVal.bitsToFloat();
699 else if (DestTy->isDoubleTy())
700 GV.DoubleVal = GV.IntVal.bitsToDouble();
702 case Type::FloatTyID:
703 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
704 GV.IntVal = APInt::floatToBits(GV.FloatVal);
706 case Type::DoubleTyID:
707 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
708 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
710 case Type::PointerTyID:
711 assert(DestTy->isPointerTy() && "Invalid bitcast");
712 break; // getConstantValue(Op0) above already converted it
716 case Instruction::Add:
717 case Instruction::FAdd:
718 case Instruction::Sub:
719 case Instruction::FSub:
720 case Instruction::Mul:
721 case Instruction::FMul:
722 case Instruction::UDiv:
723 case Instruction::SDiv:
724 case Instruction::URem:
725 case Instruction::SRem:
726 case Instruction::And:
727 case Instruction::Or:
728 case Instruction::Xor: {
729 GenericValue LHS = getConstantValue(Op0);
730 GenericValue RHS = getConstantValue(CE->getOperand(1));
732 switch (CE->getOperand(0)->getType()->getTypeID()) {
733 default: llvm_unreachable("Bad add type!");
734 case Type::IntegerTyID:
735 switch (CE->getOpcode()) {
736 default: llvm_unreachable("Invalid integer opcode");
737 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
738 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
739 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
740 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
741 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
742 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
743 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
744 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
745 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
746 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
749 case Type::FloatTyID:
750 switch (CE->getOpcode()) {
751 default: llvm_unreachable("Invalid float opcode");
752 case Instruction::FAdd:
753 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
754 case Instruction::FSub:
755 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
756 case Instruction::FMul:
757 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
758 case Instruction::FDiv:
759 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
760 case Instruction::FRem:
761 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
764 case Type::DoubleTyID:
765 switch (CE->getOpcode()) {
766 default: llvm_unreachable("Invalid double opcode");
767 case Instruction::FAdd:
768 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
769 case Instruction::FSub:
770 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
771 case Instruction::FMul:
772 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
773 case Instruction::FDiv:
774 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
775 case Instruction::FRem:
776 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
779 case Type::X86_FP80TyID:
780 case Type::PPC_FP128TyID:
781 case Type::FP128TyID: {
782 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
783 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
784 switch (CE->getOpcode()) {
785 default: llvm_unreachable("Invalid long double opcode");
786 case Instruction::FAdd:
787 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
788 GV.IntVal = apfLHS.bitcastToAPInt();
790 case Instruction::FSub:
791 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
792 APFloat::rmNearestTiesToEven);
793 GV.IntVal = apfLHS.bitcastToAPInt();
795 case Instruction::FMul:
796 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
797 APFloat::rmNearestTiesToEven);
798 GV.IntVal = apfLHS.bitcastToAPInt();
800 case Instruction::FDiv:
801 apfLHS.divide(APFloat(Sem, RHS.IntVal),
802 APFloat::rmNearestTiesToEven);
803 GV.IntVal = apfLHS.bitcastToAPInt();
805 case Instruction::FRem:
806 apfLHS.mod(APFloat(Sem, RHS.IntVal),
807 APFloat::rmNearestTiesToEven);
808 GV.IntVal = apfLHS.bitcastToAPInt();
820 SmallString<256> Msg;
821 raw_svector_ostream OS(Msg);
822 OS << "ConstantExpr not handled: " << *CE;
823 report_fatal_error(OS.str());
826 // Otherwise, we have a simple constant.
828 switch (C->getType()->getTypeID()) {
829 case Type::FloatTyID:
830 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
832 case Type::DoubleTyID:
833 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
835 case Type::X86_FP80TyID:
836 case Type::FP128TyID:
837 case Type::PPC_FP128TyID:
838 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
840 case Type::IntegerTyID:
841 Result.IntVal = cast<ConstantInt>(C)->getValue();
843 case Type::PointerTyID:
844 if (isa<ConstantPointerNull>(C))
845 Result.PointerVal = 0;
846 else if (const Function *F = dyn_cast<Function>(C))
847 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
848 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
849 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
850 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
851 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
852 BA->getBasicBlock())));
854 llvm_unreachable("Unknown constant pointer type!");
856 case Type::VectorTyID: {
859 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
860 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
861 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
864 elemNum = CDV->getNumElements();
865 ElemTy = CDV->getElementType();
866 } else if (CV || CAZ) {
867 VectorType* VTy = dyn_cast<VectorType>(C->getType());
868 elemNum = VTy->getNumElements();
869 ElemTy = VTy->getElementType();
871 llvm_unreachable("Unknown constant vector type!");
874 Result.AggregateVal.resize(elemNum);
875 // Check if vector holds floats.
876 if(ElemTy->isFloatTy()) {
878 GenericValue floatZero;
879 floatZero.FloatVal = 0.f;
880 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
885 for (unsigned i = 0; i < elemNum; ++i)
886 if (!isa<UndefValue>(CV->getOperand(i)))
887 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
888 CV->getOperand(i))->getValueAPF().convertToFloat();
892 for (unsigned i = 0; i < elemNum; ++i)
893 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
897 // Check if vector holds doubles.
898 if (ElemTy->isDoubleTy()) {
900 GenericValue doubleZero;
901 doubleZero.DoubleVal = 0.0;
902 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
907 for (unsigned i = 0; i < elemNum; ++i)
908 if (!isa<UndefValue>(CV->getOperand(i)))
909 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
910 CV->getOperand(i))->getValueAPF().convertToDouble();
914 for (unsigned i = 0; i < elemNum; ++i)
915 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
919 // Check if vector holds integers.
920 if (ElemTy->isIntegerTy()) {
922 GenericValue intZero;
923 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
924 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
929 for (unsigned i = 0; i < elemNum; ++i)
930 if (!isa<UndefValue>(CV->getOperand(i)))
931 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
932 CV->getOperand(i))->getValue();
934 Result.AggregateVal[i].IntVal =
935 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
940 for (unsigned i = 0; i < elemNum; ++i)
941 Result.AggregateVal[i].IntVal = APInt(
942 CDV->getElementType()->getPrimitiveSizeInBits(),
943 CDV->getElementAsInteger(i));
947 llvm_unreachable("Unknown constant pointer type!");
952 SmallString<256> Msg;
953 raw_svector_ostream OS(Msg);
954 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
955 report_fatal_error(OS.str());
961 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
962 /// with the integer held in IntVal.
963 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
964 unsigned StoreBytes) {
965 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
966 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
968 if (sys::IsLittleEndianHost) {
969 // Little-endian host - the source is ordered from LSB to MSB. Order the
970 // destination from LSB to MSB: Do a straight copy.
971 memcpy(Dst, Src, StoreBytes);
973 // Big-endian host - the source is an array of 64 bit words ordered from
974 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
975 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
976 while (StoreBytes > sizeof(uint64_t)) {
977 StoreBytes -= sizeof(uint64_t);
978 // May not be aligned so use memcpy.
979 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
980 Src += sizeof(uint64_t);
983 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
987 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
988 GenericValue *Ptr, Type *Ty) {
989 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
991 switch (Ty->getTypeID()) {
993 dbgs() << "Cannot store value of type " << *Ty << "!\n";
995 case Type::IntegerTyID:
996 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
998 case Type::FloatTyID:
999 *((float*)Ptr) = Val.FloatVal;
1001 case Type::DoubleTyID:
1002 *((double*)Ptr) = Val.DoubleVal;
1004 case Type::X86_FP80TyID:
1005 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1007 case Type::PointerTyID:
1008 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1009 if (StoreBytes != sizeof(PointerTy))
1010 memset(&(Ptr->PointerVal), 0, StoreBytes);
1012 *((PointerTy*)Ptr) = Val.PointerVal;
1014 case Type::VectorTyID:
1015 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1016 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1017 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1018 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1019 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1020 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1021 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1022 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1023 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1029 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1030 // Host and target are different endian - reverse the stored bytes.
1031 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1034 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1035 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1036 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1037 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1038 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1039 const_cast<uint64_t *>(IntVal.getRawData()));
1041 if (sys::IsLittleEndianHost)
1042 // Little-endian host - the destination must be ordered from LSB to MSB.
1043 // The source is ordered from LSB to MSB: Do a straight copy.
1044 memcpy(Dst, Src, LoadBytes);
1046 // Big-endian - the destination is an array of 64 bit words ordered from
1047 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1048 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1050 while (LoadBytes > sizeof(uint64_t)) {
1051 LoadBytes -= sizeof(uint64_t);
1052 // May not be aligned so use memcpy.
1053 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1054 Dst += sizeof(uint64_t);
1057 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1063 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1066 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1068 switch (Ty->getTypeID()) {
1069 case Type::IntegerTyID:
1070 // An APInt with all words initially zero.
1071 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1072 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1074 case Type::FloatTyID:
1075 Result.FloatVal = *((float*)Ptr);
1077 case Type::DoubleTyID:
1078 Result.DoubleVal = *((double*)Ptr);
1080 case Type::PointerTyID:
1081 Result.PointerVal = *((PointerTy*)Ptr);
1083 case Type::X86_FP80TyID: {
1084 // This is endian dependent, but it will only work on x86 anyway.
1085 // FIXME: Will not trap if loading a signaling NaN.
1088 Result.IntVal = APInt(80, y);
1091 case Type::VectorTyID: {
1092 const VectorType *VT = cast<VectorType>(Ty);
1093 const Type *ElemT = VT->getElementType();
1094 const unsigned numElems = VT->getNumElements();
1095 if (ElemT->isFloatTy()) {
1096 Result.AggregateVal.resize(numElems);
1097 for (unsigned i = 0; i < numElems; ++i)
1098 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1100 if (ElemT->isDoubleTy()) {
1101 Result.AggregateVal.resize(numElems);
1102 for (unsigned i = 0; i < numElems; ++i)
1103 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1105 if (ElemT->isIntegerTy()) {
1106 GenericValue intZero;
1107 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1108 intZero.IntVal = APInt(elemBitWidth, 0);
1109 Result.AggregateVal.resize(numElems, intZero);
1110 for (unsigned i = 0; i < numElems; ++i)
1111 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1112 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1117 SmallString<256> Msg;
1118 raw_svector_ostream OS(Msg);
1119 OS << "Cannot load value of type " << *Ty << "!";
1120 report_fatal_error(OS.str());
1124 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1125 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1126 DEBUG(Init->dump());
1127 if (isa<UndefValue>(Init))
1130 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1131 unsigned ElementSize =
1132 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1133 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1134 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1138 if (isa<ConstantAggregateZero>(Init)) {
1139 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1143 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1144 unsigned ElementSize =
1145 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1146 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1147 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1151 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1152 const StructLayout *SL =
1153 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1154 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1155 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1159 if (const ConstantDataSequential *CDS =
1160 dyn_cast<ConstantDataSequential>(Init)) {
1161 // CDS is already laid out in host memory order.
1162 StringRef Data = CDS->getRawDataValues();
1163 memcpy(Addr, Data.data(), Data.size());
1167 if (Init->getType()->isFirstClassType()) {
1168 GenericValue Val = getConstantValue(Init);
1169 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1173 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1174 llvm_unreachable("Unknown constant type to initialize memory with!");
1177 /// EmitGlobals - Emit all of the global variables to memory, storing their
1178 /// addresses into GlobalAddress. This must make sure to copy the contents of
1179 /// their initializers into the memory.
1180 void ExecutionEngine::emitGlobals() {
1181 // Loop over all of the global variables in the program, allocating the memory
1182 // to hold them. If there is more than one module, do a prepass over globals
1183 // to figure out how the different modules should link together.
1184 std::map<std::pair<std::string, Type*>,
1185 const GlobalValue*> LinkedGlobalsMap;
1187 if (Modules.size() != 1) {
1188 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1189 Module &M = *Modules[m];
1190 for (Module::const_global_iterator I = M.global_begin(),
1191 E = M.global_end(); I != E; ++I) {
1192 const GlobalValue *GV = I;
1193 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1194 GV->hasAppendingLinkage() || !GV->hasName())
1195 continue;// Ignore external globals and globals with internal linkage.
1197 const GlobalValue *&GVEntry =
1198 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1200 // If this is the first time we've seen this global, it is the canonical
1207 // If the existing global is strong, never replace it.
1208 if (GVEntry->hasExternalLinkage() ||
1209 GVEntry->hasDLLImportLinkage() ||
1210 GVEntry->hasDLLExportLinkage())
1213 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1214 // symbol. FIXME is this right for common?
1215 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1221 std::vector<const GlobalValue*> NonCanonicalGlobals;
1222 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1223 Module &M = *Modules[m];
1224 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1226 // In the multi-module case, see what this global maps to.
1227 if (!LinkedGlobalsMap.empty()) {
1228 if (const GlobalValue *GVEntry =
1229 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1230 // If something else is the canonical global, ignore this one.
1231 if (GVEntry != &*I) {
1232 NonCanonicalGlobals.push_back(I);
1238 if (!I->isDeclaration()) {
1239 addGlobalMapping(I, getMemoryForGV(I));
1241 // External variable reference. Try to use the dynamic loader to
1242 // get a pointer to it.
1244 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1245 addGlobalMapping(I, SymAddr);
1247 report_fatal_error("Could not resolve external global address: "
1253 // If there are multiple modules, map the non-canonical globals to their
1254 // canonical location.
1255 if (!NonCanonicalGlobals.empty()) {
1256 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1257 const GlobalValue *GV = NonCanonicalGlobals[i];
1258 const GlobalValue *CGV =
1259 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1260 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1261 assert(Ptr && "Canonical global wasn't codegen'd!");
1262 addGlobalMapping(GV, Ptr);
1266 // Now that all of the globals are set up in memory, loop through them all
1267 // and initialize their contents.
1268 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1270 if (!I->isDeclaration()) {
1271 if (!LinkedGlobalsMap.empty()) {
1272 if (const GlobalValue *GVEntry =
1273 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1274 if (GVEntry != &*I) // Not the canonical variable.
1277 EmitGlobalVariable(I);
1283 // EmitGlobalVariable - This method emits the specified global variable to the
1284 // address specified in GlobalAddresses, or allocates new memory if it's not
1285 // already in the map.
1286 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1287 void *GA = getPointerToGlobalIfAvailable(GV);
1290 // If it's not already specified, allocate memory for the global.
1291 GA = getMemoryForGV(GV);
1293 // If we failed to allocate memory for this global, return.
1294 if (GA == 0) return;
1296 addGlobalMapping(GV, GA);
1299 // Don't initialize if it's thread local, let the client do it.
1300 if (!GV->isThreadLocal())
1301 InitializeMemory(GV->getInitializer(), GA);
1303 Type *ElTy = GV->getType()->getElementType();
1304 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1305 NumInitBytes += (unsigned)GVSize;
1309 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1310 : EE(EE), GlobalAddressMap(this) {
1314 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1315 return &EES->EE.lock;
1318 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1319 const GlobalValue *Old) {
1320 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1321 EES->GlobalAddressReverseMap.erase(OldVal);
1324 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1325 const GlobalValue *,
1326 const GlobalValue *) {
1327 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1328 " RAUW on a value it has a global mapping for.");