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) {
39 LazyCompilationDisabled = false;
41 assert(P && "ModuleProvider is null?");
44 ExecutionEngine::ExecutionEngine(Module *M) {
45 LazyCompilationDisabled = false;
46 assert(M && "Module is null?");
47 Modules.push_back(new ExistingModuleProvider(M));
50 ExecutionEngine::~ExecutionEngine() {
51 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
55 /// FindFunctionNamed - Search all of the active modules to find the one that
56 /// defines FnName. This is very slow operation and shouldn't be used for
58 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
59 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
60 if (Function *F = Modules[i]->getModule()->getNamedFunction(FnName))
67 /// addGlobalMapping - Tell the execution engine that the specified global is
68 /// at the specified location. This is used internally as functions are JIT'd
69 /// and as global variables are laid out in memory. It can and should also be
70 /// used by clients of the EE that want to have an LLVM global overlay
71 /// existing data in memory.
72 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
73 MutexGuard locked(lock);
75 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
76 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
79 // If we are using the reverse mapping, add it too
80 if (!state.getGlobalAddressReverseMap(locked).empty()) {
81 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
82 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
87 /// clearAllGlobalMappings - Clear all global mappings and start over again
88 /// use in dynamic compilation scenarios when you want to move globals
89 void ExecutionEngine::clearAllGlobalMappings() {
90 MutexGuard locked(lock);
92 state.getGlobalAddressMap(locked).clear();
93 state.getGlobalAddressReverseMap(locked).clear();
96 /// updateGlobalMapping - Replace an existing mapping for GV with a new
97 /// address. This updates both maps as required. If "Addr" is null, the
98 /// entry for the global is removed from the mappings.
99 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
100 MutexGuard locked(lock);
102 // Deleting from the mapping?
104 state.getGlobalAddressMap(locked).erase(GV);
105 if (!state.getGlobalAddressReverseMap(locked).empty())
106 state.getGlobalAddressReverseMap(locked).erase(Addr);
110 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
111 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
112 state.getGlobalAddressReverseMap(locked).erase(CurVal);
115 // If we are using the reverse mapping, add it too
116 if (!state.getGlobalAddressReverseMap(locked).empty()) {
117 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
118 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
123 /// getPointerToGlobalIfAvailable - This returns the address of the specified
124 /// global value if it is has already been codegen'd, otherwise it returns null.
126 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
127 MutexGuard locked(lock);
129 std::map<const GlobalValue*, void*>::iterator I =
130 state.getGlobalAddressMap(locked).find(GV);
131 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
134 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
135 /// at the specified address.
137 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
138 MutexGuard locked(lock);
140 // If we haven't computed the reverse mapping yet, do so first.
141 if (state.getGlobalAddressReverseMap(locked).empty()) {
142 for (std::map<const GlobalValue*, void *>::iterator
143 I = state.getGlobalAddressMap(locked).begin(),
144 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
145 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
149 std::map<void *, const GlobalValue*>::iterator I =
150 state.getGlobalAddressReverseMap(locked).find(Addr);
151 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
154 // CreateArgv - Turn a vector of strings into a nice argv style array of
155 // pointers to null terminated strings.
157 static void *CreateArgv(ExecutionEngine *EE,
158 const std::vector<std::string> &InputArgv) {
159 unsigned PtrSize = EE->getTargetData()->getPointerSize();
160 char *Result = new char[(InputArgv.size()+1)*PtrSize];
162 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
163 const Type *SBytePtr = PointerType::get(Type::SByteTy);
165 for (unsigned i = 0; i != InputArgv.size(); ++i) {
166 unsigned Size = InputArgv[i].size()+1;
167 char *Dest = new char[Size];
168 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
170 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
173 // Endian safe: Result[i] = (PointerTy)Dest;
174 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
179 EE->StoreValueToMemory(PTOGV(0),
180 (GenericValue*)(Result+InputArgv.size()*PtrSize),
186 /// runStaticConstructorsDestructors - This method is used to execute all of
187 /// the static constructors or destructors for a program, depending on the
188 /// value of isDtors.
189 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
190 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
192 // Execute global ctors/dtors for each module in the program.
193 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
194 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
196 // If this global has internal linkage, or if it has a use, then it must be
197 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
198 // this is the case, don't execute any of the global ctors, __main will do
200 if (!GV || GV->isExternal() || GV->hasInternalLinkage()) continue;
202 // Should be an array of '{ int, void ()* }' structs. The first value is
203 // the init priority, which we ignore.
204 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
205 if (!InitList) continue;
206 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
207 if (ConstantStruct *CS =
208 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
209 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
211 Constant *FP = CS->getOperand(1);
212 if (FP->isNullValue())
213 break; // Found a null terminator, exit.
215 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
217 FP = CE->getOperand(0);
218 if (Function *F = dyn_cast<Function>(FP)) {
219 // Execute the ctor/dtor function!
220 runFunction(F, std::vector<GenericValue>());
226 /// runFunctionAsMain - This is a helper function which wraps runFunction to
227 /// handle the common task of starting up main with the specified argc, argv,
228 /// and envp parameters.
229 int ExecutionEngine::runFunctionAsMain(Function *Fn,
230 const std::vector<std::string> &argv,
231 const char * const * envp) {
232 std::vector<GenericValue> GVArgs;
234 GVArgc.IntVal = argv.size();
235 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
237 GVArgs.push_back(GVArgc); // Arg #0 = argc.
239 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
240 assert(((char **)GVTOP(GVArgs[1]))[0] &&
241 "argv[0] was null after CreateArgv");
243 std::vector<std::string> EnvVars;
244 for (unsigned i = 0; envp[i]; ++i)
245 EnvVars.push_back(envp[i]);
246 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
250 return runFunction(Fn, GVArgs).IntVal;
253 /// If possible, create a JIT, unless the caller specifically requests an
254 /// Interpreter or there's an error. If even an Interpreter cannot be created,
255 /// NULL is returned.
257 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
258 bool ForceInterpreter) {
259 ExecutionEngine *EE = 0;
261 // Unless the interpreter was explicitly selected, try making a JIT.
262 if (!ForceInterpreter && JITCtor)
265 // If we can't make a JIT, make an interpreter instead.
266 if (EE == 0 && InterpCtor)
270 // Make sure we can resolve symbols in the program as well. The zero arg
271 // to the function tells DynamicLibrary to load the program, not a library.
273 sys::DynamicLibrary::LoadLibraryPermanently(0);
281 /// getPointerToGlobal - This returns the address of the specified global
282 /// value. This may involve code generation if it's a function.
284 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
285 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
286 return getPointerToFunction(F);
288 MutexGuard locked(lock);
289 void *p = state.getGlobalAddressMap(locked)[GV];
293 // Global variable might have been added since interpreter started.
294 if (GlobalVariable *GVar =
295 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
296 EmitGlobalVariable(GVar);
298 assert("Global hasn't had an address allocated yet!");
299 return state.getGlobalAddressMap(locked)[GV];
302 /// This function converts a Constant* into a GenericValue. The interesting
303 /// part is if C is a ConstantExpr.
304 /// @brief Get a GenericValue for a Constnat*
305 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
306 // Declare the result as garbage.
309 // If its undefined, return the garbage.
310 if (isa<UndefValue>(C)) return Result;
312 // If the value is a ConstantExpr
313 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
314 switch (CE->getOpcode()) {
315 case Instruction::GetElementPtr: {
317 Result = getConstantValue(CE->getOperand(0));
318 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
320 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
322 if (getTargetData()->getPointerSize() == 4)
323 Result.IntVal += Offset;
325 Result.LongVal += Offset;
328 case Instruction::Trunc:
329 case Instruction::ZExt:
330 case Instruction::SExt:
331 case Instruction::FPTrunc:
332 case Instruction::FPExt:
333 case Instruction::UIToFP:
334 case Instruction::SIToFP:
335 case Instruction::FPToUI:
336 case Instruction::FPToSI:
338 case Instruction::PtrToInt: {
339 Constant *Op = CE->getOperand(0);
340 GenericValue GV = getConstantValue(Op);
343 case Instruction::BitCast: {
344 // Bit casts are no-ops but we can only return the GV of the operand if
345 // they are the same basic type (pointer->pointer, packed->packed, etc.)
346 Constant *Op = CE->getOperand(0);
347 GenericValue GV = getConstantValue(Op);
348 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
352 case Instruction::IntToPtr: {
353 // IntToPtr casts are just so special. Cast to intptr_t first.
354 Constant *Op = CE->getOperand(0);
355 GenericValue GV = getConstantValue(Op);
356 switch (Op->getType()->getTypeID()) {
357 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
358 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
359 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
360 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
361 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
362 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
363 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
364 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
365 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
366 default: assert(0 && "Unknown integral type!");
370 case Instruction::Add:
371 switch (CE->getOperand(0)->getType()->getTypeID()) {
372 default: assert(0 && "Bad add type!"); abort();
374 case Type::ULongTyID:
375 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
376 getConstantValue(CE->getOperand(1)).LongVal;
380 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
381 getConstantValue(CE->getOperand(1)).IntVal;
383 case Type::ShortTyID:
384 case Type::UShortTyID:
385 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
386 getConstantValue(CE->getOperand(1)).ShortVal;
388 case Type::SByteTyID:
389 case Type::UByteTyID:
390 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
391 getConstantValue(CE->getOperand(1)).SByteVal;
393 case Type::FloatTyID:
394 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
395 getConstantValue(CE->getOperand(1)).FloatVal;
397 case Type::DoubleTyID:
398 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
399 getConstantValue(CE->getOperand(1)).DoubleVal;
406 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
410 switch (C->getType()->getTypeID()) {
411 #define GET_CONST_VAL(TY, CTY, CLASS, GETMETH) \
412 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->GETMETH(); break
413 GET_CONST_VAL(Bool , bool , ConstantBool, getValue);
414 GET_CONST_VAL(UByte , unsigned char , ConstantInt, getZExtValue);
415 GET_CONST_VAL(SByte , signed char , ConstantInt, getSExtValue);
416 GET_CONST_VAL(UShort , unsigned short, ConstantInt, getZExtValue);
417 GET_CONST_VAL(Short , signed short , ConstantInt, getSExtValue);
418 GET_CONST_VAL(UInt , unsigned int , ConstantInt, getZExtValue);
419 GET_CONST_VAL(Int , signed int , ConstantInt, getSExtValue);
420 GET_CONST_VAL(ULong , uint64_t , ConstantInt, getZExtValue);
421 GET_CONST_VAL(Long , int64_t , ConstantInt, getSExtValue);
422 GET_CONST_VAL(Float , float , ConstantFP, getValue);
423 GET_CONST_VAL(Double , double , ConstantFP, getValue);
425 case Type::PointerTyID:
426 if (isa<ConstantPointerNull>(C))
427 Result.PointerVal = 0;
428 else if (const Function *F = dyn_cast<Function>(C))
429 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
430 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
431 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
433 assert(0 && "Unknown constant pointer type!");
436 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
442 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
443 /// is the address of the memory at which to store Val, cast to GenericValue *.
444 /// It is not a pointer to a GenericValue containing the address at which to
447 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
449 if (getTargetData()->isLittleEndian()) {
450 switch (Ty->getTypeID()) {
452 case Type::UByteTyID:
453 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
454 case Type::UShortTyID:
455 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
456 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
458 Store4BytesLittleEndian:
459 case Type::FloatTyID:
461 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
462 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
463 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
464 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
466 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
467 goto Store4BytesLittleEndian;
468 case Type::DoubleTyID:
469 case Type::ULongTyID:
471 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
472 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
473 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
474 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
475 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
476 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
477 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
478 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
481 std::cout << "Cannot store value of type " << *Ty << "!\n";
484 switch (Ty->getTypeID()) {
486 case Type::UByteTyID:
487 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
488 case Type::UShortTyID:
489 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
490 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
492 Store4BytesBigEndian:
493 case Type::FloatTyID:
495 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
496 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
497 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
498 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
500 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
501 goto Store4BytesBigEndian;
502 case Type::DoubleTyID:
503 case Type::ULongTyID:
505 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
506 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
507 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
508 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
509 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
510 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
511 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
512 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
515 std::cout << "Cannot store value of type " << *Ty << "!\n";
522 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
525 if (getTargetData()->isLittleEndian()) {
526 switch (Ty->getTypeID()) {
528 case Type::UByteTyID:
529 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
530 case Type::UShortTyID:
531 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
532 ((unsigned)Ptr->Untyped[1] << 8);
534 Load4BytesLittleEndian:
535 case Type::FloatTyID:
537 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
538 ((unsigned)Ptr->Untyped[1] << 8) |
539 ((unsigned)Ptr->Untyped[2] << 16) |
540 ((unsigned)Ptr->Untyped[3] << 24);
542 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
543 goto Load4BytesLittleEndian;
544 case Type::DoubleTyID:
545 case Type::ULongTyID:
546 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
547 ((uint64_t)Ptr->Untyped[1] << 8) |
548 ((uint64_t)Ptr->Untyped[2] << 16) |
549 ((uint64_t)Ptr->Untyped[3] << 24) |
550 ((uint64_t)Ptr->Untyped[4] << 32) |
551 ((uint64_t)Ptr->Untyped[5] << 40) |
552 ((uint64_t)Ptr->Untyped[6] << 48) |
553 ((uint64_t)Ptr->Untyped[7] << 56);
556 std::cout << "Cannot load value of type " << *Ty << "!\n";
560 switch (Ty->getTypeID()) {
562 case Type::UByteTyID:
563 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
564 case Type::UShortTyID:
565 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
566 ((unsigned)Ptr->Untyped[0] << 8);
569 case Type::FloatTyID:
571 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
572 ((unsigned)Ptr->Untyped[2] << 8) |
573 ((unsigned)Ptr->Untyped[1] << 16) |
574 ((unsigned)Ptr->Untyped[0] << 24);
576 case Type::PointerTyID: if (getTargetData()->getPointerSize() == 4)
577 goto Load4BytesBigEndian;
578 case Type::DoubleTyID:
579 case Type::ULongTyID:
580 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
581 ((uint64_t)Ptr->Untyped[6] << 8) |
582 ((uint64_t)Ptr->Untyped[5] << 16) |
583 ((uint64_t)Ptr->Untyped[4] << 24) |
584 ((uint64_t)Ptr->Untyped[3] << 32) |
585 ((uint64_t)Ptr->Untyped[2] << 40) |
586 ((uint64_t)Ptr->Untyped[1] << 48) |
587 ((uint64_t)Ptr->Untyped[0] << 56);
590 std::cout << "Cannot load value of type " << *Ty << "!\n";
597 // InitializeMemory - Recursive function to apply a Constant value into the
598 // specified memory location...
600 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
601 if (isa<UndefValue>(Init)) {
603 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
604 unsigned ElementSize =
605 getTargetData()->getTypeSize(CP->getType()->getElementType());
606 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
607 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
609 } else if (Init->getType()->isFirstClassType()) {
610 GenericValue Val = getConstantValue(Init);
611 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
613 } else if (isa<ConstantAggregateZero>(Init)) {
614 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
618 switch (Init->getType()->getTypeID()) {
619 case Type::ArrayTyID: {
620 const ConstantArray *CPA = cast<ConstantArray>(Init);
621 unsigned ElementSize =
622 getTargetData()->getTypeSize(CPA->getType()->getElementType());
623 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
624 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
628 case Type::StructTyID: {
629 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
630 const StructLayout *SL =
631 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
632 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
633 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
638 std::cerr << "Bad Type: " << *Init->getType() << "\n";
639 assert(0 && "Unknown constant type to initialize memory with!");
643 /// EmitGlobals - Emit all of the global variables to memory, storing their
644 /// addresses into GlobalAddress. This must make sure to copy the contents of
645 /// their initializers into the memory.
647 void ExecutionEngine::emitGlobals() {
648 const TargetData *TD = getTargetData();
650 // Loop over all of the global variables in the program, allocating the memory
651 // to hold them. If there is more than one module, do a prepass over globals
652 // to figure out how the different modules should link together.
654 std::map<std::pair<std::string, const Type*>,
655 const GlobalValue*> LinkedGlobalsMap;
657 if (Modules.size() != 1) {
658 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
659 Module &M = *Modules[m]->getModule();
660 for (Module::const_global_iterator I = M.global_begin(),
661 E = M.global_end(); I != E; ++I) {
662 const GlobalValue *GV = I;
663 if (GV->hasInternalLinkage() || GV->isExternal() ||
664 GV->hasAppendingLinkage() || !GV->hasName())
665 continue;// Ignore external globals and globals with internal linkage.
667 const GlobalValue *&GVEntry =
668 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
670 // If this is the first time we've seen this global, it is the canonical
677 // If the existing global is strong, never replace it.
678 if (GVEntry->hasExternalLinkage() ||
679 GVEntry->hasDLLImportLinkage() ||
680 GVEntry->hasDLLExportLinkage())
683 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
685 if (GV->hasExternalLinkage())
691 std::vector<const GlobalValue*> NonCanonicalGlobals;
692 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
693 Module &M = *Modules[m]->getModule();
694 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
696 // In the multi-module case, see what this global maps to.
697 if (!LinkedGlobalsMap.empty()) {
698 if (const GlobalValue *GVEntry =
699 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
700 // If something else is the canonical global, ignore this one.
701 if (GVEntry != &*I) {
702 NonCanonicalGlobals.push_back(I);
708 if (!I->isExternal()) {
709 // Get the type of the global.
710 const Type *Ty = I->getType()->getElementType();
712 // Allocate some memory for it!
713 unsigned Size = TD->getTypeSize(Ty);
714 addGlobalMapping(I, new char[Size]);
716 // External variable reference. Try to use the dynamic loader to
717 // get a pointer to it.
719 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
720 addGlobalMapping(I, SymAddr);
722 std::cerr << "Could not resolve external global address: "
723 << I->getName() << "\n";
729 // If there are multiple modules, map the non-canonical globals to their
730 // canonical location.
731 if (!NonCanonicalGlobals.empty()) {
732 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
733 const GlobalValue *GV = NonCanonicalGlobals[i];
734 const GlobalValue *CGV =
735 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
736 void *Ptr = getPointerToGlobalIfAvailable(CGV);
737 assert(Ptr && "Canonical global wasn't codegen'd!");
738 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
742 // Now that all of the globals are set up in memory, loop through them all and
743 // initialize their contents.
744 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
746 if (!I->isExternal()) {
747 if (!LinkedGlobalsMap.empty()) {
748 if (const GlobalValue *GVEntry =
749 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
750 if (GVEntry != &*I) // Not the canonical variable.
753 EmitGlobalVariable(I);
759 // EmitGlobalVariable - This method emits the specified global variable to the
760 // address specified in GlobalAddresses, or allocates new memory if it's not
761 // already in the map.
762 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
763 void *GA = getPointerToGlobalIfAvailable(GV);
764 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
766 const Type *ElTy = GV->getType()->getElementType();
767 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
769 // If it's not already specified, allocate memory for the global.
770 GA = new char[GVSize];
771 addGlobalMapping(GV, GA);
774 InitializeMemory(GV->getInitializer(), GA);
775 NumInitBytes += (unsigned)GVSize;