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)(
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
42 CodeGenOpt::Level OptLevel,
47 const SmallVectorImpl<std::string>& MAttrs) = 0;
48 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
49 std::string *ErrorStr) = 0;
50 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
53 ExecutionEngine::ExecutionEngine(Module *M)
55 LazyFunctionCreator(0) {
56 CompilingLazily = false;
57 GVCompilationDisabled = false;
58 SymbolSearchingDisabled = false;
60 assert(M && "Module is null?");
63 ExecutionEngine::~ExecutionEngine() {
64 clearAllGlobalMappings();
65 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
69 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
71 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
72 return new char[GVSize];
75 /// removeModule - Remove a Module from the list of modules.
76 bool ExecutionEngine::removeModule(Module *M) {
77 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
78 E = Modules.end(); I != E; ++I) {
82 clearGlobalMappingsFromModule(M);
89 /// FindFunctionNamed - Search all of the active modules to find the one that
90 /// defines FnName. This is very slow operation and shouldn't be used for
92 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
93 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
94 if (Function *F = Modules[i]->getFunction(FnName))
101 void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
105 if (I == GlobalAddressMap.end())
109 GlobalAddressMap.erase(I);
112 GlobalAddressReverseMap.erase(OldVal);
116 /// addGlobalMapping - Tell the execution engine that the specified global is
117 /// at the specified location. This is used internally as functions are JIT'd
118 /// and as global variables are laid out in memory. It can and should also be
119 /// used by clients of the EE that want to have an LLVM global overlay
120 /// existing data in memory.
121 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
122 MutexGuard locked(lock);
124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
125 << "\' to [" << Addr << "]\n";);
126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
127 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
130 // If we are using the reverse mapping, add it too
131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
132 AssertingVH<const GlobalValue> &V =
133 EEState.getGlobalAddressReverseMap(locked)[Addr];
134 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
139 /// clearAllGlobalMappings - Clear all global mappings and start over again
140 /// use in dynamic compilation scenarios when you want to move globals
141 void ExecutionEngine::clearAllGlobalMappings() {
142 MutexGuard locked(lock);
144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
148 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
149 /// particular module, because it has been removed from the JIT.
150 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
151 MutexGuard locked(lock);
153 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
154 EEState.RemoveMapping(locked, FI);
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
158 EEState.RemoveMapping(locked, GI);
162 /// updateGlobalMapping - Replace an existing mapping for GV with a new
163 /// address. This updates both maps as required. If "Addr" is null, the
164 /// entry for the global is removed from the mappings.
165 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
166 MutexGuard locked(lock);
168 ExecutionEngineState::GlobalAddressMapTy &Map =
169 EEState.getGlobalAddressMap(locked);
171 // Deleting from the mapping?
173 return EEState.RemoveMapping(locked, GV);
176 void *&CurVal = Map[GV];
177 void *OldVal = CurVal;
179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
183 // If we are using the reverse mapping, add it too
184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
185 AssertingVH<const GlobalValue> &V =
186 EEState.getGlobalAddressReverseMap(locked)[Addr];
187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
193 /// getPointerToGlobalIfAvailable - This returns the address of the specified
194 /// global value if it is has already been codegen'd, otherwise it returns null.
196 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
204 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
205 /// at the specified address.
207 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
208 MutexGuard locked(lock);
210 // If we haven't computed the reverse mapping yet, do so first.
211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
213 I = EEState.getGlobalAddressMap(locked).begin(),
214 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
215 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
224 // CreateArgv - Turn a vector of strings into a nice argv style array of
225 // pointers to null terminated strings.
227 static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
228 const std::vector<std::string> &InputArgv) {
229 unsigned PtrSize = EE->getTargetData()->getPointerSize();
230 char *Result = new char[(InputArgv.size()+1)*PtrSize];
232 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
233 const Type *SBytePtr = Type::getInt8PtrTy(C);
235 for (unsigned i = 0; i != InputArgv.size(); ++i) {
236 unsigned Size = InputArgv[i].size()+1;
237 char *Dest = new char[Size];
238 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
243 // Endian safe: Result[i] = (PointerTy)Dest;
244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
249 EE->StoreValueToMemory(PTOGV(0),
250 (GenericValue*)(Result+InputArgv.size()*PtrSize),
256 /// runStaticConstructorsDestructors - This method is used to execute all of
257 /// the static constructors or destructors for a module, depending on the
258 /// value of isDtors.
259 void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
261 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
263 // Execute global ctors/dtors for each module in the program.
265 GlobalVariable *GV = module->getNamedGlobal(Name);
267 // If this global has internal linkage, or if it has a use, then it must be
268 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
269 // this is the case, don't execute any of the global ctors, __main will do
271 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
273 // Should be an array of '{ int, void ()* }' structs. The first value is
274 // the init priority, which we ignore.
275 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
276 if (!InitList) return;
277 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
278 if (ConstantStruct *CS =
279 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
280 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
282 Constant *FP = CS->getOperand(1);
283 if (FP->isNullValue())
284 break; // Found a null terminator, exit.
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
288 FP = CE->getOperand(0);
289 if (Function *F = dyn_cast<Function>(FP)) {
290 // Execute the ctor/dtor function!
291 runFunction(F, std::vector<GenericValue>());
296 /// runStaticConstructorsDestructors - This method is used to execute all of
297 /// the static constructors or destructors for a program, depending on the
298 /// value of isDtors.
299 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
300 // Execute global ctors/dtors for each module in the program.
301 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
302 runStaticConstructorsDestructors(Modules[m], isDtors);
306 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
307 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
308 unsigned PtrSize = EE->getTargetData()->getPointerSize();
309 for (unsigned i = 0; i < PtrSize; ++i)
310 if (*(i + (uint8_t*)Loc))
316 /// runFunctionAsMain - This is a helper function which wraps runFunction to
317 /// handle the common task of starting up main with the specified argc, argv,
318 /// and envp parameters.
319 int ExecutionEngine::runFunctionAsMain(Function *Fn,
320 const std::vector<std::string> &argv,
321 const char * const * envp) {
322 std::vector<GenericValue> GVArgs;
324 GVArgc.IntVal = APInt(32, argv.size());
327 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
328 const FunctionType *FTy = Fn->getFunctionType();
329 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
332 if (FTy->getParamType(2) != PPInt8Ty) {
333 llvm_report_error("Invalid type for third argument of main() supplied");
337 if (FTy->getParamType(1) != PPInt8Ty) {
338 llvm_report_error("Invalid type for second argument of main() supplied");
342 if (!FTy->getParamType(0)->isIntegerTy(32)) {
343 llvm_report_error("Invalid type for first argument of main() supplied");
347 if (!FTy->getReturnType()->isIntegerTy() &&
348 !FTy->getReturnType()->isVoidTy()) {
349 llvm_report_error("Invalid return type of main() supplied");
353 llvm_report_error("Invalid number of arguments of main() supplied");
357 GVArgs.push_back(GVArgc); // Arg #0 = argc.
360 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
361 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
362 "argv[0] was null after CreateArgv");
364 std::vector<std::string> EnvVars;
365 for (unsigned i = 0; envp[i]; ++i)
366 EnvVars.push_back(envp[i]);
368 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
372 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
375 /// If possible, create a JIT, unless the caller specifically requests an
376 /// Interpreter or there's an error. If even an Interpreter cannot be created,
377 /// NULL is returned.
379 ExecutionEngine *ExecutionEngine::create(Module *M,
380 bool ForceInterpreter,
381 std::string *ErrorStr,
382 CodeGenOpt::Level OptLevel,
384 return EngineBuilder(M)
385 .setEngineKind(ForceInterpreter
386 ? EngineKind::Interpreter
388 .setErrorStr(ErrorStr)
389 .setOptLevel(OptLevel)
390 .setAllocateGVsWithCode(GVsWithCode)
394 ExecutionEngine *EngineBuilder::create() {
395 // Make sure we can resolve symbols in the program as well. The zero arg
396 // to the function tells DynamicLibrary to load the program, not a library.
397 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
400 // If the user specified a memory manager but didn't specify which engine to
401 // create, we assume they only want the JIT, and we fail if they only want
404 if (WhichEngine & EngineKind::JIT)
405 WhichEngine = EngineKind::JIT;
408 *ErrorStr = "Cannot create an interpreter with a memory manager.";
413 // Unless the interpreter was explicitly selected or the JIT is not linked,
415 if (WhichEngine & EngineKind::JIT) {
416 if (ExecutionEngine::JITCtor) {
417 ExecutionEngine *EE =
418 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
419 AllocateGVsWithCode, CMModel,
420 MArch, MCPU, MAttrs);
425 // If we can't make a JIT and we didn't request one specifically, try making
426 // an interpreter instead.
427 if (WhichEngine & EngineKind::Interpreter) {
428 if (ExecutionEngine::InterpCtor)
429 return ExecutionEngine::InterpCtor(M, ErrorStr);
431 *ErrorStr = "Interpreter has not been linked in.";
435 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
437 *ErrorStr = "JIT has not been linked in.";
442 /// getPointerToGlobal - This returns the address of the specified global
443 /// value. This may involve code generation if it's a function.
445 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
446 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
447 return getPointerToFunction(F);
449 MutexGuard locked(lock);
450 void *p = EEState.getGlobalAddressMap(locked)[GV];
454 // Global variable might have been added since interpreter started.
455 if (GlobalVariable *GVar =
456 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
457 EmitGlobalVariable(GVar);
459 llvm_unreachable("Global hasn't had an address allocated yet!");
460 return EEState.getGlobalAddressMap(locked)[GV];
463 /// This function converts a Constant* into a GenericValue. The interesting
464 /// part is if C is a ConstantExpr.
465 /// @brief Get a GenericValue for a Constant*
466 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
467 // If its undefined, return the garbage.
468 if (isa<UndefValue>(C)) {
470 switch (C->getType()->getTypeID()) {
471 case Type::IntegerTyID:
472 case Type::X86_FP80TyID:
473 case Type::FP128TyID:
474 case Type::PPC_FP128TyID:
475 // Although the value is undefined, we still have to construct an APInt
476 // with the correct bit width.
477 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
485 // If the value is a ConstantExpr
486 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
487 Constant *Op0 = CE->getOperand(0);
488 switch (CE->getOpcode()) {
489 case Instruction::GetElementPtr: {
491 GenericValue Result = getConstantValue(Op0);
492 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
494 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
496 char* tmp = (char*) Result.PointerVal;
497 Result = PTOGV(tmp + Offset);
500 case Instruction::Trunc: {
501 GenericValue GV = getConstantValue(Op0);
502 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
503 GV.IntVal = GV.IntVal.trunc(BitWidth);
506 case Instruction::ZExt: {
507 GenericValue GV = getConstantValue(Op0);
508 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
509 GV.IntVal = GV.IntVal.zext(BitWidth);
512 case Instruction::SExt: {
513 GenericValue GV = getConstantValue(Op0);
514 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
515 GV.IntVal = GV.IntVal.sext(BitWidth);
518 case Instruction::FPTrunc: {
520 GenericValue GV = getConstantValue(Op0);
521 GV.FloatVal = float(GV.DoubleVal);
524 case Instruction::FPExt:{
526 GenericValue GV = getConstantValue(Op0);
527 GV.DoubleVal = double(GV.FloatVal);
530 case Instruction::UIToFP: {
531 GenericValue GV = getConstantValue(Op0);
532 if (CE->getType()->isFloatTy())
533 GV.FloatVal = float(GV.IntVal.roundToDouble());
534 else if (CE->getType()->isDoubleTy())
535 GV.DoubleVal = GV.IntVal.roundToDouble();
536 else if (CE->getType()->isX86_FP80Ty()) {
537 const uint64_t zero[] = {0, 0};
538 APFloat apf = APFloat(APInt(80, 2, zero));
539 (void)apf.convertFromAPInt(GV.IntVal,
541 APFloat::rmNearestTiesToEven);
542 GV.IntVal = apf.bitcastToAPInt();
546 case Instruction::SIToFP: {
547 GenericValue GV = getConstantValue(Op0);
548 if (CE->getType()->isFloatTy())
549 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
550 else if (CE->getType()->isDoubleTy())
551 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
552 else if (CE->getType()->isX86_FP80Ty()) {
553 const uint64_t zero[] = { 0, 0};
554 APFloat apf = APFloat(APInt(80, 2, zero));
555 (void)apf.convertFromAPInt(GV.IntVal,
557 APFloat::rmNearestTiesToEven);
558 GV.IntVal = apf.bitcastToAPInt();
562 case Instruction::FPToUI: // double->APInt conversion handles sign
563 case Instruction::FPToSI: {
564 GenericValue GV = getConstantValue(Op0);
565 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
566 if (Op0->getType()->isFloatTy())
567 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
568 else if (Op0->getType()->isDoubleTy())
569 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
570 else if (Op0->getType()->isX86_FP80Ty()) {
571 APFloat apf = APFloat(GV.IntVal);
574 (void)apf.convertToInteger(&v, BitWidth,
575 CE->getOpcode()==Instruction::FPToSI,
576 APFloat::rmTowardZero, &ignored);
577 GV.IntVal = v; // endian?
581 case Instruction::PtrToInt: {
582 GenericValue GV = getConstantValue(Op0);
583 uint32_t PtrWidth = TD->getPointerSizeInBits();
584 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
587 case Instruction::IntToPtr: {
588 GenericValue GV = getConstantValue(Op0);
589 uint32_t PtrWidth = TD->getPointerSizeInBits();
590 if (PtrWidth != GV.IntVal.getBitWidth())
591 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
592 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
593 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
596 case Instruction::BitCast: {
597 GenericValue GV = getConstantValue(Op0);
598 const Type* DestTy = CE->getType();
599 switch (Op0->getType()->getTypeID()) {
600 default: llvm_unreachable("Invalid bitcast operand");
601 case Type::IntegerTyID:
602 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
603 if (DestTy->isFloatTy())
604 GV.FloatVal = GV.IntVal.bitsToFloat();
605 else if (DestTy->isDoubleTy())
606 GV.DoubleVal = GV.IntVal.bitsToDouble();
608 case Type::FloatTyID:
609 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
610 GV.IntVal.floatToBits(GV.FloatVal);
612 case Type::DoubleTyID:
613 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
614 GV.IntVal.doubleToBits(GV.DoubleVal);
616 case Type::PointerTyID:
617 assert(DestTy->isPointerTy() && "Invalid bitcast");
618 break; // getConstantValue(Op0) above already converted it
622 case Instruction::Add:
623 case Instruction::FAdd:
624 case Instruction::Sub:
625 case Instruction::FSub:
626 case Instruction::Mul:
627 case Instruction::FMul:
628 case Instruction::UDiv:
629 case Instruction::SDiv:
630 case Instruction::URem:
631 case Instruction::SRem:
632 case Instruction::And:
633 case Instruction::Or:
634 case Instruction::Xor: {
635 GenericValue LHS = getConstantValue(Op0);
636 GenericValue RHS = getConstantValue(CE->getOperand(1));
638 switch (CE->getOperand(0)->getType()->getTypeID()) {
639 default: llvm_unreachable("Bad add type!");
640 case Type::IntegerTyID:
641 switch (CE->getOpcode()) {
642 default: llvm_unreachable("Invalid integer opcode");
643 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
644 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
645 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
646 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
647 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
648 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
649 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
650 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
651 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
652 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
655 case Type::FloatTyID:
656 switch (CE->getOpcode()) {
657 default: llvm_unreachable("Invalid float opcode");
658 case Instruction::FAdd:
659 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
660 case Instruction::FSub:
661 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
662 case Instruction::FMul:
663 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
664 case Instruction::FDiv:
665 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
666 case Instruction::FRem:
667 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
670 case Type::DoubleTyID:
671 switch (CE->getOpcode()) {
672 default: llvm_unreachable("Invalid double opcode");
673 case Instruction::FAdd:
674 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
675 case Instruction::FSub:
676 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
677 case Instruction::FMul:
678 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
679 case Instruction::FDiv:
680 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
681 case Instruction::FRem:
682 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
685 case Type::X86_FP80TyID:
686 case Type::PPC_FP128TyID:
687 case Type::FP128TyID: {
688 APFloat apfLHS = APFloat(LHS.IntVal);
689 switch (CE->getOpcode()) {
690 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
691 case Instruction::FAdd:
692 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
693 GV.IntVal = apfLHS.bitcastToAPInt();
695 case Instruction::FSub:
696 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
697 GV.IntVal = apfLHS.bitcastToAPInt();
699 case Instruction::FMul:
700 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
701 GV.IntVal = apfLHS.bitcastToAPInt();
703 case Instruction::FDiv:
704 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
705 GV.IntVal = apfLHS.bitcastToAPInt();
707 case Instruction::FRem:
708 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
709 GV.IntVal = apfLHS.bitcastToAPInt();
721 raw_string_ostream Msg(msg);
722 Msg << "ConstantExpr not handled: " << *CE;
723 llvm_report_error(Msg.str());
727 switch (C->getType()->getTypeID()) {
728 case Type::FloatTyID:
729 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
731 case Type::DoubleTyID:
732 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
734 case Type::X86_FP80TyID:
735 case Type::FP128TyID:
736 case Type::PPC_FP128TyID:
737 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
739 case Type::IntegerTyID:
740 Result.IntVal = cast<ConstantInt>(C)->getValue();
742 case Type::PointerTyID:
743 if (isa<ConstantPointerNull>(C))
744 Result.PointerVal = 0;
745 else if (const Function *F = dyn_cast<Function>(C))
746 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
747 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
748 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
749 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
750 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
751 BA->getBasicBlock())));
753 llvm_unreachable("Unknown constant pointer type!");
757 raw_string_ostream Msg(msg);
758 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
759 llvm_report_error(Msg.str());
764 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
765 /// with the integer held in IntVal.
766 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
767 unsigned StoreBytes) {
768 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
769 uint8_t *Src = (uint8_t *)IntVal.getRawData();
771 if (sys::isLittleEndianHost())
772 // Little-endian host - the source is ordered from LSB to MSB. Order the
773 // destination from LSB to MSB: Do a straight copy.
774 memcpy(Dst, Src, StoreBytes);
776 // Big-endian host - the source is an array of 64 bit words ordered from
777 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
778 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
779 while (StoreBytes > sizeof(uint64_t)) {
780 StoreBytes -= sizeof(uint64_t);
781 // May not be aligned so use memcpy.
782 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
783 Src += sizeof(uint64_t);
786 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
790 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
791 /// is the address of the memory at which to store Val, cast to GenericValue *.
792 /// It is not a pointer to a GenericValue containing the address at which to
794 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
795 GenericValue *Ptr, const Type *Ty) {
796 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
798 switch (Ty->getTypeID()) {
799 case Type::IntegerTyID:
800 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
802 case Type::FloatTyID:
803 *((float*)Ptr) = Val.FloatVal;
805 case Type::DoubleTyID:
806 *((double*)Ptr) = Val.DoubleVal;
808 case Type::X86_FP80TyID:
809 memcpy(Ptr, Val.IntVal.getRawData(), 10);
811 case Type::PointerTyID:
812 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
813 if (StoreBytes != sizeof(PointerTy))
814 memset(Ptr, 0, StoreBytes);
816 *((PointerTy*)Ptr) = Val.PointerVal;
819 dbgs() << "Cannot store value of type " << *Ty << "!\n";
822 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
823 // Host and target are different endian - reverse the stored bytes.
824 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
827 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
828 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
829 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
830 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
831 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
833 if (sys::isLittleEndianHost())
834 // Little-endian host - the destination must be ordered from LSB to MSB.
835 // The source is ordered from LSB to MSB: Do a straight copy.
836 memcpy(Dst, Src, LoadBytes);
838 // Big-endian - the destination is an array of 64 bit words ordered from
839 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
840 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
842 while (LoadBytes > sizeof(uint64_t)) {
843 LoadBytes -= sizeof(uint64_t);
844 // May not be aligned so use memcpy.
845 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
846 Dst += sizeof(uint64_t);
849 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
855 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
858 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
860 switch (Ty->getTypeID()) {
861 case Type::IntegerTyID:
862 // An APInt with all words initially zero.
863 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
864 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
866 case Type::FloatTyID:
867 Result.FloatVal = *((float*)Ptr);
869 case Type::DoubleTyID:
870 Result.DoubleVal = *((double*)Ptr);
872 case Type::PointerTyID:
873 Result.PointerVal = *((PointerTy*)Ptr);
875 case Type::X86_FP80TyID: {
876 // This is endian dependent, but it will only work on x86 anyway.
877 // FIXME: Will not trap if loading a signaling NaN.
880 Result.IntVal = APInt(80, 2, y);
885 raw_string_ostream Msg(msg);
886 Msg << "Cannot load value of type " << *Ty << "!";
887 llvm_report_error(Msg.str());
891 // InitializeMemory - Recursive function to apply a Constant value into the
892 // specified memory location...
894 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
895 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
897 if (isa<UndefValue>(Init)) {
899 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
900 unsigned ElementSize =
901 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
902 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
903 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
905 } else if (isa<ConstantAggregateZero>(Init)) {
906 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
908 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
909 unsigned ElementSize =
910 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
911 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
912 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
914 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
915 const StructLayout *SL =
916 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
917 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
918 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
920 } else if (Init->getType()->isFirstClassType()) {
921 GenericValue Val = getConstantValue(Init);
922 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
926 dbgs() << "Bad Type: " << *Init->getType() << "\n";
927 llvm_unreachable("Unknown constant type to initialize memory with!");
930 /// EmitGlobals - Emit all of the global variables to memory, storing their
931 /// addresses into GlobalAddress. This must make sure to copy the contents of
932 /// their initializers into the memory.
934 void ExecutionEngine::emitGlobals() {
936 // Loop over all of the global variables in the program, allocating the memory
937 // to hold them. If there is more than one module, do a prepass over globals
938 // to figure out how the different modules should link together.
940 std::map<std::pair<std::string, const Type*>,
941 const GlobalValue*> LinkedGlobalsMap;
943 if (Modules.size() != 1) {
944 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
945 Module &M = *Modules[m];
946 for (Module::const_global_iterator I = M.global_begin(),
947 E = M.global_end(); I != E; ++I) {
948 const GlobalValue *GV = I;
949 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
950 GV->hasAppendingLinkage() || !GV->hasName())
951 continue;// Ignore external globals and globals with internal linkage.
953 const GlobalValue *&GVEntry =
954 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
956 // If this is the first time we've seen this global, it is the canonical
963 // If the existing global is strong, never replace it.
964 if (GVEntry->hasExternalLinkage() ||
965 GVEntry->hasDLLImportLinkage() ||
966 GVEntry->hasDLLExportLinkage())
969 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
970 // symbol. FIXME is this right for common?
971 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
977 std::vector<const GlobalValue*> NonCanonicalGlobals;
978 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
979 Module &M = *Modules[m];
980 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
982 // In the multi-module case, see what this global maps to.
983 if (!LinkedGlobalsMap.empty()) {
984 if (const GlobalValue *GVEntry =
985 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
986 // If something else is the canonical global, ignore this one.
987 if (GVEntry != &*I) {
988 NonCanonicalGlobals.push_back(I);
994 if (!I->isDeclaration()) {
995 addGlobalMapping(I, getMemoryForGV(I));
997 // External variable reference. Try to use the dynamic loader to
998 // get a pointer to it.
1000 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1001 addGlobalMapping(I, SymAddr);
1003 llvm_report_error("Could not resolve external global address: "
1009 // If there are multiple modules, map the non-canonical globals to their
1010 // canonical location.
1011 if (!NonCanonicalGlobals.empty()) {
1012 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1013 const GlobalValue *GV = NonCanonicalGlobals[i];
1014 const GlobalValue *CGV =
1015 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1016 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1017 assert(Ptr && "Canonical global wasn't codegen'd!");
1018 addGlobalMapping(GV, Ptr);
1022 // Now that all of the globals are set up in memory, loop through them all
1023 // and initialize their contents.
1024 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1026 if (!I->isDeclaration()) {
1027 if (!LinkedGlobalsMap.empty()) {
1028 if (const GlobalValue *GVEntry =
1029 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1030 if (GVEntry != &*I) // Not the canonical variable.
1033 EmitGlobalVariable(I);
1039 // EmitGlobalVariable - This method emits the specified global variable to the
1040 // address specified in GlobalAddresses, or allocates new memory if it's not
1041 // already in the map.
1042 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1043 void *GA = getPointerToGlobalIfAvailable(GV);
1046 // If it's not already specified, allocate memory for the global.
1047 GA = getMemoryForGV(GV);
1048 addGlobalMapping(GV, GA);
1051 // Don't initialize if it's thread local, let the client do it.
1052 if (!GV->isThreadLocal())
1053 InitializeMemory(GV->getInitializer(), GA);
1055 const Type *ElTy = GV->getType()->getElementType();
1056 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
1057 NumInitBytes += (unsigned)GVSize;
1061 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1062 : EE(EE), GlobalAddressMap(this) {
1065 sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1066 ExecutionEngineState *EES) {
1067 return &EES->EE.lock;
1069 void ExecutionEngineState::AddressMapConfig::onDelete(
1070 ExecutionEngineState *EES, const GlobalValue *Old) {
1071 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1072 EES->GlobalAddressReverseMap.erase(OldVal);
1075 void ExecutionEngineState::AddressMapConfig::onRAUW(
1076 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
1077 assert(false && "The ExecutionEngine doesn't know how to handle a"
1078 " RAUW on a value it has a global mapping for.");