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/System/Host.h"
27 #include "llvm/Target/TargetData.h"
31 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
32 STATISTIC(NumGlobals , "Number of global vars initialized");
34 ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
35 ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
37 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
38 LazyCompilationDisabled = false;
40 assert(P && "ModuleProvider is null?");
43 ExecutionEngine::~ExecutionEngine() {
44 clearAllGlobalMappings();
45 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
49 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
50 /// Release module from ModuleProvider.
51 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
52 std::string *ErrInfo) {
53 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
54 E = Modules.end(); I != E; ++I) {
55 ModuleProvider *MP = *I;
58 return MP->releaseModule(ErrInfo);
64 /// FindFunctionNamed - Search all of the active modules to find the one that
65 /// defines FnName. This is very slow operation and shouldn't be used for
67 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
68 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
69 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
76 /// addGlobalMapping - Tell the execution engine that the specified global is
77 /// at the specified location. This is used internally as functions are JIT'd
78 /// and as global variables are laid out in memory. It can and should also be
79 /// used by clients of the EE that want to have an LLVM global overlay
80 /// existing data in memory.
81 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
82 MutexGuard locked(lock);
84 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
85 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
88 // If we are using the reverse mapping, add it too
89 if (!state.getGlobalAddressReverseMap(locked).empty()) {
90 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
91 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
96 /// clearAllGlobalMappings - Clear all global mappings and start over again
97 /// use in dynamic compilation scenarios when you want to move globals
98 void ExecutionEngine::clearAllGlobalMappings() {
99 MutexGuard locked(lock);
101 state.getGlobalAddressMap(locked).clear();
102 state.getGlobalAddressReverseMap(locked).clear();
105 /// updateGlobalMapping - Replace an existing mapping for GV with a new
106 /// address. This updates both maps as required. If "Addr" is null, the
107 /// entry for the global is removed from the mappings.
108 void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
109 MutexGuard locked(lock);
111 // Deleting from the mapping?
113 state.getGlobalAddressMap(locked).erase(GV);
114 if (!state.getGlobalAddressReverseMap(locked).empty())
115 state.getGlobalAddressReverseMap(locked).erase(Addr);
119 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
120 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
121 state.getGlobalAddressReverseMap(locked).erase(CurVal);
124 // If we are using the reverse mapping, add it too
125 if (!state.getGlobalAddressReverseMap(locked).empty()) {
126 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
127 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
132 /// getPointerToGlobalIfAvailable - This returns the address of the specified
133 /// global value if it is has already been codegen'd, otherwise it returns null.
135 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
136 MutexGuard locked(lock);
138 std::map<const GlobalValue*, void*>::iterator I =
139 state.getGlobalAddressMap(locked).find(GV);
140 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
143 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
144 /// at the specified address.
146 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
147 MutexGuard locked(lock);
149 // If we haven't computed the reverse mapping yet, do so first.
150 if (state.getGlobalAddressReverseMap(locked).empty()) {
151 for (std::map<const GlobalValue*, void *>::iterator
152 I = state.getGlobalAddressMap(locked).begin(),
153 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
154 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
158 std::map<void *, const GlobalValue*>::iterator I =
159 state.getGlobalAddressReverseMap(locked).find(Addr);
160 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
163 // CreateArgv - Turn a vector of strings into a nice argv style array of
164 // pointers to null terminated strings.
166 static void *CreateArgv(ExecutionEngine *EE,
167 const std::vector<std::string> &InputArgv) {
168 unsigned PtrSize = EE->getTargetData()->getPointerSize();
169 char *Result = new char[(InputArgv.size()+1)*PtrSize];
171 DOUT << "ARGV = " << (void*)Result << "\n";
172 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
174 for (unsigned i = 0; i != InputArgv.size(); ++i) {
175 unsigned Size = InputArgv[i].size()+1;
176 char *Dest = new char[Size];
177 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
179 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
182 // Endian safe: Result[i] = (PointerTy)Dest;
183 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
188 EE->StoreValueToMemory(PTOGV(0),
189 (GenericValue*)(Result+InputArgv.size()*PtrSize),
195 /// runStaticConstructorsDestructors - This method is used to execute all of
196 /// the static constructors or destructors for a program, depending on the
197 /// value of isDtors.
198 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
199 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
201 // Execute global ctors/dtors for each module in the program.
202 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
203 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
205 // If this global has internal linkage, or if it has a use, then it must be
206 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
207 // this is the case, don't execute any of the global ctors, __main will do
209 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
211 // Should be an array of '{ int, void ()* }' structs. The first value is
212 // the init priority, which we ignore.
213 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
214 if (!InitList) continue;
215 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
216 if (ConstantStruct *CS =
217 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
218 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
220 Constant *FP = CS->getOperand(1);
221 if (FP->isNullValue())
222 break; // Found a null terminator, exit.
224 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
226 FP = CE->getOperand(0);
227 if (Function *F = dyn_cast<Function>(FP)) {
228 // Execute the ctor/dtor function!
229 runFunction(F, std::vector<GenericValue>());
235 /// runFunctionAsMain - This is a helper function which wraps runFunction to
236 /// handle the common task of starting up main with the specified argc, argv,
237 /// and envp parameters.
238 int ExecutionEngine::runFunctionAsMain(Function *Fn,
239 const std::vector<std::string> &argv,
240 const char * const * envp) {
241 std::vector<GenericValue> GVArgs;
243 GVArgc.IntVal = APInt(32, argv.size());
246 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
247 const FunctionType *FTy = Fn->getFunctionType();
248 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
251 if (FTy->getParamType(2) != PPInt8Ty) {
252 cerr << "Invalid type for third argument of main() supplied\n";
257 if (FTy->getParamType(1) != PPInt8Ty) {
258 cerr << "Invalid type for second argument of main() supplied\n";
263 if (FTy->getParamType(0) != Type::Int32Ty) {
264 cerr << "Invalid type for first argument of main() supplied\n";
269 if (FTy->getReturnType() != Type::Int32Ty &&
270 FTy->getReturnType() != Type::VoidTy) {
271 cerr << "Invalid return type of main() supplied\n";
276 cerr << "Invalid number of arguments of main() supplied\n";
281 GVArgs.push_back(GVArgc); // Arg #0 = argc.
283 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
284 assert(((char **)GVTOP(GVArgs[1]))[0] &&
285 "argv[0] was null after CreateArgv");
287 std::vector<std::string> EnvVars;
288 for (unsigned i = 0; envp[i]; ++i)
289 EnvVars.push_back(envp[i]);
290 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
294 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
297 /// If possible, create a JIT, unless the caller specifically requests an
298 /// Interpreter or there's an error. If even an Interpreter cannot be created,
299 /// NULL is returned.
301 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
302 bool ForceInterpreter,
303 std::string *ErrorStr) {
304 ExecutionEngine *EE = 0;
306 // Unless the interpreter was explicitly selected, try making a JIT.
307 if (!ForceInterpreter && JITCtor)
308 EE = JITCtor(MP, ErrorStr);
310 // If we can't make a JIT, make an interpreter instead.
311 if (EE == 0 && InterpCtor)
312 EE = InterpCtor(MP, ErrorStr);
315 // Make sure we can resolve symbols in the program as well. The zero arg
316 // to the function tells DynamicLibrary to load the program, not a library.
317 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
326 ExecutionEngine *ExecutionEngine::create(Module *M) {
327 return create(new ExistingModuleProvider(M));
330 /// getPointerToGlobal - This returns the address of the specified global
331 /// value. This may involve code generation if it's a function.
333 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
334 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
335 return getPointerToFunction(F);
337 MutexGuard locked(lock);
338 void *p = state.getGlobalAddressMap(locked)[GV];
342 // Global variable might have been added since interpreter started.
343 if (GlobalVariable *GVar =
344 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
345 EmitGlobalVariable(GVar);
347 assert(0 && "Global hasn't had an address allocated yet!");
348 return state.getGlobalAddressMap(locked)[GV];
351 /// This function converts a Constant* into a GenericValue. The interesting
352 /// part is if C is a ConstantExpr.
353 /// @brief Get a GenericValue for a Constant*
354 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
355 // If its undefined, return the garbage.
356 if (isa<UndefValue>(C))
357 return GenericValue();
359 // If the value is a ConstantExpr
360 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
361 Constant *Op0 = CE->getOperand(0);
362 switch (CE->getOpcode()) {
363 case Instruction::GetElementPtr: {
365 GenericValue Result = getConstantValue(Op0);
366 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
368 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
370 char* tmp = (char*) Result.PointerVal;
371 Result = PTOGV(tmp + Offset);
374 case Instruction::Trunc: {
375 GenericValue GV = getConstantValue(Op0);
376 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
377 GV.IntVal = GV.IntVal.trunc(BitWidth);
380 case Instruction::ZExt: {
381 GenericValue GV = getConstantValue(Op0);
382 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
383 GV.IntVal = GV.IntVal.zext(BitWidth);
386 case Instruction::SExt: {
387 GenericValue GV = getConstantValue(Op0);
388 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
389 GV.IntVal = GV.IntVal.sext(BitWidth);
392 case Instruction::FPTrunc: {
394 GenericValue GV = getConstantValue(Op0);
395 GV.FloatVal = float(GV.DoubleVal);
398 case Instruction::FPExt:{
400 GenericValue GV = getConstantValue(Op0);
401 GV.DoubleVal = double(GV.FloatVal);
404 case Instruction::UIToFP: {
405 GenericValue GV = getConstantValue(Op0);
406 if (CE->getType() == Type::FloatTy)
407 GV.FloatVal = float(GV.IntVal.roundToDouble());
408 else if (CE->getType() == Type::DoubleTy)
409 GV.DoubleVal = GV.IntVal.roundToDouble();
410 else if (CE->getType() == Type::X86_FP80Ty) {
411 const uint64_t zero[] = {0, 0};
412 APFloat apf = APFloat(APInt(80, 2, zero));
413 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
414 GV.IntVal.getBitWidth(), false,
415 APFloat::rmNearestTiesToEven);
416 GV.IntVal = apf.convertToAPInt();
420 case Instruction::SIToFP: {
421 GenericValue GV = getConstantValue(Op0);
422 if (CE->getType() == Type::FloatTy)
423 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
424 else if (CE->getType() == Type::DoubleTy)
425 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
426 else if (CE->getType() == Type::X86_FP80Ty) {
427 const uint64_t zero[] = { 0, 0};
428 APFloat apf = APFloat(APInt(80, 2, zero));
429 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
430 GV.IntVal.getBitWidth(), true,
431 APFloat::rmNearestTiesToEven);
432 GV.IntVal = apf.convertToAPInt();
436 case Instruction::FPToUI: // double->APInt conversion handles sign
437 case Instruction::FPToSI: {
438 GenericValue GV = getConstantValue(Op0);
439 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
440 if (Op0->getType() == Type::FloatTy)
441 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
442 else if (Op0->getType() == Type::DoubleTy)
443 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
444 else if (Op0->getType() == Type::X86_FP80Ty) {
445 APFloat apf = APFloat(GV.IntVal);
447 (void)apf.convertToInteger(&v, BitWidth,
448 CE->getOpcode()==Instruction::FPToSI,
449 APFloat::rmTowardZero);
450 GV.IntVal = v; // endian?
454 case Instruction::PtrToInt: {
455 GenericValue GV = getConstantValue(Op0);
456 uint32_t PtrWidth = TD->getPointerSizeInBits();
457 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
460 case Instruction::IntToPtr: {
461 GenericValue GV = getConstantValue(Op0);
462 uint32_t PtrWidth = TD->getPointerSizeInBits();
463 if (PtrWidth != GV.IntVal.getBitWidth())
464 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
465 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
466 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
469 case Instruction::BitCast: {
470 GenericValue GV = getConstantValue(Op0);
471 const Type* DestTy = CE->getType();
472 switch (Op0->getType()->getTypeID()) {
473 default: assert(0 && "Invalid bitcast operand");
474 case Type::IntegerTyID:
475 assert(DestTy->isFloatingPoint() && "invalid bitcast");
476 if (DestTy == Type::FloatTy)
477 GV.FloatVal = GV.IntVal.bitsToFloat();
478 else if (DestTy == Type::DoubleTy)
479 GV.DoubleVal = GV.IntVal.bitsToDouble();
481 case Type::FloatTyID:
482 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
483 GV.IntVal.floatToBits(GV.FloatVal);
485 case Type::DoubleTyID:
486 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
487 GV.IntVal.doubleToBits(GV.DoubleVal);
489 case Type::PointerTyID:
490 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
491 break; // getConstantValue(Op0) above already converted it
495 case Instruction::Add:
496 case Instruction::Sub:
497 case Instruction::Mul:
498 case Instruction::UDiv:
499 case Instruction::SDiv:
500 case Instruction::URem:
501 case Instruction::SRem:
502 case Instruction::And:
503 case Instruction::Or:
504 case Instruction::Xor: {
505 GenericValue LHS = getConstantValue(Op0);
506 GenericValue RHS = getConstantValue(CE->getOperand(1));
508 switch (CE->getOperand(0)->getType()->getTypeID()) {
509 default: assert(0 && "Bad add type!"); abort();
510 case Type::IntegerTyID:
511 switch (CE->getOpcode()) {
512 default: assert(0 && "Invalid integer opcode");
513 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
514 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
515 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
516 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
517 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
518 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
519 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
520 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
521 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
522 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
525 case Type::FloatTyID:
526 switch (CE->getOpcode()) {
527 default: assert(0 && "Invalid float opcode"); abort();
528 case Instruction::Add:
529 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
530 case Instruction::Sub:
531 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
532 case Instruction::Mul:
533 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
534 case Instruction::FDiv:
535 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
536 case Instruction::FRem:
537 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
540 case Type::DoubleTyID:
541 switch (CE->getOpcode()) {
542 default: assert(0 && "Invalid double opcode"); abort();
543 case Instruction::Add:
544 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
545 case Instruction::Sub:
546 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
547 case Instruction::Mul:
548 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
549 case Instruction::FDiv:
550 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
551 case Instruction::FRem:
552 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
555 case Type::X86_FP80TyID:
556 case Type::PPC_FP128TyID:
557 case Type::FP128TyID: {
558 APFloat apfLHS = APFloat(LHS.IntVal);
559 switch (CE->getOpcode()) {
560 default: assert(0 && "Invalid long double opcode"); abort();
561 case Instruction::Add:
562 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
563 GV.IntVal = apfLHS.convertToAPInt();
565 case Instruction::Sub:
566 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
567 GV.IntVal = apfLHS.convertToAPInt();
569 case Instruction::Mul:
570 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
571 GV.IntVal = apfLHS.convertToAPInt();
573 case Instruction::FDiv:
574 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
575 GV.IntVal = apfLHS.convertToAPInt();
577 case Instruction::FRem:
578 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
579 GV.IntVal = apfLHS.convertToAPInt();
590 cerr << "ConstantExpr not handled: " << *CE << "\n";
595 switch (C->getType()->getTypeID()) {
596 case Type::FloatTyID:
597 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
599 case Type::DoubleTyID:
600 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
602 case Type::X86_FP80TyID:
603 case Type::FP128TyID:
604 case Type::PPC_FP128TyID:
605 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
607 case Type::IntegerTyID:
608 Result.IntVal = cast<ConstantInt>(C)->getValue();
610 case Type::PointerTyID:
611 if (isa<ConstantPointerNull>(C))
612 Result.PointerVal = 0;
613 else if (const Function *F = dyn_cast<Function>(C))
614 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
615 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
616 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
618 assert(0 && "Unknown constant pointer type!");
621 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
627 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
628 /// is the address of the memory at which to store Val, cast to GenericValue *.
629 /// It is not a pointer to a GenericValue containing the address at which to
632 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
634 switch (Ty->getTypeID()) {
635 case Type::IntegerTyID: {
636 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
637 unsigned StoreBytes = (BitWidth + 7)/8;
638 uint8_t *Src = (uint8_t *)Val.IntVal.getRawData();
639 uint8_t *Dst = (uint8_t *)Ptr;
641 if (sys::littleEndianHost())
642 // Little-endian host - the source is ordered from LSB to MSB.
643 // Order the destination from LSB to MSB: Do a straight copy.
644 memcpy(Dst, Src, StoreBytes);
646 // Big-endian host - the source is an array of 64 bit words ordered from
647 // LSW to MSW. Each word is ordered from MSB to LSB.
648 // Order the destination from MSB to LSB: Reverse the word order, but not
649 // the bytes in a word.
650 while (StoreBytes > sizeof(uint64_t)) {
651 StoreBytes -= sizeof(uint64_t);
652 // May not be aligned so use memcpy.
653 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
654 Src += sizeof(uint64_t);
657 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
661 case Type::FloatTyID:
662 *((float*)Ptr) = Val.FloatVal;
664 case Type::DoubleTyID:
665 *((double*)Ptr) = Val.DoubleVal;
667 case Type::X86_FP80TyID: {
668 uint16_t *Dest = (uint16_t*)Ptr;
669 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
670 // This is endian dependent, but it will only work on x86 anyway.
678 case Type::PointerTyID:
679 *((PointerTy*)Ptr) = Val.PointerVal;
682 cerr << "Cannot store value of type " << *Ty << "!\n";
688 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
691 switch (Ty->getTypeID()) {
692 case Type::IntegerTyID: {
693 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
694 unsigned LoadBytes = (BitWidth + 7)/8;
696 // An APInt with all words initially zero.
697 Result.IntVal = APInt(BitWidth, 0);
699 uint8_t *Src = (uint8_t *)Ptr;
700 uint8_t *Dst = (uint8_t *)Result.IntVal.getRawData();
702 if (sys::littleEndianHost())
703 // Little-endian host - the destination must be ordered from LSB to MSB.
704 // The source is ordered from LSB to MSB: Do a straight copy.
705 memcpy(Dst, Src, LoadBytes);
707 // Big-endian - the destination is an array of 64 bit words ordered from
708 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
709 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
711 while (LoadBytes > sizeof(uint64_t)) {
712 LoadBytes -= sizeof(uint64_t);
713 // May not be aligned so use memcpy.
714 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
715 Dst += sizeof(uint64_t);
718 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
722 case Type::FloatTyID:
723 Result.FloatVal = *((float*)Ptr);
725 case Type::DoubleTyID:
726 Result.DoubleVal = *((double*)Ptr);
728 case Type::PointerTyID:
729 Result.PointerVal = *((PointerTy*)Ptr);
731 case Type::X86_FP80TyID: {
732 // This is endian dependent, but it will only work on x86 anyway.
733 uint16_t *p = (uint16_t*)Ptr;
743 Result.IntVal = APInt(80, 2, y);
747 cerr << "Cannot load value of type " << *Ty << "!\n";
752 // InitializeMemory - Recursive function to apply a Constant value into the
753 // specified memory location...
755 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
756 if (isa<UndefValue>(Init)) {
758 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
759 unsigned ElementSize =
760 getTargetData()->getABITypeSize(CP->getType()->getElementType());
761 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
762 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
764 } else if (Init->getType()->isFirstClassType()) {
765 GenericValue Val = getConstantValue(Init);
766 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
768 } else if (isa<ConstantAggregateZero>(Init)) {
769 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
773 switch (Init->getType()->getTypeID()) {
774 case Type::ArrayTyID: {
775 const ConstantArray *CPA = cast<ConstantArray>(Init);
776 unsigned ElementSize =
777 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
778 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
779 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
783 case Type::StructTyID: {
784 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
785 const StructLayout *SL =
786 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
787 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
788 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
793 cerr << "Bad Type: " << *Init->getType() << "\n";
794 assert(0 && "Unknown constant type to initialize memory with!");
798 /// EmitGlobals - Emit all of the global variables to memory, storing their
799 /// addresses into GlobalAddress. This must make sure to copy the contents of
800 /// their initializers into the memory.
802 void ExecutionEngine::emitGlobals() {
803 const TargetData *TD = getTargetData();
805 // Loop over all of the global variables in the program, allocating the memory
806 // to hold them. If there is more than one module, do a prepass over globals
807 // to figure out how the different modules should link together.
809 std::map<std::pair<std::string, const Type*>,
810 const GlobalValue*> LinkedGlobalsMap;
812 if (Modules.size() != 1) {
813 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
814 Module &M = *Modules[m]->getModule();
815 for (Module::const_global_iterator I = M.global_begin(),
816 E = M.global_end(); I != E; ++I) {
817 const GlobalValue *GV = I;
818 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
819 GV->hasAppendingLinkage() || !GV->hasName())
820 continue;// Ignore external globals and globals with internal linkage.
822 const GlobalValue *&GVEntry =
823 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
825 // If this is the first time we've seen this global, it is the canonical
832 // If the existing global is strong, never replace it.
833 if (GVEntry->hasExternalLinkage() ||
834 GVEntry->hasDLLImportLinkage() ||
835 GVEntry->hasDLLExportLinkage())
838 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
840 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
846 std::vector<const GlobalValue*> NonCanonicalGlobals;
847 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
848 Module &M = *Modules[m]->getModule();
849 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
851 // In the multi-module case, see what this global maps to.
852 if (!LinkedGlobalsMap.empty()) {
853 if (const GlobalValue *GVEntry =
854 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
855 // If something else is the canonical global, ignore this one.
856 if (GVEntry != &*I) {
857 NonCanonicalGlobals.push_back(I);
863 if (!I->isDeclaration()) {
864 // Get the type of the global.
865 const Type *Ty = I->getType()->getElementType();
867 // Allocate some memory for it!
868 unsigned Size = TD->getABITypeSize(Ty);
869 addGlobalMapping(I, new char[Size]);
871 // External variable reference. Try to use the dynamic loader to
872 // get a pointer to it.
874 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
875 addGlobalMapping(I, SymAddr);
877 cerr << "Could not resolve external global address: "
878 << I->getName() << "\n";
884 // If there are multiple modules, map the non-canonical globals to their
885 // canonical location.
886 if (!NonCanonicalGlobals.empty()) {
887 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
888 const GlobalValue *GV = NonCanonicalGlobals[i];
889 const GlobalValue *CGV =
890 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
891 void *Ptr = getPointerToGlobalIfAvailable(CGV);
892 assert(Ptr && "Canonical global wasn't codegen'd!");
893 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
897 // Now that all of the globals are set up in memory, loop through them all
898 // and initialize their contents.
899 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
901 if (!I->isDeclaration()) {
902 if (!LinkedGlobalsMap.empty()) {
903 if (const GlobalValue *GVEntry =
904 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
905 if (GVEntry != &*I) // Not the canonical variable.
908 EmitGlobalVariable(I);
914 // EmitGlobalVariable - This method emits the specified global variable to the
915 // address specified in GlobalAddresses, or allocates new memory if it's not
916 // already in the map.
917 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
918 void *GA = getPointerToGlobalIfAvailable(GV);
919 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
921 const Type *ElTy = GV->getType()->getElementType();
922 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
924 // If it's not already specified, allocate memory for the global.
925 GA = new char[GVSize];
926 addGlobalMapping(GV, GA);
929 InitializeMemory(GV->getInitializer(), GA);
930 NumInitBytes += (unsigned)GVSize;