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"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ExecutionEngine/GenericValue.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/DynamicLibrary.h"
29 #include "llvm/System/Host.h"
30 #include "llvm/Target/TargetData.h"
35 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36 STATISTIC(NumGlobals , "Number of global vars initialized");
38 ExecutionEngine *(*ExecutionEngine::JITCtor)(Module *M,
39 std::string *ErrorStr,
40 JITMemoryManager *JMM,
41 CodeGenOpt::Level OptLevel,
43 CodeModel::Model CMM) = 0;
44 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
45 std::string *ErrorStr) = 0;
46 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
49 ExecutionEngine::ExecutionEngine(Module *M)
51 LazyFunctionCreator(0) {
52 CompilingLazily = false;
53 GVCompilationDisabled = false;
54 SymbolSearchingDisabled = false;
56 assert(M && "Module is null?");
59 ExecutionEngine::~ExecutionEngine() {
60 clearAllGlobalMappings();
61 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
65 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
66 const Type *ElTy = GV->getType()->getElementType();
67 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
68 return new char[GVSize];
71 /// removeModule - Remove a Module from the list of modules.
72 bool ExecutionEngine::removeModule(Module *M) {
73 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
74 E = Modules.end(); I != E; ++I) {
78 clearGlobalMappingsFromModule(M);
85 /// FindFunctionNamed - Search all of the active modules to find the one that
86 /// defines FnName. This is very slow operation and shouldn't be used for
88 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
89 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
90 if (Function *F = Modules[i]->getFunction(FnName))
97 void *ExecutionEngineState::RemoveMapping(
98 const MutexGuard &, const GlobalValue *ToUnmap) {
99 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
101 if (I == GlobalAddressMap.end())
105 GlobalAddressMap.erase(I);
108 GlobalAddressReverseMap.erase(OldVal);
112 /// addGlobalMapping - Tell the execution engine that the specified global is
113 /// at the specified location. This is used internally as functions are JIT'd
114 /// and as global variables are laid out in memory. It can and should also be
115 /// used by clients of the EE that want to have an LLVM global overlay
116 /// existing data in memory.
117 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
118 MutexGuard locked(lock);
120 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
121 << "\' to [" << Addr << "]\n";);
122 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
123 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
126 // If we are using the reverse mapping, add it too
127 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
128 AssertingVH<const GlobalValue> &V =
129 EEState.getGlobalAddressReverseMap(locked)[Addr];
130 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 /// clearAllGlobalMappings - Clear all global mappings and start over again
136 /// use in dynamic compilation scenarios when you want to move globals
137 void ExecutionEngine::clearAllGlobalMappings() {
138 MutexGuard locked(lock);
140 EEState.getGlobalAddressMap(locked).clear();
141 EEState.getGlobalAddressReverseMap(locked).clear();
144 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
145 /// particular module, because it has been removed from the JIT.
146 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
147 MutexGuard locked(lock);
149 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
150 EEState.RemoveMapping(locked, FI);
152 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
154 EEState.RemoveMapping(locked, GI);
158 /// updateGlobalMapping - Replace an existing mapping for GV with a new
159 /// address. This updates both maps as required. If "Addr" is null, the
160 /// entry for the global is removed from the mappings.
161 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
162 MutexGuard locked(lock);
164 ExecutionEngineState::GlobalAddressMapTy &Map =
165 EEState.getGlobalAddressMap(locked);
167 // Deleting from the mapping?
169 return EEState.RemoveMapping(locked, GV);
172 void *&CurVal = Map[GV];
173 void *OldVal = CurVal;
175 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
176 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
179 // If we are using the reverse mapping, add it too
180 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
181 AssertingVH<const GlobalValue> &V =
182 EEState.getGlobalAddressReverseMap(locked)[Addr];
183 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
189 /// getPointerToGlobalIfAvailable - This returns the address of the specified
190 /// global value if it is has already been codegen'd, otherwise it returns null.
192 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
193 MutexGuard locked(lock);
195 ExecutionEngineState::GlobalAddressMapTy::iterator I =
196 EEState.getGlobalAddressMap(locked).find(GV);
197 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
200 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
201 /// at the specified address.
203 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
204 MutexGuard locked(lock);
206 // If we haven't computed the reverse mapping yet, do so first.
207 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
208 for (ExecutionEngineState::GlobalAddressMapTy::iterator
209 I = EEState.getGlobalAddressMap(locked).begin(),
210 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
211 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
215 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
216 EEState.getGlobalAddressReverseMap(locked).find(Addr);
217 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
220 // CreateArgv - Turn a vector of strings into a nice argv style array of
221 // pointers to null terminated strings.
223 static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
224 const std::vector<std::string> &InputArgv) {
225 unsigned PtrSize = EE->getTargetData()->getPointerSize();
226 char *Result = new char[(InputArgv.size()+1)*PtrSize];
228 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
229 const Type *SBytePtr = Type::getInt8PtrTy(C);
231 for (unsigned i = 0; i != InputArgv.size(); ++i) {
232 unsigned Size = InputArgv[i].size()+1;
233 char *Dest = new char[Size];
234 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
236 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
239 // Endian safe: Result[i] = (PointerTy)Dest;
240 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245 EE->StoreValueToMemory(PTOGV(0),
246 (GenericValue*)(Result+InputArgv.size()*PtrSize),
252 /// runStaticConstructorsDestructors - This method is used to execute all of
253 /// the static constructors or destructors for a module, depending on the
254 /// value of isDtors.
255 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
257 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
259 // Execute global ctors/dtors for each module in the program.
261 GlobalVariable *GV = module->getNamedGlobal(Name);
263 // If this global has internal linkage, or if it has a use, then it must be
264 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
265 // this is the case, don't execute any of the global ctors, __main will do
267 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
269 // Should be an array of '{ int, void ()* }' structs. The first value is
270 // the init priority, which we ignore.
271 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
272 if (!InitList) return;
273 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
274 if (ConstantStruct *CS =
275 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
276 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
278 Constant *FP = CS->getOperand(1);
279 if (FP->isNullValue())
280 break; // Found a null terminator, exit.
282 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
284 FP = CE->getOperand(0);
285 if (Function *F = dyn_cast<Function>(FP)) {
286 // Execute the ctor/dtor function!
287 runFunction(F, std::vector<GenericValue>());
292 /// runStaticConstructorsDestructors - This method is used to execute all of
293 /// the static constructors or destructors for a program, depending on the
294 /// value of isDtors.
295 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
296 // Execute global ctors/dtors for each module in the program.
297 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
298 runStaticConstructorsDestructors(Modules[m], isDtors);
302 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
303 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
304 unsigned PtrSize = EE->getTargetData()->getPointerSize();
305 for (unsigned i = 0; i < PtrSize; ++i)
306 if (*(i + (uint8_t*)Loc))
312 /// runFunctionAsMain - This is a helper function which wraps runFunction to
313 /// handle the common task of starting up main with the specified argc, argv,
314 /// and envp parameters.
315 int ExecutionEngine::runFunctionAsMain(Function *Fn,
316 const std::vector<std::string> &argv,
317 const char * const * envp) {
318 std::vector<GenericValue> GVArgs;
320 GVArgc.IntVal = APInt(32, argv.size());
323 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
324 const FunctionType *FTy = Fn->getFunctionType();
325 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
328 if (FTy->getParamType(2) != PPInt8Ty) {
329 llvm_report_error("Invalid type for third argument of main() supplied");
333 if (FTy->getParamType(1) != PPInt8Ty) {
334 llvm_report_error("Invalid type for second argument of main() supplied");
338 if (!FTy->getParamType(0)->isInteger(32)) {
339 llvm_report_error("Invalid type for first argument of main() supplied");
343 if (!isa<IntegerType>(FTy->getReturnType()) &&
344 !FTy->getReturnType()->isVoidTy()) {
345 llvm_report_error("Invalid return type of main() supplied");
349 llvm_report_error("Invalid number of arguments of main() supplied");
353 GVArgs.push_back(GVArgc); // Arg #0 = argc.
356 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
357 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
358 "argv[0] was null after CreateArgv");
360 std::vector<std::string> EnvVars;
361 for (unsigned i = 0; envp[i]; ++i)
362 EnvVars.push_back(envp[i]);
364 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
368 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
371 /// If possible, create a JIT, unless the caller specifically requests an
372 /// Interpreter or there's an error. If even an Interpreter cannot be created,
373 /// NULL is returned.
375 ExecutionEngine *ExecutionEngine::create(Module *M,
376 bool ForceInterpreter,
377 std::string *ErrorStr,
378 CodeGenOpt::Level OptLevel,
380 return EngineBuilder(M)
381 .setEngineKind(ForceInterpreter
382 ? EngineKind::Interpreter
384 .setErrorStr(ErrorStr)
385 .setOptLevel(OptLevel)
386 .setAllocateGVsWithCode(GVsWithCode)
390 ExecutionEngine *EngineBuilder::create() {
391 // Make sure we can resolve symbols in the program as well. The zero arg
392 // to the function tells DynamicLibrary to load the program, not a library.
393 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
396 // If the user specified a memory manager but didn't specify which engine to
397 // create, we assume they only want the JIT, and we fail if they only want
400 if (WhichEngine & EngineKind::JIT)
401 WhichEngine = EngineKind::JIT;
404 *ErrorStr = "Cannot create an interpreter with a memory manager.";
409 // Unless the interpreter was explicitly selected or the JIT is not linked,
411 if (WhichEngine & EngineKind::JIT) {
412 if (ExecutionEngine::JITCtor) {
413 ExecutionEngine *EE =
414 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
415 AllocateGVsWithCode, CMModel);
420 // If we can't make a JIT and we didn't request one specifically, try making
421 // an interpreter instead.
422 if (WhichEngine & EngineKind::Interpreter) {
423 if (ExecutionEngine::InterpCtor)
424 return ExecutionEngine::InterpCtor(M, ErrorStr);
426 *ErrorStr = "Interpreter has not been linked in.";
430 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
432 *ErrorStr = "JIT has not been linked in.";
437 /// getPointerToGlobal - This returns the address of the specified global
438 /// value. This may involve code generation if it's a function.
440 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
441 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
442 return getPointerToFunction(F);
444 MutexGuard locked(lock);
445 void *p = EEState.getGlobalAddressMap(locked)[GV];
449 // Global variable might have been added since interpreter started.
450 if (GlobalVariable *GVar =
451 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
452 EmitGlobalVariable(GVar);
454 llvm_unreachable("Global hasn't had an address allocated yet!");
455 return EEState.getGlobalAddressMap(locked)[GV];
458 /// This function converts a Constant* into a GenericValue. The interesting
459 /// part is if C is a ConstantExpr.
460 /// @brief Get a GenericValue for a Constant*
461 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
462 // If its undefined, return the garbage.
463 if (isa<UndefValue>(C)) {
465 switch (C->getType()->getTypeID()) {
466 case Type::IntegerTyID:
467 case Type::X86_FP80TyID:
468 case Type::FP128TyID:
469 case Type::PPC_FP128TyID:
470 // Although the value is undefined, we still have to construct an APInt
471 // with the correct bit width.
472 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
480 // If the value is a ConstantExpr
481 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
482 Constant *Op0 = CE->getOperand(0);
483 switch (CE->getOpcode()) {
484 case Instruction::GetElementPtr: {
486 GenericValue Result = getConstantValue(Op0);
487 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
489 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
491 char* tmp = (char*) Result.PointerVal;
492 Result = PTOGV(tmp + Offset);
495 case Instruction::Trunc: {
496 GenericValue GV = getConstantValue(Op0);
497 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
498 GV.IntVal = GV.IntVal.trunc(BitWidth);
501 case Instruction::ZExt: {
502 GenericValue GV = getConstantValue(Op0);
503 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
504 GV.IntVal = GV.IntVal.zext(BitWidth);
507 case Instruction::SExt: {
508 GenericValue GV = getConstantValue(Op0);
509 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
510 GV.IntVal = GV.IntVal.sext(BitWidth);
513 case Instruction::FPTrunc: {
515 GenericValue GV = getConstantValue(Op0);
516 GV.FloatVal = float(GV.DoubleVal);
519 case Instruction::FPExt:{
521 GenericValue GV = getConstantValue(Op0);
522 GV.DoubleVal = double(GV.FloatVal);
525 case Instruction::UIToFP: {
526 GenericValue GV = getConstantValue(Op0);
527 if (CE->getType()->isFloatTy())
528 GV.FloatVal = float(GV.IntVal.roundToDouble());
529 else if (CE->getType()->isDoubleTy())
530 GV.DoubleVal = GV.IntVal.roundToDouble();
531 else if (CE->getType()->isX86_FP80Ty()) {
532 const uint64_t zero[] = {0, 0};
533 APFloat apf = APFloat(APInt(80, 2, zero));
534 (void)apf.convertFromAPInt(GV.IntVal,
536 APFloat::rmNearestTiesToEven);
537 GV.IntVal = apf.bitcastToAPInt();
541 case Instruction::SIToFP: {
542 GenericValue GV = getConstantValue(Op0);
543 if (CE->getType()->isFloatTy())
544 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
545 else if (CE->getType()->isDoubleTy())
546 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
547 else if (CE->getType()->isX86_FP80Ty()) {
548 const uint64_t zero[] = { 0, 0};
549 APFloat apf = APFloat(APInt(80, 2, zero));
550 (void)apf.convertFromAPInt(GV.IntVal,
552 APFloat::rmNearestTiesToEven);
553 GV.IntVal = apf.bitcastToAPInt();
557 case Instruction::FPToUI: // double->APInt conversion handles sign
558 case Instruction::FPToSI: {
559 GenericValue GV = getConstantValue(Op0);
560 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
561 if (Op0->getType()->isFloatTy())
562 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
563 else if (Op0->getType()->isDoubleTy())
564 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
565 else if (Op0->getType()->isX86_FP80Ty()) {
566 APFloat apf = APFloat(GV.IntVal);
569 (void)apf.convertToInteger(&v, BitWidth,
570 CE->getOpcode()==Instruction::FPToSI,
571 APFloat::rmTowardZero, &ignored);
572 GV.IntVal = v; // endian?
576 case Instruction::PtrToInt: {
577 GenericValue GV = getConstantValue(Op0);
578 uint32_t PtrWidth = TD->getPointerSizeInBits();
579 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
582 case Instruction::IntToPtr: {
583 GenericValue GV = getConstantValue(Op0);
584 uint32_t PtrWidth = TD->getPointerSizeInBits();
585 if (PtrWidth != GV.IntVal.getBitWidth())
586 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
587 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
588 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
591 case Instruction::BitCast: {
592 GenericValue GV = getConstantValue(Op0);
593 const Type* DestTy = CE->getType();
594 switch (Op0->getType()->getTypeID()) {
595 default: llvm_unreachable("Invalid bitcast operand");
596 case Type::IntegerTyID:
597 assert(DestTy->isFloatingPoint() && "invalid bitcast");
598 if (DestTy->isFloatTy())
599 GV.FloatVal = GV.IntVal.bitsToFloat();
600 else if (DestTy->isDoubleTy())
601 GV.DoubleVal = GV.IntVal.bitsToDouble();
603 case Type::FloatTyID:
604 assert(DestTy->isInteger(32) && "Invalid bitcast");
605 GV.IntVal.floatToBits(GV.FloatVal);
607 case Type::DoubleTyID:
608 assert(DestTy->isInteger(64) && "Invalid bitcast");
609 GV.IntVal.doubleToBits(GV.DoubleVal);
611 case Type::PointerTyID:
612 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
613 break; // getConstantValue(Op0) above already converted it
617 case Instruction::Add:
618 case Instruction::FAdd:
619 case Instruction::Sub:
620 case Instruction::FSub:
621 case Instruction::Mul:
622 case Instruction::FMul:
623 case Instruction::UDiv:
624 case Instruction::SDiv:
625 case Instruction::URem:
626 case Instruction::SRem:
627 case Instruction::And:
628 case Instruction::Or:
629 case Instruction::Xor: {
630 GenericValue LHS = getConstantValue(Op0);
631 GenericValue RHS = getConstantValue(CE->getOperand(1));
633 switch (CE->getOperand(0)->getType()->getTypeID()) {
634 default: llvm_unreachable("Bad add type!");
635 case Type::IntegerTyID:
636 switch (CE->getOpcode()) {
637 default: llvm_unreachable("Invalid integer opcode");
638 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
639 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
640 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
641 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
642 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
643 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
644 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
645 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
646 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
647 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
650 case Type::FloatTyID:
651 switch (CE->getOpcode()) {
652 default: llvm_unreachable("Invalid float opcode");
653 case Instruction::FAdd:
654 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
655 case Instruction::FSub:
656 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
657 case Instruction::FMul:
658 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
659 case Instruction::FDiv:
660 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
661 case Instruction::FRem:
662 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
665 case Type::DoubleTyID:
666 switch (CE->getOpcode()) {
667 default: llvm_unreachable("Invalid double opcode");
668 case Instruction::FAdd:
669 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
670 case Instruction::FSub:
671 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
672 case Instruction::FMul:
673 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
674 case Instruction::FDiv:
675 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
676 case Instruction::FRem:
677 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
680 case Type::X86_FP80TyID:
681 case Type::PPC_FP128TyID:
682 case Type::FP128TyID: {
683 APFloat apfLHS = APFloat(LHS.IntVal);
684 switch (CE->getOpcode()) {
685 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
686 case Instruction::FAdd:
687 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
688 GV.IntVal = apfLHS.bitcastToAPInt();
690 case Instruction::FSub:
691 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
692 GV.IntVal = apfLHS.bitcastToAPInt();
694 case Instruction::FMul:
695 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
696 GV.IntVal = apfLHS.bitcastToAPInt();
698 case Instruction::FDiv:
699 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
700 GV.IntVal = apfLHS.bitcastToAPInt();
702 case Instruction::FRem:
703 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
704 GV.IntVal = apfLHS.bitcastToAPInt();
716 raw_string_ostream Msg(msg);
717 Msg << "ConstantExpr not handled: " << *CE;
718 llvm_report_error(Msg.str());
722 switch (C->getType()->getTypeID()) {
723 case Type::FloatTyID:
724 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
726 case Type::DoubleTyID:
727 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
729 case Type::X86_FP80TyID:
730 case Type::FP128TyID:
731 case Type::PPC_FP128TyID:
732 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
734 case Type::IntegerTyID:
735 Result.IntVal = cast<ConstantInt>(C)->getValue();
737 case Type::PointerTyID:
738 if (isa<ConstantPointerNull>(C))
739 Result.PointerVal = 0;
740 else if (const Function *F = dyn_cast<Function>(C))
741 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
742 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
743 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
744 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
745 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
746 BA->getBasicBlock())));
748 llvm_unreachable("Unknown constant pointer type!");
752 raw_string_ostream Msg(msg);
753 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
754 llvm_report_error(Msg.str());
759 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
760 /// with the integer held in IntVal.
761 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
762 unsigned StoreBytes) {
763 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
764 uint8_t *Src = (uint8_t *)IntVal.getRawData();
766 if (sys::isLittleEndianHost())
767 // Little-endian host - the source is ordered from LSB to MSB. Order the
768 // destination from LSB to MSB: Do a straight copy.
769 memcpy(Dst, Src, StoreBytes);
771 // Big-endian host - the source is an array of 64 bit words ordered from
772 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
773 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
774 while (StoreBytes > sizeof(uint64_t)) {
775 StoreBytes -= sizeof(uint64_t);
776 // May not be aligned so use memcpy.
777 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
778 Src += sizeof(uint64_t);
781 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
785 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
786 /// is the address of the memory at which to store Val, cast to GenericValue *.
787 /// It is not a pointer to a GenericValue containing the address at which to
789 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
790 GenericValue *Ptr, const Type *Ty) {
791 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
793 switch (Ty->getTypeID()) {
794 case Type::IntegerTyID:
795 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
797 case Type::FloatTyID:
798 *((float*)Ptr) = Val.FloatVal;
800 case Type::DoubleTyID:
801 *((double*)Ptr) = Val.DoubleVal;
803 case Type::X86_FP80TyID:
804 memcpy(Ptr, Val.IntVal.getRawData(), 10);
806 case Type::PointerTyID:
807 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
808 if (StoreBytes != sizeof(PointerTy))
809 memset(Ptr, 0, StoreBytes);
811 *((PointerTy*)Ptr) = Val.PointerVal;
814 dbgs() << "Cannot store value of type " << *Ty << "!\n";
817 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
818 // Host and target are different endian - reverse the stored bytes.
819 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
822 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
823 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
824 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
825 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
826 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
828 if (sys::isLittleEndianHost())
829 // Little-endian host - the destination must be ordered from LSB to MSB.
830 // The source is ordered from LSB to MSB: Do a straight copy.
831 memcpy(Dst, Src, LoadBytes);
833 // Big-endian - the destination is an array of 64 bit words ordered from
834 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
835 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
837 while (LoadBytes > sizeof(uint64_t)) {
838 LoadBytes -= sizeof(uint64_t);
839 // May not be aligned so use memcpy.
840 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
841 Dst += sizeof(uint64_t);
844 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
850 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
853 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
855 switch (Ty->getTypeID()) {
856 case Type::IntegerTyID:
857 // An APInt with all words initially zero.
858 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
859 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
861 case Type::FloatTyID:
862 Result.FloatVal = *((float*)Ptr);
864 case Type::DoubleTyID:
865 Result.DoubleVal = *((double*)Ptr);
867 case Type::PointerTyID:
868 Result.PointerVal = *((PointerTy*)Ptr);
870 case Type::X86_FP80TyID: {
871 // This is endian dependent, but it will only work on x86 anyway.
872 // FIXME: Will not trap if loading a signaling NaN.
875 Result.IntVal = APInt(80, 2, y);
880 raw_string_ostream Msg(msg);
881 Msg << "Cannot load value of type " << *Ty << "!";
882 llvm_report_error(Msg.str());
886 // InitializeMemory - Recursive function to apply a Constant value into the
887 // specified memory location...
889 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
890 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
892 if (isa<UndefValue>(Init)) {
894 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
895 unsigned ElementSize =
896 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
897 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
898 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
900 } else if (isa<ConstantAggregateZero>(Init)) {
901 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
903 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
904 unsigned ElementSize =
905 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
906 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
907 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
909 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
910 const StructLayout *SL =
911 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
912 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
913 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
915 } else if (Init->getType()->isFirstClassType()) {
916 GenericValue Val = getConstantValue(Init);
917 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
921 dbgs() << "Bad Type: " << *Init->getType() << "\n";
922 llvm_unreachable("Unknown constant type to initialize memory with!");
925 /// EmitGlobals - Emit all of the global variables to memory, storing their
926 /// addresses into GlobalAddress. This must make sure to copy the contents of
927 /// their initializers into the memory.
929 void ExecutionEngine::emitGlobals() {
931 // Loop over all of the global variables in the program, allocating the memory
932 // to hold them. If there is more than one module, do a prepass over globals
933 // to figure out how the different modules should link together.
935 std::map<std::pair<std::string, const Type*>,
936 const GlobalValue*> LinkedGlobalsMap;
938 if (Modules.size() != 1) {
939 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
940 Module &M = *Modules[m];
941 for (Module::const_global_iterator I = M.global_begin(),
942 E = M.global_end(); I != E; ++I) {
943 const GlobalValue *GV = I;
944 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
945 GV->hasAppendingLinkage() || !GV->hasName())
946 continue;// Ignore external globals and globals with internal linkage.
948 const GlobalValue *&GVEntry =
949 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
951 // If this is the first time we've seen this global, it is the canonical
958 // If the existing global is strong, never replace it.
959 if (GVEntry->hasExternalLinkage() ||
960 GVEntry->hasDLLImportLinkage() ||
961 GVEntry->hasDLLExportLinkage())
964 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
965 // symbol. FIXME is this right for common?
966 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
972 std::vector<const GlobalValue*> NonCanonicalGlobals;
973 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
974 Module &M = *Modules[m];
975 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
977 // In the multi-module case, see what this global maps to.
978 if (!LinkedGlobalsMap.empty()) {
979 if (const GlobalValue *GVEntry =
980 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
981 // If something else is the canonical global, ignore this one.
982 if (GVEntry != &*I) {
983 NonCanonicalGlobals.push_back(I);
989 if (!I->isDeclaration()) {
990 addGlobalMapping(I, getMemoryForGV(I));
992 // External variable reference. Try to use the dynamic loader to
993 // get a pointer to it.
995 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
996 addGlobalMapping(I, SymAddr);
998 llvm_report_error("Could not resolve external global address: "
1004 // If there are multiple modules, map the non-canonical globals to their
1005 // canonical location.
1006 if (!NonCanonicalGlobals.empty()) {
1007 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1008 const GlobalValue *GV = NonCanonicalGlobals[i];
1009 const GlobalValue *CGV =
1010 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1011 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1012 assert(Ptr && "Canonical global wasn't codegen'd!");
1013 addGlobalMapping(GV, Ptr);
1017 // Now that all of the globals are set up in memory, loop through them all
1018 // and initialize their contents.
1019 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1021 if (!I->isDeclaration()) {
1022 if (!LinkedGlobalsMap.empty()) {
1023 if (const GlobalValue *GVEntry =
1024 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1025 if (GVEntry != &*I) // Not the canonical variable.
1028 EmitGlobalVariable(I);
1034 // EmitGlobalVariable - This method emits the specified global variable to the
1035 // address specified in GlobalAddresses, or allocates new memory if it's not
1036 // already in the map.
1037 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1038 void *GA = getPointerToGlobalIfAvailable(GV);
1041 // If it's not already specified, allocate memory for the global.
1042 GA = getMemoryForGV(GV);
1043 addGlobalMapping(GV, GA);
1046 // Don't initialize if it's thread local, let the client do it.
1047 if (!GV->isThreadLocal())
1048 InitializeMemory(GV->getInitializer(), GA);
1050 const Type *ElTy = GV->getType()->getElementType();
1051 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1052 NumInitBytes += (unsigned)GVSize;
1056 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1057 : EE(EE), GlobalAddressMap(this) {
1060 sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1061 ExecutionEngineState *EES) {
1062 return &EES->EE.lock;
1064 void ExecutionEngineState::AddressMapConfig::onDelete(
1065 ExecutionEngineState *EES, const GlobalValue *Old) {
1066 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1067 EES->GlobalAddressReverseMap.erase(OldVal);
1070 void ExecutionEngineState::AddressMapConfig::onRAUW(
1071 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
1072 assert(false && "The ExecutionEngine doesn't know how to handle a"
1073 " RAUW on a value it has a global mapping for.");