1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/ExecutionEngine/GenericValue.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/MutexGuard.h"
25 #include "llvm/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetData.h"
30 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
31 STATISTIC(NumGlobals , "Number of global vars initialized");
33 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
34 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
37 LazyCompilationDisabled = false;
39 assert(P && "ModuleProvider is null?");
42 ExecutionEngine::~ExecutionEngine() {
43 clearAllGlobalMappings();
44 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
48 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
49 /// Release module from ModuleProvider.
50 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
51 std::string *ErrInfo) {
52 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
53 E = Modules.end(); I != E; ++I) {
54 ModuleProvider *MP = *I;
57 return MP->releaseModule(ErrInfo);
63 /// FindFunctionNamed - Search all of the active modules to find the one that
64 /// defines FnName. This is very slow operation and shouldn't be used for
66 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
67 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
68 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
75 /// addGlobalMapping - Tell the execution engine that the specified global is
76 /// at the specified location. This is used internally as functions are JIT'd
77 /// and as global variables are laid out in memory. It can and should also be
78 /// used by clients of the EE that want to have an LLVM global overlay
79 /// existing data in memory.
80 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
81 MutexGuard locked(lock);
83 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
84 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
87 // If we are using the reverse mapping, add it too
88 if (!state.getGlobalAddressReverseMap(locked).empty()) {
89 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
90 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
95 /// clearAllGlobalMappings - Clear all global mappings and start over again
96 /// use in dynamic compilation scenarios when you want to move globals
97 void ExecutionEngine::clearAllGlobalMappings() {
98 MutexGuard locked(lock);
100 state.getGlobalAddressMap(locked).clear();
101 state.getGlobalAddressReverseMap(locked).clear();
104 /// updateGlobalMapping - Replace an existing mapping for GV with a new
105 /// address. This updates both maps as required. If "Addr" is null, the
106 /// entry for the global is removed from the mappings.
107 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
108 MutexGuard locked(lock);
110 // Deleting from the mapping?
112 state.getGlobalAddressMap(locked).erase(GV);
113 if (!state.getGlobalAddressReverseMap(locked).empty())
114 state.getGlobalAddressReverseMap(locked).erase(Addr);
118 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
119 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
120 state.getGlobalAddressReverseMap(locked).erase(CurVal);
123 // If we are using the reverse mapping, add it too
124 if (!state.getGlobalAddressReverseMap(locked).empty()) {
125 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
126 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
131 /// getPointerToGlobalIfAvailable - This returns the address of the specified
132 /// global value if it is has already been codegen'd, otherwise it returns null.
134 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
135 MutexGuard locked(lock);
137 std::map<const GlobalValue*, void*>::iterator I =
138 state.getGlobalAddressMap(locked).find(GV);
139 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
142 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
143 /// at the specified address.
145 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
146 MutexGuard locked(lock);
148 // If we haven't computed the reverse mapping yet, do so first.
149 if (state.getGlobalAddressReverseMap(locked).empty()) {
150 for (std::map<const GlobalValue*, void *>::iterator
151 I = state.getGlobalAddressMap(locked).begin(),
152 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
153 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
157 std::map<void *, const GlobalValue*>::iterator I =
158 state.getGlobalAddressReverseMap(locked).find(Addr);
159 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
162 // CreateArgv - Turn a vector of strings into a nice argv style array of
163 // pointers to null terminated strings.
165 static void *CreateArgv(ExecutionEngine *EE,
166 const std::vector<std::string> &InputArgv) {
167 unsigned PtrSize = EE->getTargetData()->getPointerSize();
168 char *Result = new char[(InputArgv.size()+1)*PtrSize];
170 DOUT << "ARGV = " << (void*)Result << "\n";
171 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
173 for (unsigned i = 0; i != InputArgv.size(); ++i) {
174 unsigned Size = InputArgv[i].size()+1;
175 char *Dest = new char[Size];
176 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
178 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
181 // Endian safe: Result[i] = (PointerTy)Dest;
182 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
187 EE->StoreValueToMemory(PTOGV(0),
188 (GenericValue*)(Result+InputArgv.size()*PtrSize),
194 /// runStaticConstructorsDestructors - This method is used to execute all of
195 /// the static constructors or destructors for a program, depending on the
196 /// value of isDtors.
197 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
198 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
200 // Execute global ctors/dtors for each module in the program.
201 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
202 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
204 // If this global has internal linkage, or if it has a use, then it must be
205 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
206 // this is the case, don't execute any of the global ctors, __main will do
208 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
210 // Should be an array of '{ int, void ()* }' structs. The first value is
211 // the init priority, which we ignore.
212 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
213 if (!InitList) continue;
214 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
215 if (ConstantStruct *CS =
216 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
217 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
219 Constant *FP = CS->getOperand(1);
220 if (FP->isNullValue())
221 break; // Found a null terminator, exit.
223 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
225 FP = CE->getOperand(0);
226 if (Function *F = dyn_cast<Function>(FP)) {
227 // Execute the ctor/dtor function!
228 runFunction(F, std::vector<GenericValue>());
234 /// runFunctionAsMain - This is a helper function which wraps runFunction to
235 /// handle the common task of starting up main with the specified argc, argv,
236 /// and envp parameters.
237 int ExecutionEngine::runFunctionAsMain(Function *Fn,
238 const std::vector<std::string> &argv,
239 const char * const * envp) {
240 std::vector<GenericValue> GVArgs;
242 GVArgc.IntVal = APInt(32, argv.size());
245 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
246 const FunctionType *FTy = Fn->getFunctionType();
247 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
250 if (FTy->getParamType(2) != PPInt8Ty) {
251 cerr << "Invalid type for third argument of main() supplied\n";
256 if (FTy->getParamType(1) != PPInt8Ty) {
257 cerr << "Invalid type for second argument of main() supplied\n";
262 if (FTy->getParamType(0) != Type::Int32Ty) {
263 cerr << "Invalid type for first argument of main() supplied\n";
268 if (FTy->getReturnType() != Type::Int32Ty &&
269 FTy->getReturnType() != Type::VoidTy) {
270 cerr << "Invalid return type of main() supplied\n";
275 cerr << "Invalid number of arguments of main() supplied\n";
280 GVArgs.push_back(GVArgc); // Arg #0 = argc.
282 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
283 assert(((char **)GVTOP(GVArgs[1]))[0] &&
284 "argv[0] was null after CreateArgv");
286 std::vector<std::string> EnvVars;
287 for (unsigned i = 0; envp[i]; ++i)
288 EnvVars.push_back(envp[i]);
289 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
293 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
296 /// If possible, create a JIT, unless the caller specifically requests an
297 /// Interpreter or there's an error. If even an Interpreter cannot be created,
298 /// NULL is returned.
300 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
301 bool ForceInterpreter,
302 std::string *ErrorStr) {
303 ExecutionEngine *EE = 0;
305 // Unless the interpreter was explicitly selected, try making a JIT.
306 if (!ForceInterpreter && JITCtor)
307 EE = JITCtor(MP, ErrorStr);
309 // If we can't make a JIT, make an interpreter instead.
310 if (EE == 0 && InterpCtor)
311 EE = InterpCtor(MP, ErrorStr);
314 // Make sure we can resolve symbols in the program as well. The zero arg
315 // to the function tells DynamicLibrary to load the program, not a library.
316 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
325 ExecutionEngine *ExecutionEngine::create(Module *M) {
326 return create(new ExistingModuleProvider(M));
329 /// getPointerToGlobal - This returns the address of the specified global
330 /// value. This may involve code generation if it's a function.
332 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
333 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
334 return getPointerToFunction(F);
336 MutexGuard locked(lock);
337 void *p = state.getGlobalAddressMap(locked)[GV];
341 // Global variable might have been added since interpreter started.
342 if (GlobalVariable *GVar =
343 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
344 EmitGlobalVariable(GVar);
346 assert(0 && "Global hasn't had an address allocated yet!");
347 return state.getGlobalAddressMap(locked)[GV];
350 /// This function converts a Constant* into a GenericValue. The interesting
351 /// part is if C is a ConstantExpr.
352 /// @brief Get a GenericValue for a Constant*
353 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
354 // If its undefined, return the garbage.
355 if (isa<UndefValue>(C))
356 return GenericValue();
358 // If the value is a ConstantExpr
359 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
360 Constant *Op0 = CE->getOperand(0);
361 switch (CE->getOpcode()) {
362 case Instruction::GetElementPtr: {
364 GenericValue Result = getConstantValue(Op0);
365 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
367 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
369 char* tmp = (char*) Result.PointerVal;
370 Result = PTOGV(tmp + Offset);
373 case Instruction::Trunc: {
374 GenericValue GV = getConstantValue(Op0);
375 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
376 GV.IntVal = GV.IntVal.trunc(BitWidth);
379 case Instruction::ZExt: {
380 GenericValue GV = getConstantValue(Op0);
381 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
382 GV.IntVal = GV.IntVal.zext(BitWidth);
385 case Instruction::SExt: {
386 GenericValue GV = getConstantValue(Op0);
387 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
388 GV.IntVal = GV.IntVal.sext(BitWidth);
391 case Instruction::FPTrunc: {
393 GenericValue GV = getConstantValue(Op0);
394 GV.FloatVal = float(GV.DoubleVal);
397 case Instruction::FPExt:{
399 GenericValue GV = getConstantValue(Op0);
400 GV.DoubleVal = double(GV.FloatVal);
403 case Instruction::UIToFP: {
404 GenericValue GV = getConstantValue(Op0);
405 if (CE->getType() == Type::FloatTy)
406 GV.FloatVal = float(GV.IntVal.roundToDouble());
407 else if (CE->getType() == Type::DoubleTy)
408 GV.DoubleVal = GV.IntVal.roundToDouble();
409 else if (CE->getType() == Type::X86_FP80Ty) {
410 const uint64_t zero[] = {0, 0};
411 APFloat apf = APFloat(APInt(80, 2, zero));
412 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
413 GV.IntVal.getBitWidth(), false,
414 APFloat::rmNearestTiesToEven);
415 GV.IntVal = apf.convertToAPInt();
419 case Instruction::SIToFP: {
420 GenericValue GV = getConstantValue(Op0);
421 if (CE->getType() == Type::FloatTy)
422 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
423 else if (CE->getType() == Type::DoubleTy)
424 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
425 else if (CE->getType() == Type::X86_FP80Ty) {
426 const uint64_t zero[] = { 0, 0};
427 APFloat apf = APFloat(APInt(80, 2, zero));
428 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
429 GV.IntVal.getBitWidth(), true,
430 APFloat::rmNearestTiesToEven);
431 GV.IntVal = apf.convertToAPInt();
435 case Instruction::FPToUI: // double->APInt conversion handles sign
436 case Instruction::FPToSI: {
437 GenericValue GV = getConstantValue(Op0);
438 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
439 if (Op0->getType() == Type::FloatTy)
440 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
441 else if (Op0->getType() == Type::DoubleTy)
442 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
443 else if (Op0->getType() == Type::X86_FP80Ty) {
444 APFloat apf = APFloat(GV.IntVal);
446 (void)apf.convertToInteger(&v, BitWidth,
447 CE->getOpcode()==Instruction::FPToSI,
448 APFloat::rmTowardZero);
449 GV.IntVal = v; // endian?
453 case Instruction::PtrToInt: {
454 GenericValue GV = getConstantValue(Op0);
455 uint32_t PtrWidth = TD->getPointerSizeInBits();
456 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
459 case Instruction::IntToPtr: {
460 GenericValue GV = getConstantValue(Op0);
461 uint32_t PtrWidth = TD->getPointerSizeInBits();
462 if (PtrWidth != GV.IntVal.getBitWidth())
463 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
464 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
465 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
468 case Instruction::BitCast: {
469 GenericValue GV = getConstantValue(Op0);
470 const Type* DestTy = CE->getType();
471 switch (Op0->getType()->getTypeID()) {
472 default: assert(0 && "Invalid bitcast operand");
473 case Type::IntegerTyID:
474 assert(DestTy->isFloatingPoint() && "invalid bitcast");
475 if (DestTy == Type::FloatTy)
476 GV.FloatVal = GV.IntVal.bitsToFloat();
477 else if (DestTy == Type::DoubleTy)
478 GV.DoubleVal = GV.IntVal.bitsToDouble();
480 case Type::FloatTyID:
481 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
482 GV.IntVal.floatToBits(GV.FloatVal);
484 case Type::DoubleTyID:
485 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
486 GV.IntVal.doubleToBits(GV.DoubleVal);
488 case Type::PointerTyID:
489 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
490 break; // getConstantValue(Op0) above already converted it
494 case Instruction::Add:
495 case Instruction::Sub:
496 case Instruction::Mul:
497 case Instruction::UDiv:
498 case Instruction::SDiv:
499 case Instruction::URem:
500 case Instruction::SRem:
501 case Instruction::And:
502 case Instruction::Or:
503 case Instruction::Xor: {
504 GenericValue LHS = getConstantValue(Op0);
505 GenericValue RHS = getConstantValue(CE->getOperand(1));
507 switch (CE->getOperand(0)->getType()->getTypeID()) {
508 default: assert(0 && "Bad add type!"); abort();
509 case Type::IntegerTyID:
510 switch (CE->getOpcode()) {
511 default: assert(0 && "Invalid integer opcode");
512 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
513 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
514 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
515 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
516 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
517 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
518 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
519 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
520 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
521 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
524 case Type::FloatTyID:
525 switch (CE->getOpcode()) {
526 default: assert(0 && "Invalid float opcode"); abort();
527 case Instruction::Add:
528 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
529 case Instruction::Sub:
530 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
531 case Instruction::Mul:
532 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
533 case Instruction::FDiv:
534 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
535 case Instruction::FRem:
536 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
539 case Type::DoubleTyID:
540 switch (CE->getOpcode()) {
541 default: assert(0 && "Invalid double opcode"); abort();
542 case Instruction::Add:
543 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
544 case Instruction::Sub:
545 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
546 case Instruction::Mul:
547 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
548 case Instruction::FDiv:
549 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
550 case Instruction::FRem:
551 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
554 case Type::X86_FP80TyID:
555 case Type::PPC_FP128TyID:
556 case Type::FP128TyID: {
557 APFloat apfLHS = APFloat(LHS.IntVal);
558 switch (CE->getOpcode()) {
559 default: assert(0 && "Invalid long double opcode"); abort();
560 case Instruction::Add:
561 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
562 GV.IntVal = apfLHS.convertToAPInt();
564 case Instruction::Sub:
565 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
566 GV.IntVal = apfLHS.convertToAPInt();
568 case Instruction::Mul:
569 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
570 GV.IntVal = apfLHS.convertToAPInt();
572 case Instruction::FDiv:
573 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
574 GV.IntVal = apfLHS.convertToAPInt();
576 case Instruction::FRem:
577 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
578 GV.IntVal = apfLHS.convertToAPInt();
589 cerr << "ConstantExpr not handled: " << *CE << "\n";
594 switch (C->getType()->getTypeID()) {
595 case Type::FloatTyID:
596 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
598 case Type::DoubleTyID:
599 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
601 case Type::X86_FP80TyID:
602 case Type::FP128TyID:
603 case Type::PPC_FP128TyID:
604 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
606 case Type::IntegerTyID:
607 Result.IntVal = cast<ConstantInt>(C)->getValue();
609 case Type::PointerTyID:
610 if (isa<ConstantPointerNull>(C))
611 Result.PointerVal = 0;
612 else if (const Function *F = dyn_cast<Function>(C))
613 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
614 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
615 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
617 assert(0 && "Unknown constant pointer type!");
620 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
626 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
627 /// is the address of the memory at which to store Val, cast to GenericValue *.
628 /// It is not a pointer to a GenericValue containing the address at which to
631 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
633 switch (Ty->getTypeID()) {
634 case Type::IntegerTyID: {
635 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
636 unsigned StoreBytes = (BitWidth + 7)/8;
637 uint8_t *Src = (uint8_t *)Val.IntVal.getRawData();
638 uint8_t *Dst = (uint8_t *)Ptr;
640 if (getTargetData()->hostIsLittleEndian())
641 // Little-endian host - the source is ordered from LSB to MSB.
642 // Order the destination from LSB to MSB: Do a straight copy.
643 memcpy(Dst, Src, StoreBytes);
645 // Big-endian host - the source is an array of 64 bit words ordered from
646 // LSW to MSW. Each word is ordered from MSB to LSB.
647 // Order the destination from MSB to LSB: Reverse the word order, but not
648 // the bytes in a word.
649 while (StoreBytes > sizeof(uint64_t)) {
650 StoreBytes -= sizeof(uint64_t);
651 // May not be aligned so use memcpy.
652 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
653 Src += sizeof(uint64_t);
656 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
660 case Type::FloatTyID:
661 *((float*)Ptr) = Val.FloatVal;
663 case Type::DoubleTyID:
664 *((double*)Ptr) = Val.DoubleVal;
666 case Type::X86_FP80TyID: {
667 uint16_t *Dest = (uint16_t*)Ptr;
668 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
669 // This is endian dependent, but it will only work on x86 anyway.
677 case Type::PointerTyID:
678 *((PointerTy*)Ptr) = Val.PointerVal;
681 cerr << "Cannot store value of type " << *Ty << "!\n";
687 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
690 switch (Ty->getTypeID()) {
691 case Type::IntegerTyID: {
692 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
693 unsigned LoadBytes = (BitWidth + 7)/8;
695 // An APInt with all words initially zero.
696 Result.IntVal = APInt(BitWidth, 0);
698 uint8_t *Src = (uint8_t *)Ptr;
699 uint8_t *Dst = (uint8_t *)Result.IntVal.getRawData();
701 if (getTargetData()->hostIsLittleEndian())
702 // Little-endian host - the destination must be ordered from LSB to MSB.
703 // The source is ordered from LSB to MSB: Do a straight copy.
704 memcpy(Dst, Src, LoadBytes);
706 // Big-endian - the destination is an array of 64 bit words ordered from
707 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
708 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
710 while (LoadBytes > sizeof(uint64_t)) {
711 LoadBytes -= sizeof(uint64_t);
712 // May not be aligned so use memcpy.
713 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
714 Dst += sizeof(uint64_t);
717 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
721 case Type::FloatTyID:
722 Result.FloatVal = *((float*)Ptr);
724 case Type::DoubleTyID:
725 Result.DoubleVal = *((double*)Ptr);
727 case Type::PointerTyID:
728 Result.PointerVal = *((PointerTy*)Ptr);
730 case Type::X86_FP80TyID: {
731 // This is endian dependent, but it will only work on x86 anyway.
732 uint16_t *p = (uint16_t*)Ptr;
742 Result.IntVal = APInt(80, 2, y);
746 cerr << "Cannot load value of type " << *Ty << "!\n";
751 // InitializeMemory - Recursive function to apply a Constant value into the
752 // specified memory location...
754 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
755 if (isa<UndefValue>(Init)) {
757 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
758 unsigned ElementSize =
759 getTargetData()->getABITypeSize(CP->getType()->getElementType());
760 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
761 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
763 } else if (Init->getType()->isFirstClassType()) {
764 GenericValue Val = getConstantValue(Init);
765 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
767 } else if (isa<ConstantAggregateZero>(Init)) {
768 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
772 switch (Init->getType()->getTypeID()) {
773 case Type::ArrayTyID: {
774 const ConstantArray *CPA = cast<ConstantArray>(Init);
775 unsigned ElementSize =
776 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
777 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
778 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
782 case Type::StructTyID: {
783 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
784 const StructLayout *SL =
785 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
786 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
787 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
792 cerr << "Bad Type: " << *Init->getType() << "\n";
793 assert(0 && "Unknown constant type to initialize memory with!");
797 /// EmitGlobals - Emit all of the global variables to memory, storing their
798 /// addresses into GlobalAddress. This must make sure to copy the contents of
799 /// their initializers into the memory.
801 void ExecutionEngine::emitGlobals() {
802 const TargetData *TD = getTargetData();
804 // Loop over all of the global variables in the program, allocating the memory
805 // to hold them. If there is more than one module, do a prepass over globals
806 // to figure out how the different modules should link together.
808 std::map<std::pair<std::string, const Type*>,
809 const GlobalValue*> LinkedGlobalsMap;
811 if (Modules.size() != 1) {
812 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
813 Module &M = *Modules[m]->getModule();
814 for (Module::const_global_iterator I = M.global_begin(),
815 E = M.global_end(); I != E; ++I) {
816 const GlobalValue *GV = I;
817 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
818 GV->hasAppendingLinkage() || !GV->hasName())
819 continue;// Ignore external globals and globals with internal linkage.
821 const GlobalValue *&GVEntry =
822 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
824 // If this is the first time we've seen this global, it is the canonical
831 // If the existing global is strong, never replace it.
832 if (GVEntry->hasExternalLinkage() ||
833 GVEntry->hasDLLImportLinkage() ||
834 GVEntry->hasDLLExportLinkage())
837 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
839 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
845 std::vector<const GlobalValue*> NonCanonicalGlobals;
846 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
847 Module &M = *Modules[m]->getModule();
848 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
850 // In the multi-module case, see what this global maps to.
851 if (!LinkedGlobalsMap.empty()) {
852 if (const GlobalValue *GVEntry =
853 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
854 // If something else is the canonical global, ignore this one.
855 if (GVEntry != &*I) {
856 NonCanonicalGlobals.push_back(I);
862 if (!I->isDeclaration()) {
863 // Get the type of the global.
864 const Type *Ty = I->getType()->getElementType();
866 // Allocate some memory for it!
867 unsigned Size = TD->getABITypeSize(Ty);
868 addGlobalMapping(I, new char[Size]);
870 // External variable reference. Try to use the dynamic loader to
871 // get a pointer to it.
873 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
874 addGlobalMapping(I, SymAddr);
876 cerr << "Could not resolve external global address: "
877 << I->getName() << "\n";
883 // If there are multiple modules, map the non-canonical globals to their
884 // canonical location.
885 if (!NonCanonicalGlobals.empty()) {
886 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
887 const GlobalValue *GV = NonCanonicalGlobals[i];
888 const GlobalValue *CGV =
889 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
890 void *Ptr = getPointerToGlobalIfAvailable(CGV);
891 assert(Ptr && "Canonical global wasn't codegen'd!");
892 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
896 // Now that all of the globals are set up in memory, loop through them all
897 // and initialize their contents.
898 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
900 if (!I->isDeclaration()) {
901 if (!LinkedGlobalsMap.empty()) {
902 if (const GlobalValue *GVEntry =
903 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
904 if (GVEntry != &*I) // Not the canonical variable.
907 EmitGlobalVariable(I);
913 // EmitGlobalVariable - This method emits the specified global variable to the
914 // address specified in GlobalAddresses, or allocates new memory if it's not
915 // already in the map.
916 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
917 void *GA = getPointerToGlobalIfAvailable(GV);
918 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
920 const Type *ElTy = GV->getType()->getElementType();
921 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
923 // If it's not already specified, allocate memory for the global.
924 GA = new char[GVSize];
925 addGlobalMapping(GV, GA);
928 InitializeMemory(GV->getInitializer(), GA);
929 NumInitBytes += (unsigned)GVSize;