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/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Config/alloca.h"
22 #include "llvm/ExecutionEngine/ExecutionEngine.h"
23 #include "llvm/ExecutionEngine/GenericValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/System/Host.h"
28 #include "llvm/Target/TargetData.h"
33 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34 STATISTIC(NumGlobals , "Number of global vars initialized");
36 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
41 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
42 LazyCompilationDisabled = false;
44 assert(P && "ModuleProvider is null?");
47 ExecutionEngine::~ExecutionEngine() {
48 clearAllGlobalMappings();
49 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
53 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54 /// Release module from ModuleProvider.
55 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
56 std::string *ErrInfo) {
57 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
58 E = Modules.end(); I != E; ++I) {
59 ModuleProvider *MP = *I;
62 return MP->releaseModule(ErrInfo);
68 /// FindFunctionNamed - Search all of the active modules to find the one that
69 /// defines FnName. This is very slow operation and shouldn't be used for
71 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
72 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
73 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
80 /// addGlobalMapping - Tell the execution engine that the specified global is
81 /// at the specified location. This is used internally as functions are JIT'd
82 /// and as global variables are laid out in memory. It can and should also be
83 /// used by clients of the EE that want to have an LLVM global overlay
84 /// existing data in memory.
85 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
86 MutexGuard locked(lock);
88 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
89 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
92 // If we are using the reverse mapping, add it too
93 if (!state.getGlobalAddressReverseMap(locked).empty()) {
94 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
95 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
100 /// clearAllGlobalMappings - Clear all global mappings and start over again
101 /// use in dynamic compilation scenarios when you want to move globals
102 void ExecutionEngine::clearAllGlobalMappings() {
103 MutexGuard locked(lock);
105 state.getGlobalAddressMap(locked).clear();
106 state.getGlobalAddressReverseMap(locked).clear();
109 /// updateGlobalMapping - Replace an existing mapping for GV with a new
110 /// address. This updates both maps as required. If "Addr" is null, the
111 /// entry for the global is removed from the mappings.
112 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
113 MutexGuard locked(lock);
115 // Deleting from the mapping?
117 state.getGlobalAddressMap(locked).erase(GV);
118 if (!state.getGlobalAddressReverseMap(locked).empty())
119 state.getGlobalAddressReverseMap(locked).erase(Addr);
123 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
124 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
125 state.getGlobalAddressReverseMap(locked).erase(CurVal);
128 // If we are using the reverse mapping, add it too
129 if (!state.getGlobalAddressReverseMap(locked).empty()) {
130 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
131 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
136 /// getPointerToGlobalIfAvailable - This returns the address of the specified
137 /// global value if it is has already been codegen'd, otherwise it returns null.
139 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
140 MutexGuard locked(lock);
142 std::map<const GlobalValue*, void*>::iterator I =
143 state.getGlobalAddressMap(locked).find(GV);
144 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
147 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
148 /// at the specified address.
150 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
151 MutexGuard locked(lock);
153 // If we haven't computed the reverse mapping yet, do so first.
154 if (state.getGlobalAddressReverseMap(locked).empty()) {
155 for (std::map<const GlobalValue*, void *>::iterator
156 I = state.getGlobalAddressMap(locked).begin(),
157 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
158 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
162 std::map<void *, const GlobalValue*>::iterator I =
163 state.getGlobalAddressReverseMap(locked).find(Addr);
164 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
167 // CreateArgv - Turn a vector of strings into a nice argv style array of
168 // pointers to null terminated strings.
170 static void *CreateArgv(ExecutionEngine *EE,
171 const std::vector<std::string> &InputArgv) {
172 unsigned PtrSize = EE->getTargetData()->getPointerSize();
173 char *Result = new char[(InputArgv.size()+1)*PtrSize];
175 DOUT << "ARGV = " << (void*)Result << "\n";
176 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
178 for (unsigned i = 0; i != InputArgv.size(); ++i) {
179 unsigned Size = InputArgv[i].size()+1;
180 char *Dest = new char[Size];
181 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
183 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
186 // Endian safe: Result[i] = (PointerTy)Dest;
187 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
192 EE->StoreValueToMemory(PTOGV(0),
193 (GenericValue*)(Result+InputArgv.size()*PtrSize),
199 /// runStaticConstructorsDestructors - This method is used to execute all of
200 /// the static constructors or destructors for a program, depending on the
201 /// value of isDtors.
202 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
203 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
205 // Execute global ctors/dtors for each module in the program.
206 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
207 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
209 // If this global has internal linkage, or if it has a use, then it must be
210 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
211 // this is the case, don't execute any of the global ctors, __main will do
213 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
215 // Should be an array of '{ int, void ()* }' structs. The first value is
216 // the init priority, which we ignore.
217 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
218 if (!InitList) continue;
219 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
220 if (ConstantStruct *CS =
221 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
222 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
224 Constant *FP = CS->getOperand(1);
225 if (FP->isNullValue())
226 break; // Found a null terminator, exit.
228 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
230 FP = CE->getOperand(0);
231 if (Function *F = dyn_cast<Function>(FP)) {
232 // Execute the ctor/dtor function!
233 runFunction(F, std::vector<GenericValue>());
239 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
240 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
241 unsigned PtrSize = EE->getTargetData()->getPointerSize();
242 for (unsigned i = 0; i < PtrSize; ++i)
243 if (*(i + (uint8_t*)Loc))
248 /// runFunctionAsMain - This is a helper function which wraps runFunction to
249 /// handle the common task of starting up main with the specified argc, argv,
250 /// and envp parameters.
251 int ExecutionEngine::runFunctionAsMain(Function *Fn,
252 const std::vector<std::string> &argv,
253 const char * const * envp) {
254 std::vector<GenericValue> GVArgs;
256 GVArgc.IntVal = APInt(32, argv.size());
259 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
260 const FunctionType *FTy = Fn->getFunctionType();
261 const Type* PPInt8Ty =
262 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
265 if (FTy->getParamType(2) != PPInt8Ty) {
266 cerr << "Invalid type for third argument of main() supplied\n";
271 if (FTy->getParamType(1) != PPInt8Ty) {
272 cerr << "Invalid type for second argument of main() supplied\n";
277 if (FTy->getParamType(0) != Type::Int32Ty) {
278 cerr << "Invalid type for first argument of main() supplied\n";
283 if (FTy->getReturnType() != Type::Int32Ty &&
284 FTy->getReturnType() != Type::VoidTy) {
285 cerr << "Invalid return type of main() supplied\n";
290 cerr << "Invalid number of arguments of main() supplied\n";
295 GVArgs.push_back(GVArgc); // Arg #0 = argc.
297 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
298 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
299 "argv[0] was null after CreateArgv");
301 std::vector<std::string> EnvVars;
302 for (unsigned i = 0; envp[i]; ++i)
303 EnvVars.push_back(envp[i]);
304 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
308 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
311 /// If possible, create a JIT, unless the caller specifically requests an
312 /// Interpreter or there's an error. If even an Interpreter cannot be created,
313 /// NULL is returned.
315 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
316 bool ForceInterpreter,
317 std::string *ErrorStr) {
318 ExecutionEngine *EE = 0;
320 // Unless the interpreter was explicitly selected, try making a JIT.
321 if (!ForceInterpreter && JITCtor)
322 EE = JITCtor(MP, ErrorStr);
324 // If we can't make a JIT, make an interpreter instead.
325 if (EE == 0 && InterpCtor)
326 EE = InterpCtor(MP, ErrorStr);
329 // Make sure we can resolve symbols in the program as well. The zero arg
330 // to the function tells DynamicLibrary to load the program, not a library.
331 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
340 ExecutionEngine *ExecutionEngine::create(Module *M) {
341 return create(new ExistingModuleProvider(M));
344 /// getPointerToGlobal - This returns the address of the specified global
345 /// value. This may involve code generation if it's a function.
347 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
348 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
349 return getPointerToFunction(F);
351 MutexGuard locked(lock);
352 void *p = state.getGlobalAddressMap(locked)[GV];
356 // Global variable might have been added since interpreter started.
357 if (GlobalVariable *GVar =
358 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
359 EmitGlobalVariable(GVar);
361 assert(0 && "Global hasn't had an address allocated yet!");
362 return state.getGlobalAddressMap(locked)[GV];
365 /// This function converts a Constant* into a GenericValue. The interesting
366 /// part is if C is a ConstantExpr.
367 /// @brief Get a GenericValue for a Constant*
368 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
369 // If its undefined, return the garbage.
370 if (isa<UndefValue>(C))
371 return GenericValue();
373 // If the value is a ConstantExpr
374 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
375 Constant *Op0 = CE->getOperand(0);
376 switch (CE->getOpcode()) {
377 case Instruction::GetElementPtr: {
379 GenericValue Result = getConstantValue(Op0);
380 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
382 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
384 char* tmp = (char*) Result.PointerVal;
385 Result = PTOGV(tmp + Offset);
388 case Instruction::Trunc: {
389 GenericValue GV = getConstantValue(Op0);
390 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
391 GV.IntVal = GV.IntVal.trunc(BitWidth);
394 case Instruction::ZExt: {
395 GenericValue GV = getConstantValue(Op0);
396 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
397 GV.IntVal = GV.IntVal.zext(BitWidth);
400 case Instruction::SExt: {
401 GenericValue GV = getConstantValue(Op0);
402 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
403 GV.IntVal = GV.IntVal.sext(BitWidth);
406 case Instruction::FPTrunc: {
408 GenericValue GV = getConstantValue(Op0);
409 GV.FloatVal = float(GV.DoubleVal);
412 case Instruction::FPExt:{
414 GenericValue GV = getConstantValue(Op0);
415 GV.DoubleVal = double(GV.FloatVal);
418 case Instruction::UIToFP: {
419 GenericValue GV = getConstantValue(Op0);
420 if (CE->getType() == Type::FloatTy)
421 GV.FloatVal = float(GV.IntVal.roundToDouble());
422 else if (CE->getType() == Type::DoubleTy)
423 GV.DoubleVal = GV.IntVal.roundToDouble();
424 else if (CE->getType() == Type::X86_FP80Ty) {
425 const uint64_t zero[] = {0, 0};
426 APFloat apf = APFloat(APInt(80, 2, zero));
427 (void)apf.convertFromAPInt(GV.IntVal,
429 APFloat::rmNearestTiesToEven);
430 GV.IntVal = apf.convertToAPInt();
434 case Instruction::SIToFP: {
435 GenericValue GV = getConstantValue(Op0);
436 if (CE->getType() == Type::FloatTy)
437 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
438 else if (CE->getType() == Type::DoubleTy)
439 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
440 else if (CE->getType() == Type::X86_FP80Ty) {
441 const uint64_t zero[] = { 0, 0};
442 APFloat apf = APFloat(APInt(80, 2, zero));
443 (void)apf.convertFromAPInt(GV.IntVal,
445 APFloat::rmNearestTiesToEven);
446 GV.IntVal = apf.convertToAPInt();
450 case Instruction::FPToUI: // double->APInt conversion handles sign
451 case Instruction::FPToSI: {
452 GenericValue GV = getConstantValue(Op0);
453 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
454 if (Op0->getType() == Type::FloatTy)
455 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
456 else if (Op0->getType() == Type::DoubleTy)
457 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
458 else if (Op0->getType() == Type::X86_FP80Ty) {
459 APFloat apf = APFloat(GV.IntVal);
461 (void)apf.convertToInteger(&v, BitWidth,
462 CE->getOpcode()==Instruction::FPToSI,
463 APFloat::rmTowardZero);
464 GV.IntVal = v; // endian?
468 case Instruction::PtrToInt: {
469 GenericValue GV = getConstantValue(Op0);
470 uint32_t PtrWidth = TD->getPointerSizeInBits();
471 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
474 case Instruction::IntToPtr: {
475 GenericValue GV = getConstantValue(Op0);
476 uint32_t PtrWidth = TD->getPointerSizeInBits();
477 if (PtrWidth != GV.IntVal.getBitWidth())
478 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
479 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
480 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
483 case Instruction::BitCast: {
484 GenericValue GV = getConstantValue(Op0);
485 const Type* DestTy = CE->getType();
486 switch (Op0->getType()->getTypeID()) {
487 default: assert(0 && "Invalid bitcast operand");
488 case Type::IntegerTyID:
489 assert(DestTy->isFloatingPoint() && "invalid bitcast");
490 if (DestTy == Type::FloatTy)
491 GV.FloatVal = GV.IntVal.bitsToFloat();
492 else if (DestTy == Type::DoubleTy)
493 GV.DoubleVal = GV.IntVal.bitsToDouble();
495 case Type::FloatTyID:
496 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
497 GV.IntVal.floatToBits(GV.FloatVal);
499 case Type::DoubleTyID:
500 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
501 GV.IntVal.doubleToBits(GV.DoubleVal);
503 case Type::PointerTyID:
504 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
505 break; // getConstantValue(Op0) above already converted it
509 case Instruction::Add:
510 case Instruction::Sub:
511 case Instruction::Mul:
512 case Instruction::UDiv:
513 case Instruction::SDiv:
514 case Instruction::URem:
515 case Instruction::SRem:
516 case Instruction::And:
517 case Instruction::Or:
518 case Instruction::Xor: {
519 GenericValue LHS = getConstantValue(Op0);
520 GenericValue RHS = getConstantValue(CE->getOperand(1));
522 switch (CE->getOperand(0)->getType()->getTypeID()) {
523 default: assert(0 && "Bad add type!"); abort();
524 case Type::IntegerTyID:
525 switch (CE->getOpcode()) {
526 default: assert(0 && "Invalid integer opcode");
527 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
528 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
529 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
530 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
531 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
532 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
533 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
534 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
535 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
536 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
539 case Type::FloatTyID:
540 switch (CE->getOpcode()) {
541 default: assert(0 && "Invalid float opcode"); abort();
542 case Instruction::Add:
543 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
544 case Instruction::Sub:
545 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
546 case Instruction::Mul:
547 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
548 case Instruction::FDiv:
549 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
550 case Instruction::FRem:
551 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
554 case Type::DoubleTyID:
555 switch (CE->getOpcode()) {
556 default: assert(0 && "Invalid double opcode"); abort();
557 case Instruction::Add:
558 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
559 case Instruction::Sub:
560 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
561 case Instruction::Mul:
562 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
563 case Instruction::FDiv:
564 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
565 case Instruction::FRem:
566 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
569 case Type::X86_FP80TyID:
570 case Type::PPC_FP128TyID:
571 case Type::FP128TyID: {
572 APFloat apfLHS = APFloat(LHS.IntVal);
573 switch (CE->getOpcode()) {
574 default: assert(0 && "Invalid long double opcode"); abort();
575 case Instruction::Add:
576 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
577 GV.IntVal = apfLHS.convertToAPInt();
579 case Instruction::Sub:
580 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
581 GV.IntVal = apfLHS.convertToAPInt();
583 case Instruction::Mul:
584 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
585 GV.IntVal = apfLHS.convertToAPInt();
587 case Instruction::FDiv:
588 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
589 GV.IntVal = apfLHS.convertToAPInt();
591 case Instruction::FRem:
592 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
593 GV.IntVal = apfLHS.convertToAPInt();
604 cerr << "ConstantExpr not handled: " << *CE << "\n";
609 switch (C->getType()->getTypeID()) {
610 case Type::FloatTyID:
611 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
613 case Type::DoubleTyID:
614 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
616 case Type::X86_FP80TyID:
617 case Type::FP128TyID:
618 case Type::PPC_FP128TyID:
619 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
621 case Type::IntegerTyID:
622 Result.IntVal = cast<ConstantInt>(C)->getValue();
624 case Type::PointerTyID:
625 if (isa<ConstantPointerNull>(C))
626 Result.PointerVal = 0;
627 else if (const Function *F = dyn_cast<Function>(C))
628 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
629 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
630 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
632 assert(0 && "Unknown constant pointer type!");
635 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
641 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
642 /// with the integer held in IntVal.
643 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
644 unsigned StoreBytes) {
645 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
646 uint8_t *Src = (uint8_t *)IntVal.getRawData();
648 if (sys::littleEndianHost())
649 // Little-endian host - the source is ordered from LSB to MSB. Order the
650 // destination from LSB to MSB: Do a straight copy.
651 memcpy(Dst, Src, StoreBytes);
653 // Big-endian host - the source is an array of 64 bit words ordered from
654 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
655 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
656 while (StoreBytes > sizeof(uint64_t)) {
657 StoreBytes -= sizeof(uint64_t);
658 // May not be aligned so use memcpy.
659 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
660 Src += sizeof(uint64_t);
663 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
667 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
668 /// is the address of the memory at which to store Val, cast to GenericValue *.
669 /// It is not a pointer to a GenericValue containing the address at which to
671 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
673 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
675 switch (Ty->getTypeID()) {
676 case Type::IntegerTyID:
677 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
679 case Type::FloatTyID:
680 *((float*)Ptr) = Val.FloatVal;
682 case Type::DoubleTyID:
683 *((double*)Ptr) = Val.DoubleVal;
685 case Type::X86_FP80TyID: {
686 uint16_t *Dest = (uint16_t*)Ptr;
687 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
688 // This is endian dependent, but it will only work on x86 anyway.
696 case Type::PointerTyID:
697 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
698 if (StoreBytes != sizeof(PointerTy))
699 memset(Ptr, 0, StoreBytes);
701 *((PointerTy*)Ptr) = Val.PointerVal;
704 cerr << "Cannot store value of type " << *Ty << "!\n";
707 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
708 // Host and target are different endian - reverse the stored bytes.
709 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
712 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
713 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
714 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
715 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
716 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
718 if (sys::littleEndianHost())
719 // Little-endian host - the destination must be ordered from LSB to MSB.
720 // The source is ordered from LSB to MSB: Do a straight copy.
721 memcpy(Dst, Src, LoadBytes);
723 // Big-endian - the destination is an array of 64 bit words ordered from
724 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
725 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
727 while (LoadBytes > sizeof(uint64_t)) {
728 LoadBytes -= sizeof(uint64_t);
729 // May not be aligned so use memcpy.
730 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
731 Dst += sizeof(uint64_t);
734 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
740 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
743 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
745 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
746 // Host and target are different endian - reverse copy the stored
747 // bytes into a buffer, and load from that.
748 uint8_t *Src = (uint8_t*)Ptr;
749 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
750 std::reverse_copy(Src, Src + LoadBytes, Buf);
751 Ptr = (GenericValue*)Buf;
754 switch (Ty->getTypeID()) {
755 case Type::IntegerTyID:
756 // An APInt with all words initially zero.
757 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
758 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
760 case Type::FloatTyID:
761 Result.FloatVal = *((float*)Ptr);
763 case Type::DoubleTyID:
764 Result.DoubleVal = *((double*)Ptr);
766 case Type::PointerTyID:
767 Result.PointerVal = *((PointerTy*)Ptr);
769 case Type::X86_FP80TyID: {
770 // This is endian dependent, but it will only work on x86 anyway.
771 // FIXME: Will not trap if loading a signaling NaN.
772 uint16_t *p = (uint16_t*)Ptr;
782 Result.IntVal = APInt(80, 2, y);
786 cerr << "Cannot load value of type " << *Ty << "!\n";
791 // InitializeMemory - Recursive function to apply a Constant value into the
792 // specified memory location...
794 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
795 if (isa<UndefValue>(Init)) {
797 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
798 unsigned ElementSize =
799 getTargetData()->getABITypeSize(CP->getType()->getElementType());
800 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
801 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
803 } else if (isa<ConstantAggregateZero>(Init)) {
804 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
806 } else if (Init->getType()->isFirstClassType()) {
807 GenericValue Val = getConstantValue(Init);
808 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
812 switch (Init->getType()->getTypeID()) {
813 case Type::ArrayTyID: {
814 const ConstantArray *CPA = cast<ConstantArray>(Init);
815 unsigned ElementSize =
816 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
817 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
818 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
822 case Type::StructTyID: {
823 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
824 const StructLayout *SL =
825 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
826 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
827 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
832 cerr << "Bad Type: " << *Init->getType() << "\n";
833 assert(0 && "Unknown constant type to initialize memory with!");
837 /// EmitGlobals - Emit all of the global variables to memory, storing their
838 /// addresses into GlobalAddress. This must make sure to copy the contents of
839 /// their initializers into the memory.
841 void ExecutionEngine::emitGlobals() {
842 const TargetData *TD = getTargetData();
844 // Loop over all of the global variables in the program, allocating the memory
845 // to hold them. If there is more than one module, do a prepass over globals
846 // to figure out how the different modules should link together.
848 std::map<std::pair<std::string, const Type*>,
849 const GlobalValue*> LinkedGlobalsMap;
851 if (Modules.size() != 1) {
852 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
853 Module &M = *Modules[m]->getModule();
854 for (Module::const_global_iterator I = M.global_begin(),
855 E = M.global_end(); I != E; ++I) {
856 const GlobalValue *GV = I;
857 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
858 GV->hasAppendingLinkage() || !GV->hasName())
859 continue;// Ignore external globals and globals with internal linkage.
861 const GlobalValue *&GVEntry =
862 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
864 // If this is the first time we've seen this global, it is the canonical
871 // If the existing global is strong, never replace it.
872 if (GVEntry->hasExternalLinkage() ||
873 GVEntry->hasDLLImportLinkage() ||
874 GVEntry->hasDLLExportLinkage())
877 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
879 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
885 std::vector<const GlobalValue*> NonCanonicalGlobals;
886 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
887 Module &M = *Modules[m]->getModule();
888 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
890 // In the multi-module case, see what this global maps to.
891 if (!LinkedGlobalsMap.empty()) {
892 if (const GlobalValue *GVEntry =
893 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
894 // If something else is the canonical global, ignore this one.
895 if (GVEntry != &*I) {
896 NonCanonicalGlobals.push_back(I);
902 if (!I->isDeclaration()) {
903 // Get the type of the global.
904 const Type *Ty = I->getType()->getElementType();
906 // Allocate some memory for it!
907 unsigned Size = TD->getABITypeSize(Ty);
908 addGlobalMapping(I, new char[Size]);
910 // External variable reference. Try to use the dynamic loader to
911 // get a pointer to it.
913 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
914 addGlobalMapping(I, SymAddr);
916 cerr << "Could not resolve external global address: "
917 << I->getName() << "\n";
923 // If there are multiple modules, map the non-canonical globals to their
924 // canonical location.
925 if (!NonCanonicalGlobals.empty()) {
926 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
927 const GlobalValue *GV = NonCanonicalGlobals[i];
928 const GlobalValue *CGV =
929 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
930 void *Ptr = getPointerToGlobalIfAvailable(CGV);
931 assert(Ptr && "Canonical global wasn't codegen'd!");
932 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
936 // Now that all of the globals are set up in memory, loop through them all
937 // and initialize their contents.
938 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
940 if (!I->isDeclaration()) {
941 if (!LinkedGlobalsMap.empty()) {
942 if (const GlobalValue *GVEntry =
943 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
944 if (GVEntry != &*I) // Not the canonical variable.
947 EmitGlobalVariable(I);
953 // EmitGlobalVariable - This method emits the specified global variable to the
954 // address specified in GlobalAddresses, or allocates new memory if it's not
955 // already in the map.
956 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
957 void *GA = getPointerToGlobalIfAvailable(GV);
958 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
960 const Type *ElTy = GV->getType()->getElementType();
961 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
963 // If it's not already specified, allocate memory for the global.
964 GA = new char[GVSize];
965 addGlobalMapping(GV, GA);
968 InitializeMemory(GV->getInitializer(), GA);
969 NumInitBytes += (unsigned)GVSize;