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"
29 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
30 STATISTIC(NumGlobals , "Number of global vars initialized");
32 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
33 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
35 ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
36 LazyCompilationDisabled = false;
38 assert(P && "ModuleProvider is null?");
41 ExecutionEngine::ExecutionEngine(Module *M) {
42 LazyCompilationDisabled = false;
43 assert(M && "Module is null?");
44 Modules.push_back(new ExistingModuleProvider(M));
47 ExecutionEngine::~ExecutionEngine() {
48 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
52 /// FindFunctionNamed - Search all of the active modules to find the one that
53 /// defines FnName. This is very slow operation and shouldn't be used for
55 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
56 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
57 if (Function *F = Modules[i]->getModule()->getNamedFunction(FnName))
64 /// addGlobalMapping - Tell the execution engine that the specified global is
65 /// at the specified location. This is used internally as functions are JIT'd
66 /// and as global variables are laid out in memory. It can and should also be
67 /// used by clients of the EE that want to have an LLVM global overlay
68 /// existing data in memory.
69 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
70 MutexGuard locked(lock);
72 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
73 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
76 // If we are using the reverse mapping, add it too
77 if (!state.getGlobalAddressReverseMap(locked).empty()) {
78 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
79 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
84 /// clearAllGlobalMappings - Clear all global mappings and start over again
85 /// use in dynamic compilation scenarios when you want to move globals
86 void ExecutionEngine::clearAllGlobalMappings() {
87 MutexGuard locked(lock);
89 state.getGlobalAddressMap(locked).clear();
90 state.getGlobalAddressReverseMap(locked).clear();
93 /// updateGlobalMapping - Replace an existing mapping for GV with a new
94 /// address. This updates both maps as required. If "Addr" is null, the
95 /// entry for the global is removed from the mappings.
96 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
97 MutexGuard locked(lock);
99 // Deleting from the mapping?
101 state.getGlobalAddressMap(locked).erase(GV);
102 if (!state.getGlobalAddressReverseMap(locked).empty())
103 state.getGlobalAddressReverseMap(locked).erase(Addr);
107 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
108 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
109 state.getGlobalAddressReverseMap(locked).erase(CurVal);
112 // If we are using the reverse mapping, add it too
113 if (!state.getGlobalAddressReverseMap(locked).empty()) {
114 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
115 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
120 /// getPointerToGlobalIfAvailable - This returns the address of the specified
121 /// global value if it is has already been codegen'd, otherwise it returns null.
123 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
124 MutexGuard locked(lock);
126 std::map<const GlobalValue*, void*>::iterator I =
127 state.getGlobalAddressMap(locked).find(GV);
128 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
131 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
132 /// at the specified address.
134 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
135 MutexGuard locked(lock);
137 // If we haven't computed the reverse mapping yet, do so first.
138 if (state.getGlobalAddressReverseMap(locked).empty()) {
139 for (std::map<const GlobalValue*, void *>::iterator
140 I = state.getGlobalAddressMap(locked).begin(),
141 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
142 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
146 std::map<void *, const GlobalValue*>::iterator I =
147 state.getGlobalAddressReverseMap(locked).find(Addr);
148 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
151 // CreateArgv - Turn a vector of strings into a nice argv style array of
152 // pointers to null terminated strings.
154 static void *CreateArgv(ExecutionEngine *EE,
155 const std::vector<std::string> &InputArgv) {
156 unsigned PtrSize = EE->getTargetData()->getPointerSize();
157 char *Result = new char[(InputArgv.size()+1)*PtrSize];
159 DOUT << "ARGV = " << (void*)Result << "\n";
160 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
162 for (unsigned i = 0; i != InputArgv.size(); ++i) {
163 unsigned Size = InputArgv[i].size()+1;
164 char *Dest = new char[Size];
165 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
167 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
170 // Endian safe: Result[i] = (PointerTy)Dest;
171 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
176 EE->StoreValueToMemory(PTOGV(0),
177 (GenericValue*)(Result+InputArgv.size()*PtrSize),
183 /// runStaticConstructorsDestructors - This method is used to execute all of
184 /// the static constructors or destructors for a program, depending on the
185 /// value of isDtors.
186 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
187 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
189 // Execute global ctors/dtors for each module in the program.
190 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
191 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
193 // If this global has internal linkage, or if it has a use, then it must be
194 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
195 // this is the case, don't execute any of the global ctors, __main will do
197 if (!GV || GV->isExternal() || GV->hasInternalLinkage()) continue;
199 // Should be an array of '{ int, void ()* }' structs. The first value is
200 // the init priority, which we ignore.
201 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
202 if (!InitList) continue;
203 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
204 if (ConstantStruct *CS =
205 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
206 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
208 Constant *FP = CS->getOperand(1);
209 if (FP->isNullValue())
210 break; // Found a null terminator, exit.
212 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
214 FP = CE->getOperand(0);
215 if (Function *F = dyn_cast<Function>(FP)) {
216 // Execute the ctor/dtor function!
217 runFunction(F, std::vector<GenericValue>());
223 /// runFunctionAsMain - This is a helper function which wraps runFunction to
224 /// handle the common task of starting up main with the specified argc, argv,
225 /// and envp parameters.
226 int ExecutionEngine::runFunctionAsMain(Function *Fn,
227 const std::vector<std::string> &argv,
228 const char * const * envp) {
229 std::vector<GenericValue> GVArgs;
231 GVArgc.Int32Val = argv.size();
232 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
234 GVArgs.push_back(GVArgc); // Arg #0 = argc.
236 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
237 assert(((char **)GVTOP(GVArgs[1]))[0] &&
238 "argv[0] was null after CreateArgv");
240 std::vector<std::string> EnvVars;
241 for (unsigned i = 0; envp[i]; ++i)
242 EnvVars.push_back(envp[i]);
243 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
247 return runFunction(Fn, GVArgs).Int32Val;
250 /// If possible, create a JIT, unless the caller specifically requests an
251 /// Interpreter or there's an error. If even an Interpreter cannot be created,
252 /// NULL is returned.
254 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
255 bool ForceInterpreter) {
256 ExecutionEngine *EE = 0;
258 // Unless the interpreter was explicitly selected, try making a JIT.
259 if (!ForceInterpreter && JITCtor)
262 // If we can't make a JIT, make an interpreter instead.
263 if (EE == 0 && InterpCtor)
267 // Make sure we can resolve symbols in the program as well. The zero arg
268 // to the function tells DynamicLibrary to load the program, not a library.
270 sys::DynamicLibrary::LoadLibraryPermanently(0);
278 /// getPointerToGlobal - This returns the address of the specified global
279 /// value. This may involve code generation if it's a function.
281 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
282 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
283 return getPointerToFunction(F);
285 MutexGuard locked(lock);
286 void *p = state.getGlobalAddressMap(locked)[GV];
290 // Global variable might have been added since interpreter started.
291 if (GlobalVariable *GVar =
292 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
293 EmitGlobalVariable(GVar);
295 assert("Global hasn't had an address allocated yet!");
296 return state.getGlobalAddressMap(locked)[GV];
299 /// This function converts a Constant* into a GenericValue. The interesting
300 /// part is if C is a ConstantExpr.
301 /// @brief Get a GenericValue for a Constnat*
302 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
303 // Declare the result as garbage.
306 // If its undefined, return the garbage.
307 if (isa<UndefValue>(C)) return Result;
309 // If the value is a ConstantExpr
310 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
311 switch (CE->getOpcode()) {
312 case Instruction::GetElementPtr: {
314 Result = getConstantValue(CE->getOperand(0));
315 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
317 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
319 if (getTargetData()->getPointerSize() == 4)
320 Result.Int32Val += Offset;
322 Result.Int64Val += Offset;
325 case Instruction::Trunc:
326 case Instruction::ZExt:
327 case Instruction::SExt:
328 case Instruction::FPTrunc:
329 case Instruction::FPExt:
330 case Instruction::UIToFP:
331 case Instruction::SIToFP:
332 case Instruction::FPToUI:
333 case Instruction::FPToSI:
335 case Instruction::PtrToInt: {
336 Constant *Op = CE->getOperand(0);
337 GenericValue GV = getConstantValue(Op);
340 case Instruction::BitCast: {
341 // Bit casts are no-ops but we can only return the GV of the operand if
342 // they are the same basic type (pointer->pointer, packed->packed, etc.)
343 Constant *Op = CE->getOperand(0);
344 GenericValue GV = getConstantValue(Op);
345 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
349 case Instruction::IntToPtr: {
350 // IntToPtr casts are just so special. Cast to intptr_t first.
351 Constant *Op = CE->getOperand(0);
352 GenericValue GV = getConstantValue(Op);
353 switch (Op->getType()->getTypeID()) {
354 case Type::Int1TyID: return PTOGV((void*)(uintptr_t)GV.Int1Val);
355 case Type::Int8TyID: return PTOGV((void*)(uintptr_t)GV.Int8Val);
356 case Type::Int16TyID: return PTOGV((void*)(uintptr_t)GV.Int16Val);
357 case Type::Int32TyID: return PTOGV((void*)(uintptr_t)GV.Int32Val);
358 case Type::Int64TyID: return PTOGV((void*)(uintptr_t)GV.Int64Val);
359 default: assert(0 && "Unknown integral type!");
363 case Instruction::Add:
364 switch (CE->getOperand(0)->getType()->getTypeID()) {
365 default: assert(0 && "Bad add type!"); abort();
366 case Type::Int64TyID:
367 Result.Int64Val = getConstantValue(CE->getOperand(0)).Int64Val +
368 getConstantValue(CE->getOperand(1)).Int64Val;
370 case Type::Int32TyID:
371 Result.Int32Val = getConstantValue(CE->getOperand(0)).Int32Val +
372 getConstantValue(CE->getOperand(1)).Int32Val;
374 case Type::Int16TyID:
375 Result.Int16Val = getConstantValue(CE->getOperand(0)).Int16Val +
376 getConstantValue(CE->getOperand(1)).Int16Val;
379 Result.Int8Val = getConstantValue(CE->getOperand(0)).Int8Val +
380 getConstantValue(CE->getOperand(1)).Int8Val;
382 case Type::FloatTyID:
383 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
384 getConstantValue(CE->getOperand(1)).FloatVal;
386 case Type::DoubleTyID:
387 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
388 getConstantValue(CE->getOperand(1)).DoubleVal;
395 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
399 switch (C->getType()->getTypeID()) {
400 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
401 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
402 GET_CONST_VAL(Int1 , bool , ConstantInt, getBoolValue);
403 GET_CONST_VAL(Int8 , unsigned char , ConstantInt, getZExtValue);
404 GET_CONST_VAL(Int16 , unsigned short, ConstantInt, getZExtValue);
405 GET_CONST_VAL(Int32 , unsigned int , ConstantInt, getZExtValue);
406 GET_CONST_VAL(Int64 , uint64_t , ConstantInt, getZExtValue);
407 GET_CONST_VAL(Float , float , ConstantFP, getValue);
408 GET_CONST_VAL(Double, double , ConstantFP, getValue);
410 case Type::PointerTyID:
411 if (isa<ConstantPointerNull>(C))
412 Result.PointerVal = 0;
413 else if (const Function *F = dyn_cast<Function>(C))
414 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
415 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
416 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
418 assert(0 && "Unknown constant pointer type!");
421 cerr << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
427 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
428 /// is the address of the memory at which to store Val, cast to GenericValue *.
429 /// It is not a pointer to a GenericValue containing the address at which to
432 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
434 if (getTargetData()->isLittleEndian()) {
435 switch (Ty->getTypeID()) {
437 case Type::Int8TyID: Ptr->Untyped[0] = Val.Int8Val; break;
438 case Type::Int16TyID: Ptr->Untyped[0] = Val.Int16Val & 255;
439 Ptr->Untyped[1] = (Val.Int16Val >> 8) & 255;
441 Store4BytesLittleEndian:
442 case Type::FloatTyID:
443 case Type::Int32TyID: Ptr->Untyped[0] = Val.Int32Val & 255;
444 Ptr->Untyped[1] = (Val.Int32Val >> 8) & 255;
445 Ptr->Untyped[2] = (Val.Int32Val >> 16) & 255;
446 Ptr->Untyped[3] = (Val.Int32Val >> 24) & 255;
448 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
449 goto Store4BytesLittleEndian;
450 case Type::DoubleTyID:
451 case Type::Int64TyID:
452 Ptr->Untyped[0] = (unsigned char)(Val.Int64Val );
453 Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >> 8);
454 Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 16);
455 Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 24);
456 Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 32);
457 Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 40);
458 Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >> 48);
459 Ptr->Untyped[7] = (unsigned char)(Val.Int64Val >> 56);
462 cerr << "Cannot store value of type " << *Ty << "!\n";
465 switch (Ty->getTypeID()) {
467 case Type::Int8TyID: Ptr->Untyped[0] = Val.Int8Val; break;
468 case Type::Int16TyID: Ptr->Untyped[1] = Val.Int16Val & 255;
469 Ptr->Untyped[0] = (Val.Int16Val >> 8) & 255;
471 Store4BytesBigEndian:
472 case Type::FloatTyID:
473 case Type::Int32TyID: Ptr->Untyped[3] = Val.Int32Val & 255;
474 Ptr->Untyped[2] = (Val.Int32Val >> 8) & 255;
475 Ptr->Untyped[1] = (Val.Int32Val >> 16) & 255;
476 Ptr->Untyped[0] = (Val.Int32Val >> 24) & 255;
478 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
479 goto Store4BytesBigEndian;
480 case Type::DoubleTyID:
481 case Type::Int64TyID:
482 Ptr->Untyped[7] = (unsigned char)(Val.Int64Val );
483 Ptr->Untyped[6] = (unsigned char)(Val.Int64Val >> 8);
484 Ptr->Untyped[5] = (unsigned char)(Val.Int64Val >> 16);
485 Ptr->Untyped[4] = (unsigned char)(Val.Int64Val >> 24);
486 Ptr->Untyped[3] = (unsigned char)(Val.Int64Val >> 32);
487 Ptr->Untyped[2] = (unsigned char)(Val.Int64Val >> 40);
488 Ptr->Untyped[1] = (unsigned char)(Val.Int64Val >> 48);
489 Ptr->Untyped[0] = (unsigned char)(Val.Int64Val >> 56);
492 cerr << "Cannot store value of type " << *Ty << "!\n";
499 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
502 if (getTargetData()->isLittleEndian()) {
503 switch (Ty->getTypeID()) {
505 case Type::Int8TyID: Result.Int8Val = Ptr->Untyped[0]; break;
506 case Type::Int16TyID: Result.Int16Val = (unsigned)Ptr->Untyped[0] |
507 ((unsigned)Ptr->Untyped[1] << 8);
509 Load4BytesLittleEndian:
510 case Type::FloatTyID:
511 case Type::Int32TyID: Result.Int32Val = (unsigned)Ptr->Untyped[0] |
512 ((unsigned)Ptr->Untyped[1] << 8) |
513 ((unsigned)Ptr->Untyped[2] << 16) |
514 ((unsigned)Ptr->Untyped[3] << 24);
516 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
517 goto Load4BytesLittleEndian;
518 case Type::DoubleTyID:
519 case Type::Int64TyID: Result.Int64Val = (uint64_t)Ptr->Untyped[0] |
520 ((uint64_t)Ptr->Untyped[1] << 8) |
521 ((uint64_t)Ptr->Untyped[2] << 16) |
522 ((uint64_t)Ptr->Untyped[3] << 24) |
523 ((uint64_t)Ptr->Untyped[4] << 32) |
524 ((uint64_t)Ptr->Untyped[5] << 40) |
525 ((uint64_t)Ptr->Untyped[6] << 48) |
526 ((uint64_t)Ptr->Untyped[7] << 56);
529 cerr << "Cannot load value of type " << *Ty << "!\n";
533 switch (Ty->getTypeID()) {
535 case Type::Int8TyID: Result.Int8Val = Ptr->Untyped[0]; break;
536 case Type::Int16TyID: Result.Int16Val = (unsigned)Ptr->Untyped[1] |
537 ((unsigned)Ptr->Untyped[0] << 8);
540 case Type::FloatTyID:
541 case Type::Int32TyID: Result.Int32Val =(unsigned)Ptr->Untyped[3] |
542 ((unsigned)Ptr->Untyped[2] << 8) |
543 ((unsigned)Ptr->Untyped[1] << 16) |
544 ((unsigned)Ptr->Untyped[0] << 24);
546 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
547 goto Load4BytesBigEndian;
548 case Type::DoubleTyID:
549 case Type::Int64TyID: Result.Int64Val = (uint64_t)Ptr->Untyped[7] |
550 ((uint64_t)Ptr->Untyped[6] << 8) |
551 ((uint64_t)Ptr->Untyped[5] << 16) |
552 ((uint64_t)Ptr->Untyped[4] << 24) |
553 ((uint64_t)Ptr->Untyped[3] << 32) |
554 ((uint64_t)Ptr->Untyped[2] << 40) |
555 ((uint64_t)Ptr->Untyped[1] << 48) |
556 ((uint64_t)Ptr->Untyped[0] << 56);
559 cerr << "Cannot load value of type " << *Ty << "!\n";
566 // InitializeMemory - Recursive function to apply a Constant value into the
567 // specified memory location...
569 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
570 if (isa<UndefValue>(Init)) {
572 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
573 unsigned ElementSize =
574 getTargetData()->getTypeSize(CP->getType()->getElementType());
575 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
576 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
578 } else if (Init->getType()->isFirstClassType()) {
579 GenericValue Val = getConstantValue(Init);
580 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
582 } else if (isa<ConstantAggregateZero>(Init)) {
583 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
587 switch (Init->getType()->getTypeID()) {
588 case Type::ArrayTyID: {
589 const ConstantArray *CPA = cast<ConstantArray>(Init);
590 unsigned ElementSize =
591 getTargetData()->getTypeSize(CPA->getType()->getElementType());
592 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
593 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
597 case Type::StructTyID: {
598 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
599 const StructLayout *SL =
600 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
601 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
602 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
607 cerr << "Bad Type: " << *Init->getType() << "\n";
608 assert(0 && "Unknown constant type to initialize memory with!");
612 /// EmitGlobals - Emit all of the global variables to memory, storing their
613 /// addresses into GlobalAddress. This must make sure to copy the contents of
614 /// their initializers into the memory.
616 void ExecutionEngine::emitGlobals() {
617 const TargetData *TD = getTargetData();
619 // Loop over all of the global variables in the program, allocating the memory
620 // to hold them. If there is more than one module, do a prepass over globals
621 // to figure out how the different modules should link together.
623 std::map<std::pair<std::string, const Type*>,
624 const GlobalValue*> LinkedGlobalsMap;
626 if (Modules.size() != 1) {
627 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
628 Module &M = *Modules[m]->getModule();
629 for (Module::const_global_iterator I = M.global_begin(),
630 E = M.global_end(); I != E; ++I) {
631 const GlobalValue *GV = I;
632 if (GV->hasInternalLinkage() || GV->isExternal() ||
633 GV->hasAppendingLinkage() || !GV->hasName())
634 continue;// Ignore external globals and globals with internal linkage.
636 const GlobalValue *&GVEntry =
637 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
639 // If this is the first time we've seen this global, it is the canonical
646 // If the existing global is strong, never replace it.
647 if (GVEntry->hasExternalLinkage() ||
648 GVEntry->hasDLLImportLinkage() ||
649 GVEntry->hasDLLExportLinkage())
652 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
654 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
660 std::vector<const GlobalValue*> NonCanonicalGlobals;
661 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
662 Module &M = *Modules[m]->getModule();
663 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
665 // In the multi-module case, see what this global maps to.
666 if (!LinkedGlobalsMap.empty()) {
667 if (const GlobalValue *GVEntry =
668 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
669 // If something else is the canonical global, ignore this one.
670 if (GVEntry != &*I) {
671 NonCanonicalGlobals.push_back(I);
677 if (!I->isExternal()) {
678 // Get the type of the global.
679 const Type *Ty = I->getType()->getElementType();
681 // Allocate some memory for it!
682 unsigned Size = TD->getTypeSize(Ty);
683 addGlobalMapping(I, new char[Size]);
685 // External variable reference. Try to use the dynamic loader to
686 // get a pointer to it.
688 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
689 addGlobalMapping(I, SymAddr);
691 cerr << "Could not resolve external global address: "
692 << I->getName() << "\n";
698 // If there are multiple modules, map the non-canonical globals to their
699 // canonical location.
700 if (!NonCanonicalGlobals.empty()) {
701 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
702 const GlobalValue *GV = NonCanonicalGlobals[i];
703 const GlobalValue *CGV =
704 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
705 void *Ptr = getPointerToGlobalIfAvailable(CGV);
706 assert(Ptr && "Canonical global wasn't codegen'd!");
707 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
711 // Now that all of the globals are set up in memory, loop through them all and
712 // initialize their contents.
713 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
715 if (!I->isExternal()) {
716 if (!LinkedGlobalsMap.empty()) {
717 if (const GlobalValue *GVEntry =
718 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
719 if (GVEntry != &*I) // Not the canonical variable.
722 EmitGlobalVariable(I);
728 // EmitGlobalVariable - This method emits the specified global variable to the
729 // address specified in GlobalAddresses, or allocates new memory if it's not
730 // already in the map.
731 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
732 void *GA = getPointerToGlobalIfAvailable(GV);
733 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
735 const Type *ElTy = GV->getType()->getElementType();
736 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
738 // If it's not already specified, allocate memory for the global.
739 GA = new char[GVSize];
740 addGlobalMapping(GV, GA);
743 InitializeMemory(GV->getInitializer(), GA);
744 NumInitBytes += (unsigned)GVSize;