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"
31 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
32 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
35 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
38 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
40 assert(P && "ModuleProvider is null?");
43 ExecutionEngine::ExecutionEngine(Module *M) {
44 assert(M && "Module is null?");
45 Modules.push_back(new ExistingModuleProvider(M));
48 ExecutionEngine::~ExecutionEngine() {
49 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
53 /// FindFunctionNamed - Search all of the active modules to find the one that
54 /// defines FnName. This is very slow operation and shouldn't be used for
56 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
57 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
58 if (Function *F = Modules[i]->getModule()->getNamedFunction(FnName))
65 /// addGlobalMapping - Tell the execution engine that the specified global is
66 /// at the specified location. This is used internally as functions are JIT'd
67 /// and as global variables are laid out in memory. It can and should also be
68 /// used by clients of the EE that want to have an LLVM global overlay
69 /// existing data in memory.
70 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
71 MutexGuard locked(lock);
73 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
74 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
77 // If we are using the reverse mapping, add it too
78 if (!state.getGlobalAddressReverseMap(locked).empty()) {
79 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
80 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
85 /// clearAllGlobalMappings - Clear all global mappings and start over again
86 /// use in dynamic compilation scenarios when you want to move globals
87 void ExecutionEngine::clearAllGlobalMappings() {
88 MutexGuard locked(lock);
90 state.getGlobalAddressMap(locked).clear();
91 state.getGlobalAddressReverseMap(locked).clear();
94 /// updateGlobalMapping - Replace an existing mapping for GV with a new
95 /// address. This updates both maps as required. If "Addr" is null, the
96 /// entry for the global is removed from the mappings.
97 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
98 MutexGuard locked(lock);
100 // Deleting from the mapping?
102 state.getGlobalAddressMap(locked).erase(GV);
103 if (!state.getGlobalAddressReverseMap(locked).empty())
104 state.getGlobalAddressReverseMap(locked).erase(Addr);
108 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
109 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
110 state.getGlobalAddressReverseMap(locked).erase(CurVal);
113 // If we are using the reverse mapping, add it too
114 if (!state.getGlobalAddressReverseMap(locked).empty()) {
115 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
116 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
121 /// getPointerToGlobalIfAvailable - This returns the address of the specified
122 /// global value if it is has already been codegen'd, otherwise it returns null.
124 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
125 MutexGuard locked(lock);
127 std::map<const GlobalValue*, void*>::iterator I =
128 state.getGlobalAddressMap(locked).find(GV);
129 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
132 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
133 /// at the specified address.
135 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
136 MutexGuard locked(lock);
138 // If we haven't computed the reverse mapping yet, do so first.
139 if (state.getGlobalAddressReverseMap(locked).empty()) {
140 for (std::map<const GlobalValue*, void *>::iterator
141 I = state.getGlobalAddressMap(locked).begin(),
142 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
143 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
147 std::map<void *, const GlobalValue*>::iterator I =
148 state.getGlobalAddressReverseMap(locked).find(Addr);
149 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
152 // CreateArgv - Turn a vector of strings into a nice argv style array of
153 // pointers to null terminated strings.
155 static void *CreateArgv(ExecutionEngine *EE,
156 const std::vector<std::string> &InputArgv) {
157 unsigned PtrSize = EE->getTargetData()->getPointerSize();
158 char *Result = new char[(InputArgv.size()+1)*PtrSize];
160 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
161 const Type *SBytePtr = PointerType::get(Type::SByteTy);
163 for (unsigned i = 0; i != InputArgv.size(); ++i) {
164 unsigned Size = InputArgv[i].size()+1;
165 char *Dest = new char[Size];
166 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
168 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
171 // Endian safe: Result[i] = (PointerTy)Dest;
172 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
177 EE->StoreValueToMemory(PTOGV(0),
178 (GenericValue*)(Result+InputArgv.size()*PtrSize),
184 /// runStaticConstructorsDestructors - This method is used to execute all of
185 /// the static constructors or destructors for a program, depending on the
186 /// value of isDtors.
187 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
188 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
190 // Execute global ctors/dtors for each module in the program.
191 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
192 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
194 // If this global has internal linkage, or if it has a use, then it must be
195 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
196 // this is the case, don't execute any of the global ctors, __main will do
198 if (!GV || GV->isExternal() || GV->hasInternalLinkage()) continue;
200 // Should be an array of '{ int, void ()* }' structs. The first value is
201 // the init priority, which we ignore.
202 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
203 if (!InitList) continue;
204 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
205 if (ConstantStruct *CS =
206 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
207 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
209 Constant *FP = CS->getOperand(1);
210 if (FP->isNullValue())
211 break; // Found a null terminator, exit.
213 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
214 if (CE->getOpcode() == Instruction::Cast)
215 FP = CE->getOperand(0);
216 if (Function *F = dyn_cast<Function>(FP)) {
217 // Execute the ctor/dtor function!
218 runFunction(F, std::vector<GenericValue>());
224 /// runFunctionAsMain - This is a helper function which wraps runFunction to
225 /// handle the common task of starting up main with the specified argc, argv,
226 /// and envp parameters.
227 int ExecutionEngine::runFunctionAsMain(Function *Fn,
228 const std::vector<std::string> &argv,
229 const char * const * envp) {
230 std::vector<GenericValue> GVArgs;
232 GVArgc.IntVal = argv.size();
233 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
235 GVArgs.push_back(GVArgc); // Arg #0 = argc.
237 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
238 assert(((char **)GVTOP(GVArgs[1]))[0] &&
239 "argv[0] was null after CreateArgv");
241 std::vector<std::string> EnvVars;
242 for (unsigned i = 0; envp[i]; ++i)
243 EnvVars.push_back(envp[i]);
244 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
248 return runFunction(Fn, GVArgs).IntVal;
251 /// If possible, create a JIT, unless the caller specifically requests an
252 /// Interpreter or there's an error. If even an Interpreter cannot be created,
253 /// NULL is returned.
255 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
256 bool ForceInterpreter) {
257 ExecutionEngine *EE = 0;
259 // Unless the interpreter was explicitly selected, try making a JIT.
260 if (!ForceInterpreter && JITCtor)
263 // If we can't make a JIT, make an interpreter instead.
264 if (EE == 0 && InterpCtor)
268 // Make sure we can resolve symbols in the program as well. The zero arg
269 // to the function tells DynamicLibrary to load the program, not a library.
271 sys::DynamicLibrary::LoadLibraryPermanently(0);
279 /// getPointerToGlobal - This returns the address of the specified global
280 /// value. This may involve code generation if it's a function.
282 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
283 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
284 return getPointerToFunction(F);
286 MutexGuard locked(lock);
287 void *p = state.getGlobalAddressMap(locked)[GV];
291 // Global variable might have been added since interpreter started.
292 if (GlobalVariable *GVar =
293 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
294 EmitGlobalVariable(GVar);
296 assert("Global hasn't had an address allocated yet!");
297 return state.getGlobalAddressMap(locked)[GV];
302 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
304 if (isa<UndefValue>(C)) return Result;
306 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
307 switch (CE->getOpcode()) {
308 case Instruction::GetElementPtr: {
309 Result = getConstantValue(CE->getOperand(0));
310 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
312 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
314 if (getTargetData()->getPointerSize() == 4)
315 Result.IntVal += Offset;
317 Result.LongVal += Offset;
320 case Instruction::Cast: {
321 // We only need to handle a few cases here. Almost all casts will
322 // automatically fold, just the ones involving pointers won't.
324 Constant *Op = CE->getOperand(0);
325 GenericValue GV = getConstantValue(Op);
327 // Handle cast of pointer to pointer...
328 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
331 // Handle a cast of pointer to any integral type...
332 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
335 // Handle cast of integer to a pointer...
336 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
337 switch (Op->getType()->getTypeID()) {
338 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
339 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
340 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
341 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
342 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
343 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
344 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
345 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
346 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
347 default: assert(0 && "Unknown integral type!");
352 case Instruction::Add:
353 switch (CE->getOperand(0)->getType()->getTypeID()) {
354 default: assert(0 && "Bad add type!"); abort();
356 case Type::ULongTyID:
357 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
358 getConstantValue(CE->getOperand(1)).LongVal;
362 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
363 getConstantValue(CE->getOperand(1)).IntVal;
365 case Type::ShortTyID:
366 case Type::UShortTyID:
367 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
368 getConstantValue(CE->getOperand(1)).ShortVal;
370 case Type::SByteTyID:
371 case Type::UByteTyID:
372 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
373 getConstantValue(CE->getOperand(1)).SByteVal;
375 case Type::FloatTyID:
376 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
377 getConstantValue(CE->getOperand(1)).FloatVal;
379 case Type::DoubleTyID:
380 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
381 getConstantValue(CE->getOperand(1)).DoubleVal;
388 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
392 switch (C->getType()->getTypeID()) {
393 #define GET_CONST_VAL(TY, CTY, CLASS) \
394 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
395 GET_CONST_VAL(Bool , bool , ConstantBool);
396 GET_CONST_VAL(UByte , unsigned char , ConstantUInt);
397 GET_CONST_VAL(SByte , signed char , ConstantSInt);
398 GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
399 GET_CONST_VAL(Short , signed short , ConstantSInt);
400 GET_CONST_VAL(UInt , unsigned int , ConstantUInt);
401 GET_CONST_VAL(Int , signed int , ConstantSInt);
402 GET_CONST_VAL(ULong , uint64_t , ConstantUInt);
403 GET_CONST_VAL(Long , int64_t , ConstantSInt);
404 GET_CONST_VAL(Float , float , ConstantFP);
405 GET_CONST_VAL(Double , double , ConstantFP);
407 case Type::PointerTyID:
408 if (isa<ConstantPointerNull>(C))
409 Result.PointerVal = 0;
410 else if (const Function *F = dyn_cast<Function>(C))
411 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
412 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
413 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
415 assert(0 && "Unknown constant pointer type!");
418 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
424 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
425 /// is the address of the memory at which to store Val, cast to GenericValue *.
426 /// It is not a pointer to a GenericValue containing the address at which to
429 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
431 if (getTargetData()->isLittleEndian()) {
432 switch (Ty->getTypeID()) {
434 case Type::UByteTyID:
435 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
436 case Type::UShortTyID:
437 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
438 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
440 Store4BytesLittleEndian:
441 case Type::FloatTyID:
443 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
444 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
445 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
446 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
448 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
449 goto Store4BytesLittleEndian;
450 case Type::DoubleTyID:
451 case Type::ULongTyID:
453 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
454 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
455 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
456 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
457 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
458 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
459 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
460 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
463 std::cout << "Cannot store value of type " << *Ty << "!\n";
466 switch (Ty->getTypeID()) {
468 case Type::UByteTyID:
469 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
470 case Type::UShortTyID:
471 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
472 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
474 Store4BytesBigEndian:
475 case Type::FloatTyID:
477 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
478 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
479 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
480 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
482 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
483 goto Store4BytesBigEndian;
484 case Type::DoubleTyID:
485 case Type::ULongTyID:
487 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
488 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
489 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
490 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
491 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
492 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
493 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
494 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
497 std::cout << "Cannot store value of type " << *Ty << "!\n";
504 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
507 if (getTargetData()->isLittleEndian()) {
508 switch (Ty->getTypeID()) {
510 case Type::UByteTyID:
511 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
512 case Type::UShortTyID:
513 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
514 ((unsigned)Ptr->Untyped[1] << 8);
516 Load4BytesLittleEndian:
517 case Type::FloatTyID:
519 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
520 ((unsigned)Ptr->Untyped[1] << 8) |
521 ((unsigned)Ptr->Untyped[2] << 16) |
522 ((unsigned)Ptr->Untyped[3] << 24);
524 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
525 goto Load4BytesLittleEndian;
526 case Type::DoubleTyID:
527 case Type::ULongTyID:
528 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
529 ((uint64_t)Ptr->Untyped[1] << 8) |
530 ((uint64_t)Ptr->Untyped[2] << 16) |
531 ((uint64_t)Ptr->Untyped[3] << 24) |
532 ((uint64_t)Ptr->Untyped[4] << 32) |
533 ((uint64_t)Ptr->Untyped[5] << 40) |
534 ((uint64_t)Ptr->Untyped[6] << 48) |
535 ((uint64_t)Ptr->Untyped[7] << 56);
538 std::cout << "Cannot load value of type " << *Ty << "!\n";
542 switch (Ty->getTypeID()) {
544 case Type::UByteTyID:
545 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
546 case Type::UShortTyID:
547 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
548 ((unsigned)Ptr->Untyped[0] << 8);
551 case Type::FloatTyID:
553 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
554 ((unsigned)Ptr->Untyped[2] << 8) |
555 ((unsigned)Ptr->Untyped[1] << 16) |
556 ((unsigned)Ptr->Untyped[0] << 24);
558 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
559 goto Load4BytesBigEndian;
560 case Type::DoubleTyID:
561 case Type::ULongTyID:
562 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
563 ((uint64_t)Ptr->Untyped[6] << 8) |
564 ((uint64_t)Ptr->Untyped[5] << 16) |
565 ((uint64_t)Ptr->Untyped[4] << 24) |
566 ((uint64_t)Ptr->Untyped[3] << 32) |
567 ((uint64_t)Ptr->Untyped[2] << 40) |
568 ((uint64_t)Ptr->Untyped[1] << 48) |
569 ((uint64_t)Ptr->Untyped[0] << 56);
572 std::cout << "Cannot load value of type " << *Ty << "!\n";
579 // InitializeMemory - Recursive function to apply a Constant value into the
580 // specified memory location...
582 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
583 if (isa<UndefValue>(Init)) {
585 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
586 unsigned ElementSize =
587 getTargetData()->getTypeSize(CP->getType()->getElementType());
588 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
589 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
591 } else if (Init->getType()->isFirstClassType()) {
592 GenericValue Val = getConstantValue(Init);
593 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
595 } else if (isa<ConstantAggregateZero>(Init)) {
596 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
600 switch (Init->getType()->getTypeID()) {
601 case Type::ArrayTyID: {
602 const ConstantArray *CPA = cast<ConstantArray>(Init);
603 unsigned ElementSize =
604 getTargetData()->getTypeSize(CPA->getType()->getElementType());
605 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
606 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
610 case Type::StructTyID: {
611 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
612 const StructLayout *SL =
613 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
614 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
615 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
620 std::cerr << "Bad Type: " << *Init->getType() << "\n";
621 assert(0 && "Unknown constant type to initialize memory with!");
625 /// EmitGlobals - Emit all of the global variables to memory, storing their
626 /// addresses into GlobalAddress. This must make sure to copy the contents of
627 /// their initializers into the memory.
629 void ExecutionEngine::emitGlobals() {
630 const TargetData *TD = getTargetData();
632 // Loop over all of the global variables in the program, allocating the memory
633 // to hold them. If there is more than one module, do a prepass over globals
634 // to figure out how the different modules should link together.
636 std::map<std::pair<std::string, const Type*>,
637 const GlobalValue*> LinkedGlobalsMap;
639 if (Modules.size() != 1) {
640 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
641 Module &M = *Modules[m]->getModule();
642 for (Module::const_global_iterator I = M.global_begin(),
643 E = M.global_end(); I != E; ++I) {
644 const GlobalValue *GV = I;
645 if (GV->hasInternalLinkage() || GV->isExternal() ||
646 GV->hasAppendingLinkage() || !GV->hasName())
647 continue;// Ignore external globals and globals with internal linkage.
649 const GlobalValue *&GVEntry =
650 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
652 // If this is the first time we've seen this global, it is the canonical
659 // If the existing global is strong, never replace it.
660 if (GVEntry->hasExternalLinkage() ||
661 GVEntry->hasDLLImportLinkage() ||
662 GVEntry->hasDLLExportLinkage())
665 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
667 if (GV->hasExternalLinkage())
673 std::vector<const GlobalValue*> NonCanonicalGlobals;
674 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
675 Module &M = *Modules[m]->getModule();
676 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
678 // In the multi-module case, see what this global maps to.
679 if (!LinkedGlobalsMap.empty()) {
680 if (const GlobalValue *GVEntry =
681 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
682 // If something else is the canonical global, ignore this one.
683 if (GVEntry != &*I) {
684 NonCanonicalGlobals.push_back(I);
690 if (!I->isExternal()) {
691 // Get the type of the global.
692 const Type *Ty = I->getType()->getElementType();
694 // Allocate some memory for it!
695 unsigned Size = TD->getTypeSize(Ty);
696 addGlobalMapping(I, new char[Size]);
698 // External variable reference. Try to use the dynamic loader to
699 // get a pointer to it.
701 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
702 addGlobalMapping(I, SymAddr);
704 std::cerr << "Could not resolve external global address: "
705 << I->getName() << "\n";
711 // If there are multiple modules, map the non-canonical globals to their
712 // canonical location.
713 if (!NonCanonicalGlobals.empty()) {
714 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
715 const GlobalValue *GV = NonCanonicalGlobals[i];
716 const GlobalValue *CGV =
717 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
718 void *Ptr = getPointerToGlobalIfAvailable(CGV);
719 assert(Ptr && "Canonical global wasn't codegen'd!");
720 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
724 // Now that all of the globals are set up in memory, loop through them all and
725 // initialize their contents.
726 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
728 if (!I->isExternal()) {
729 if (!LinkedGlobalsMap.empty()) {
730 if (const GlobalValue *GVEntry =
731 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
732 if (GVEntry != &*I) // Not the canonical variable.
735 EmitGlobalVariable(I);
741 // EmitGlobalVariable - This method emits the specified global variable to the
742 // address specified in GlobalAddresses, or allocates new memory if it's not
743 // already in the map.
744 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
745 void *GA = getPointerToGlobalIfAvailable(GV);
746 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
748 const Type *ElTy = GV->getType()->getElementType();
749 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
751 // If it's not already specified, allocate memory for the global.
752 GA = new char[GVSize];
753 addGlobalMapping(GV, GA);
756 InitializeMemory(GV->getInitializer(), GA);
757 NumInitBytes += (unsigned)GVSize;