LLVM API Documentation

ExecutionEngine.cpp
Go to the documentation of this file.
00001 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the common interface used by the various execution engine
00011 // subclasses.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/ExecutionEngine/GenericValue.h"
00019 #include "llvm/ExecutionEngine/ObjectBuffer.h"
00020 #include "llvm/ExecutionEngine/ObjectCache.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/Module.h"
00025 #include "llvm/IR/Operator.h"
00026 #include "llvm/IR/ValueHandle.h"
00027 #include "llvm/Object/Archive.h"
00028 #include "llvm/Object/ObjectFile.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/DynamicLibrary.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/Host.h"
00033 #include "llvm/Support/MutexGuard.h"
00034 #include "llvm/Support/TargetRegistry.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include <cmath>
00038 #include <cstring>
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "jit"
00042 
00043 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
00044 STATISTIC(NumGlobals  , "Number of global vars initialized");
00045 
00046 // Pin the vtable to this file.
00047 void ObjectCache::anchor() {}
00048 void ObjectBuffer::anchor() {}
00049 void ObjectBufferStream::anchor() {}
00050 
00051 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
00052     std::unique_ptr<Module> M, std::string *ErrorStr,
00053     RTDyldMemoryManager *MCJMM, std::unique_ptr<TargetMachine> TM) = nullptr;
00054 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
00055                                                 std::string *ErrorStr) =nullptr;
00056 
00057 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
00058   : EEState(*this),
00059     LazyFunctionCreator(nullptr) {
00060   CompilingLazily         = false;
00061   GVCompilationDisabled   = false;
00062   SymbolSearchingDisabled = false;
00063 
00064   // IR module verification is enabled by default in debug builds, and disabled
00065   // by default in release builds.
00066 #ifndef NDEBUG
00067   VerifyModules = true;
00068 #else
00069   VerifyModules = false;
00070 #endif
00071 
00072   assert(M && "Module is null?");
00073   Modules.push_back(std::move(M));
00074 }
00075 
00076 ExecutionEngine::~ExecutionEngine() {
00077   clearAllGlobalMappings();
00078 }
00079 
00080 namespace {
00081 /// \brief Helper class which uses a value handler to automatically deletes the
00082 /// memory block when the GlobalVariable is destroyed.
00083 class GVMemoryBlock : public CallbackVH {
00084   GVMemoryBlock(const GlobalVariable *GV)
00085     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
00086 
00087 public:
00088   /// \brief Returns the address the GlobalVariable should be written into.  The
00089   /// GVMemoryBlock object prefixes that.
00090   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
00091     Type *ElTy = GV->getType()->getElementType();
00092     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
00093     void *RawMemory = ::operator new(
00094       RoundUpToAlignment(sizeof(GVMemoryBlock),
00095                          TD.getPreferredAlignment(GV))
00096       + GVSize);
00097     new(RawMemory) GVMemoryBlock(GV);
00098     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
00099   }
00100 
00101   void deleted() override {
00102     // We allocated with operator new and with some extra memory hanging off the
00103     // end, so don't just delete this.  I'm not sure if this is actually
00104     // required.
00105     this->~GVMemoryBlock();
00106     ::operator delete(this);
00107   }
00108 };
00109 }  // anonymous namespace
00110 
00111 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
00112   return GVMemoryBlock::Create(GV, *getDataLayout());
00113 }
00114 
00115 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
00116   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
00117 }
00118 
00119 void
00120 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
00121   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
00122 }
00123 
00124 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
00125   llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
00126 }
00127 
00128 bool ExecutionEngine::removeModule(Module *M) {
00129   for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
00130     Module *Found = I->get();
00131     if (Found == M) {
00132       I->release();
00133       Modules.erase(I);
00134       clearGlobalMappingsFromModule(M);
00135       return true;
00136     }
00137   }
00138   return false;
00139 }
00140 
00141 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
00142   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
00143     if (Function *F = Modules[i]->getFunction(FnName))
00144       return F;
00145   }
00146   return nullptr;
00147 }
00148 
00149 
00150 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
00151   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
00152   void *OldVal;
00153 
00154   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
00155   // GlobalAddressMap.
00156   if (I == GlobalAddressMap.end())
00157     OldVal = nullptr;
00158   else {
00159     OldVal = I->second;
00160     GlobalAddressMap.erase(I);
00161   }
00162 
00163   GlobalAddressReverseMap.erase(OldVal);
00164   return OldVal;
00165 }
00166 
00167 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
00168   MutexGuard locked(lock);
00169 
00170   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
00171         << "\' to [" << Addr << "]\n";);
00172   void *&CurVal = EEState.getGlobalAddressMap()[GV];
00173   assert((!CurVal || !Addr) && "GlobalMapping already established!");
00174   CurVal = Addr;
00175 
00176   // If we are using the reverse mapping, add it too.
00177   if (!EEState.getGlobalAddressReverseMap().empty()) {
00178     AssertingVH<const GlobalValue> &V =
00179       EEState.getGlobalAddressReverseMap()[Addr];
00180     assert((!V || !GV) && "GlobalMapping already established!");
00181     V = GV;
00182   }
00183 }
00184 
00185 void ExecutionEngine::clearAllGlobalMappings() {
00186   MutexGuard locked(lock);
00187 
00188   EEState.getGlobalAddressMap().clear();
00189   EEState.getGlobalAddressReverseMap().clear();
00190 }
00191 
00192 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
00193   MutexGuard locked(lock);
00194 
00195   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
00196     EEState.RemoveMapping(FI);
00197   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
00198        GI != GE; ++GI)
00199     EEState.RemoveMapping(GI);
00200 }
00201 
00202 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
00203   MutexGuard locked(lock);
00204 
00205   ExecutionEngineState::GlobalAddressMapTy &Map =
00206     EEState.getGlobalAddressMap();
00207 
00208   // Deleting from the mapping?
00209   if (!Addr)
00210     return EEState.RemoveMapping(GV);
00211 
00212   void *&CurVal = Map[GV];
00213   void *OldVal = CurVal;
00214 
00215   if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
00216     EEState.getGlobalAddressReverseMap().erase(CurVal);
00217   CurVal = Addr;
00218 
00219   // If we are using the reverse mapping, add it too.
00220   if (!EEState.getGlobalAddressReverseMap().empty()) {
00221     AssertingVH<const GlobalValue> &V =
00222       EEState.getGlobalAddressReverseMap()[Addr];
00223     assert((!V || !GV) && "GlobalMapping already established!");
00224     V = GV;
00225   }
00226   return OldVal;
00227 }
00228 
00229 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
00230   MutexGuard locked(lock);
00231 
00232   ExecutionEngineState::GlobalAddressMapTy::iterator I =
00233     EEState.getGlobalAddressMap().find(GV);
00234   return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
00235 }
00236 
00237 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
00238   MutexGuard locked(lock);
00239 
00240   // If we haven't computed the reverse mapping yet, do so first.
00241   if (EEState.getGlobalAddressReverseMap().empty()) {
00242     for (ExecutionEngineState::GlobalAddressMapTy::iterator
00243          I = EEState.getGlobalAddressMap().begin(),
00244          E = EEState.getGlobalAddressMap().end(); I != E; ++I)
00245       EEState.getGlobalAddressReverseMap().insert(std::make_pair(
00246                                                           I->second, I->first));
00247   }
00248 
00249   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
00250     EEState.getGlobalAddressReverseMap().find(Addr);
00251   return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
00252 }
00253 
00254 namespace {
00255 class ArgvArray {
00256   std::unique_ptr<char[]> Array;
00257   std::vector<std::unique_ptr<char[]>> Values;
00258 public:
00259   /// Turn a vector of strings into a nice argv style array of pointers to null
00260   /// terminated strings.
00261   void *reset(LLVMContext &C, ExecutionEngine *EE,
00262               const std::vector<std::string> &InputArgv);
00263 };
00264 }  // anonymous namespace
00265 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
00266                        const std::vector<std::string> &InputArgv) {
00267   Values.clear();  // Free the old contents.
00268   Values.reserve(InputArgv.size());
00269   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
00270   Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
00271 
00272   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
00273   Type *SBytePtr = Type::getInt8PtrTy(C);
00274 
00275   for (unsigned i = 0; i != InputArgv.size(); ++i) {
00276     unsigned Size = InputArgv[i].size()+1;
00277     auto Dest = make_unique<char[]>(Size);
00278     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
00279 
00280     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
00281     Dest[Size-1] = 0;
00282 
00283     // Endian safe: Array[i] = (PointerTy)Dest;
00284     EE->StoreValueToMemory(PTOGV(Dest.get()),
00285                            (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
00286     Values.push_back(std::move(Dest));
00287   }
00288 
00289   // Null terminate it
00290   EE->StoreValueToMemory(PTOGV(nullptr),
00291                          (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
00292                          SBytePtr);
00293   return Array.get();
00294 }
00295 
00296 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
00297                                                        bool isDtors) {
00298   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
00299   GlobalVariable *GV = module.getNamedGlobal(Name);
00300 
00301   // If this global has internal linkage, or if it has a use, then it must be
00302   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
00303   // this is the case, don't execute any of the global ctors, __main will do
00304   // it.
00305   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
00306 
00307   // Should be an array of '{ i32, void ()* }' structs.  The first value is
00308   // the init priority, which we ignore.
00309   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
00310   if (!InitList)
00311     return;
00312   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
00313     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
00314     if (!CS) continue;
00315 
00316     Constant *FP = CS->getOperand(1);
00317     if (FP->isNullValue())
00318       continue;  // Found a sentinal value, ignore.
00319 
00320     // Strip off constant expression casts.
00321     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
00322       if (CE->isCast())
00323         FP = CE->getOperand(0);
00324 
00325     // Execute the ctor/dtor function!
00326     if (Function *F = dyn_cast<Function>(FP))
00327       runFunction(F, std::vector<GenericValue>());
00328 
00329     // FIXME: It is marginally lame that we just do nothing here if we see an
00330     // entry we don't recognize. It might not be unreasonable for the verifier
00331     // to not even allow this and just assert here.
00332   }
00333 }
00334 
00335 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
00336   // Execute global ctors/dtors for each module in the program.
00337   for (std::unique_ptr<Module> &M : Modules)
00338     runStaticConstructorsDestructors(*M, isDtors);
00339 }
00340 
00341 #ifndef NDEBUG
00342 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
00343 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
00344   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
00345   for (unsigned i = 0; i < PtrSize; ++i)
00346     if (*(i + (uint8_t*)Loc))
00347       return false;
00348   return true;
00349 }
00350 #endif
00351 
00352 int ExecutionEngine::runFunctionAsMain(Function *Fn,
00353                                        const std::vector<std::string> &argv,
00354                                        const char * const * envp) {
00355   std::vector<GenericValue> GVArgs;
00356   GenericValue GVArgc;
00357   GVArgc.IntVal = APInt(32, argv.size());
00358 
00359   // Check main() type
00360   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
00361   FunctionType *FTy = Fn->getFunctionType();
00362   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
00363 
00364   // Check the argument types.
00365   if (NumArgs > 3)
00366     report_fatal_error("Invalid number of arguments of main() supplied");
00367   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
00368     report_fatal_error("Invalid type for third argument of main() supplied");
00369   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
00370     report_fatal_error("Invalid type for second argument of main() supplied");
00371   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
00372     report_fatal_error("Invalid type for first argument of main() supplied");
00373   if (!FTy->getReturnType()->isIntegerTy() &&
00374       !FTy->getReturnType()->isVoidTy())
00375     report_fatal_error("Invalid return type of main() supplied");
00376 
00377   ArgvArray CArgv;
00378   ArgvArray CEnv;
00379   if (NumArgs) {
00380     GVArgs.push_back(GVArgc); // Arg #0 = argc.
00381     if (NumArgs > 1) {
00382       // Arg #1 = argv.
00383       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
00384       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
00385              "argv[0] was null after CreateArgv");
00386       if (NumArgs > 2) {
00387         std::vector<std::string> EnvVars;
00388         for (unsigned i = 0; envp[i]; ++i)
00389           EnvVars.push_back(envp[i]);
00390         // Arg #2 = envp.
00391         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
00392       }
00393     }
00394   }
00395 
00396   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
00397 }
00398 
00399 void EngineBuilder::InitEngine() {
00400   WhichEngine = EngineKind::Either;
00401   ErrorStr = nullptr;
00402   OptLevel = CodeGenOpt::Default;
00403   MCJMM = nullptr;
00404   Options = TargetOptions();
00405   RelocModel = Reloc::Default;
00406   CMModel = CodeModel::JITDefault;
00407 
00408 // IR module verification is enabled by default in debug builds, and disabled
00409 // by default in release builds.
00410 #ifndef NDEBUG
00411   VerifyModules = true;
00412 #else
00413   VerifyModules = false;
00414 #endif
00415 }
00416 
00417 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
00418   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
00419 
00420   // Make sure we can resolve symbols in the program as well. The zero arg
00421   // to the function tells DynamicLibrary to load the program, not a library.
00422   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
00423     return nullptr;
00424   
00425   // If the user specified a memory manager but didn't specify which engine to
00426   // create, we assume they only want the JIT, and we fail if they only want
00427   // the interpreter.
00428   if (MCJMM) {
00429     if (WhichEngine & EngineKind::JIT)
00430       WhichEngine = EngineKind::JIT;
00431     else {
00432       if (ErrorStr)
00433         *ErrorStr = "Cannot create an interpreter with a memory manager.";
00434       return nullptr;
00435     }
00436   }
00437 
00438   // Unless the interpreter was explicitly selected or the JIT is not linked,
00439   // try making a JIT.
00440   if ((WhichEngine & EngineKind::JIT) && TheTM) {
00441     Triple TT(M->getTargetTriple());
00442     if (!TM->getTarget().hasJIT()) {
00443       errs() << "WARNING: This target JIT is not designed for the host"
00444              << " you are running.  If bad things happen, please choose"
00445              << " a different -march switch.\n";
00446     }
00447 
00448     ExecutionEngine *EE = nullptr;
00449     if (ExecutionEngine::MCJITCtor)
00450       EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, MCJMM,
00451                                       std::move(TheTM));
00452     if (EE) {
00453       EE->setVerifyModules(VerifyModules);
00454       return EE;
00455     }
00456   }
00457 
00458   // If we can't make a JIT and we didn't request one specifically, try making
00459   // an interpreter instead.
00460   if (WhichEngine & EngineKind::Interpreter) {
00461     if (ExecutionEngine::InterpCtor)
00462       return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
00463     if (ErrorStr)
00464       *ErrorStr = "Interpreter has not been linked in.";
00465     return nullptr;
00466   }
00467 
00468   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
00469     if (ErrorStr)
00470       *ErrorStr = "JIT has not been linked in.";
00471   }
00472 
00473   return nullptr;
00474 }
00475 
00476 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
00477   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
00478     return getPointerToFunction(F);
00479 
00480   MutexGuard locked(lock);
00481   if (void *P = EEState.getGlobalAddressMap()[GV])
00482     return P;
00483 
00484   // Global variable might have been added since interpreter started.
00485   if (GlobalVariable *GVar =
00486           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
00487     EmitGlobalVariable(GVar);
00488   else
00489     llvm_unreachable("Global hasn't had an address allocated yet!");
00490 
00491   return EEState.getGlobalAddressMap()[GV];
00492 }
00493 
00494 /// \brief Converts a Constant* into a GenericValue, including handling of
00495 /// ConstantExpr values.
00496 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
00497   // If its undefined, return the garbage.
00498   if (isa<UndefValue>(C)) {
00499     GenericValue Result;
00500     switch (C->getType()->getTypeID()) {
00501     default:
00502       break;
00503     case Type::IntegerTyID:
00504     case Type::X86_FP80TyID:
00505     case Type::FP128TyID:
00506     case Type::PPC_FP128TyID:
00507       // Although the value is undefined, we still have to construct an APInt
00508       // with the correct bit width.
00509       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
00510       break;
00511     case Type::StructTyID: {
00512       // if the whole struct is 'undef' just reserve memory for the value.
00513       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
00514         unsigned int elemNum = STy->getNumElements();
00515         Result.AggregateVal.resize(elemNum);
00516         for (unsigned int i = 0; i < elemNum; ++i) {
00517           Type *ElemTy = STy->getElementType(i);
00518           if (ElemTy->isIntegerTy())
00519             Result.AggregateVal[i].IntVal = 
00520               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
00521           else if (ElemTy->isAggregateType()) {
00522               const Constant *ElemUndef = UndefValue::get(ElemTy);
00523               Result.AggregateVal[i] = getConstantValue(ElemUndef);
00524             }
00525           }
00526         }
00527       }
00528       break;
00529     case Type::VectorTyID:
00530       // if the whole vector is 'undef' just reserve memory for the value.
00531       const VectorType* VTy = dyn_cast<VectorType>(C->getType());
00532       const Type *ElemTy = VTy->getElementType();
00533       unsigned int elemNum = VTy->getNumElements();
00534       Result.AggregateVal.resize(elemNum);
00535       if (ElemTy->isIntegerTy())
00536         for (unsigned int i = 0; i < elemNum; ++i)
00537           Result.AggregateVal[i].IntVal =
00538             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
00539       break;
00540     }
00541     return Result;
00542   }
00543 
00544   // Otherwise, if the value is a ConstantExpr...
00545   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00546     Constant *Op0 = CE->getOperand(0);
00547     switch (CE->getOpcode()) {
00548     case Instruction::GetElementPtr: {
00549       // Compute the index
00550       GenericValue Result = getConstantValue(Op0);
00551       APInt Offset(DL->getPointerSizeInBits(), 0);
00552       cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
00553 
00554       char* tmp = (char*) Result.PointerVal;
00555       Result = PTOGV(tmp + Offset.getSExtValue());
00556       return Result;
00557     }
00558     case Instruction::Trunc: {
00559       GenericValue GV = getConstantValue(Op0);
00560       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00561       GV.IntVal = GV.IntVal.trunc(BitWidth);
00562       return GV;
00563     }
00564     case Instruction::ZExt: {
00565       GenericValue GV = getConstantValue(Op0);
00566       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00567       GV.IntVal = GV.IntVal.zext(BitWidth);
00568       return GV;
00569     }
00570     case Instruction::SExt: {
00571       GenericValue GV = getConstantValue(Op0);
00572       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00573       GV.IntVal = GV.IntVal.sext(BitWidth);
00574       return GV;
00575     }
00576     case Instruction::FPTrunc: {
00577       // FIXME long double
00578       GenericValue GV = getConstantValue(Op0);
00579       GV.FloatVal = float(GV.DoubleVal);
00580       return GV;
00581     }
00582     case Instruction::FPExt:{
00583       // FIXME long double
00584       GenericValue GV = getConstantValue(Op0);
00585       GV.DoubleVal = double(GV.FloatVal);
00586       return GV;
00587     }
00588     case Instruction::UIToFP: {
00589       GenericValue GV = getConstantValue(Op0);
00590       if (CE->getType()->isFloatTy())
00591         GV.FloatVal = float(GV.IntVal.roundToDouble());
00592       else if (CE->getType()->isDoubleTy())
00593         GV.DoubleVal = GV.IntVal.roundToDouble();
00594       else if (CE->getType()->isX86_FP80Ty()) {
00595         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
00596         (void)apf.convertFromAPInt(GV.IntVal,
00597                                    false,
00598                                    APFloat::rmNearestTiesToEven);
00599         GV.IntVal = apf.bitcastToAPInt();
00600       }
00601       return GV;
00602     }
00603     case Instruction::SIToFP: {
00604       GenericValue GV = getConstantValue(Op0);
00605       if (CE->getType()->isFloatTy())
00606         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
00607       else if (CE->getType()->isDoubleTy())
00608         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
00609       else if (CE->getType()->isX86_FP80Ty()) {
00610         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
00611         (void)apf.convertFromAPInt(GV.IntVal,
00612                                    true,
00613                                    APFloat::rmNearestTiesToEven);
00614         GV.IntVal = apf.bitcastToAPInt();
00615       }
00616       return GV;
00617     }
00618     case Instruction::FPToUI: // double->APInt conversion handles sign
00619     case Instruction::FPToSI: {
00620       GenericValue GV = getConstantValue(Op0);
00621       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00622       if (Op0->getType()->isFloatTy())
00623         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
00624       else if (Op0->getType()->isDoubleTy())
00625         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
00626       else if (Op0->getType()->isX86_FP80Ty()) {
00627         APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
00628         uint64_t v;
00629         bool ignored;
00630         (void)apf.convertToInteger(&v, BitWidth,
00631                                    CE->getOpcode()==Instruction::FPToSI,
00632                                    APFloat::rmTowardZero, &ignored);
00633         GV.IntVal = v; // endian?
00634       }
00635       return GV;
00636     }
00637     case Instruction::PtrToInt: {
00638       GenericValue GV = getConstantValue(Op0);
00639       uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
00640       assert(PtrWidth <= 64 && "Bad pointer width");
00641       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
00642       uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
00643       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
00644       return GV;
00645     }
00646     case Instruction::IntToPtr: {
00647       GenericValue GV = getConstantValue(Op0);
00648       uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
00649       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
00650       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
00651       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
00652       return GV;
00653     }
00654     case Instruction::BitCast: {
00655       GenericValue GV = getConstantValue(Op0);
00656       Type* DestTy = CE->getType();
00657       switch (Op0->getType()->getTypeID()) {
00658         default: llvm_unreachable("Invalid bitcast operand");
00659         case Type::IntegerTyID:
00660           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
00661           if (DestTy->isFloatTy())
00662             GV.FloatVal = GV.IntVal.bitsToFloat();
00663           else if (DestTy->isDoubleTy())
00664             GV.DoubleVal = GV.IntVal.bitsToDouble();
00665           break;
00666         case Type::FloatTyID:
00667           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
00668           GV.IntVal = APInt::floatToBits(GV.FloatVal);
00669           break;
00670         case Type::DoubleTyID:
00671           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
00672           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
00673           break;
00674         case Type::PointerTyID:
00675           assert(DestTy->isPointerTy() && "Invalid bitcast");
00676           break; // getConstantValue(Op0)  above already converted it
00677       }
00678       return GV;
00679     }
00680     case Instruction::Add:
00681     case Instruction::FAdd:
00682     case Instruction::Sub:
00683     case Instruction::FSub:
00684     case Instruction::Mul:
00685     case Instruction::FMul:
00686     case Instruction::UDiv:
00687     case Instruction::SDiv:
00688     case Instruction::URem:
00689     case Instruction::SRem:
00690     case Instruction::And:
00691     case Instruction::Or:
00692     case Instruction::Xor: {
00693       GenericValue LHS = getConstantValue(Op0);
00694       GenericValue RHS = getConstantValue(CE->getOperand(1));
00695       GenericValue GV;
00696       switch (CE->getOperand(0)->getType()->getTypeID()) {
00697       default: llvm_unreachable("Bad add type!");
00698       case Type::IntegerTyID:
00699         switch (CE->getOpcode()) {
00700           default: llvm_unreachable("Invalid integer opcode");
00701           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
00702           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
00703           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
00704           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
00705           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
00706           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
00707           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
00708           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
00709           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
00710           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
00711         }
00712         break;
00713       case Type::FloatTyID:
00714         switch (CE->getOpcode()) {
00715           default: llvm_unreachable("Invalid float opcode");
00716           case Instruction::FAdd:
00717             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
00718           case Instruction::FSub:
00719             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
00720           case Instruction::FMul:
00721             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
00722           case Instruction::FDiv:
00723             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
00724           case Instruction::FRem:
00725             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
00726         }
00727         break;
00728       case Type::DoubleTyID:
00729         switch (CE->getOpcode()) {
00730           default: llvm_unreachable("Invalid double opcode");
00731           case Instruction::FAdd:
00732             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
00733           case Instruction::FSub:
00734             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
00735           case Instruction::FMul:
00736             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
00737           case Instruction::FDiv:
00738             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
00739           case Instruction::FRem:
00740             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
00741         }
00742         break;
00743       case Type::X86_FP80TyID:
00744       case Type::PPC_FP128TyID:
00745       case Type::FP128TyID: {
00746         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
00747         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
00748         switch (CE->getOpcode()) {
00749           default: llvm_unreachable("Invalid long double opcode");
00750           case Instruction::FAdd:
00751             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
00752             GV.IntVal = apfLHS.bitcastToAPInt();
00753             break;
00754           case Instruction::FSub:
00755             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
00756                             APFloat::rmNearestTiesToEven);
00757             GV.IntVal = apfLHS.bitcastToAPInt();
00758             break;
00759           case Instruction::FMul:
00760             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
00761                             APFloat::rmNearestTiesToEven);
00762             GV.IntVal = apfLHS.bitcastToAPInt();
00763             break;
00764           case Instruction::FDiv:
00765             apfLHS.divide(APFloat(Sem, RHS.IntVal),
00766                           APFloat::rmNearestTiesToEven);
00767             GV.IntVal = apfLHS.bitcastToAPInt();
00768             break;
00769           case Instruction::FRem:
00770             apfLHS.mod(APFloat(Sem, RHS.IntVal),
00771                        APFloat::rmNearestTiesToEven);
00772             GV.IntVal = apfLHS.bitcastToAPInt();
00773             break;
00774           }
00775         }
00776         break;
00777       }
00778       return GV;
00779     }
00780     default:
00781       break;
00782     }
00783 
00784     SmallString<256> Msg;
00785     raw_svector_ostream OS(Msg);
00786     OS << "ConstantExpr not handled: " << *CE;
00787     report_fatal_error(OS.str());
00788   }
00789 
00790   // Otherwise, we have a simple constant.
00791   GenericValue Result;
00792   switch (C->getType()->getTypeID()) {
00793   case Type::FloatTyID:
00794     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
00795     break;
00796   case Type::DoubleTyID:
00797     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
00798     break;
00799   case Type::X86_FP80TyID:
00800   case Type::FP128TyID:
00801   case Type::PPC_FP128TyID:
00802     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
00803     break;
00804   case Type::IntegerTyID:
00805     Result.IntVal = cast<ConstantInt>(C)->getValue();
00806     break;
00807   case Type::PointerTyID:
00808     if (isa<ConstantPointerNull>(C))
00809       Result.PointerVal = nullptr;
00810     else if (const Function *F = dyn_cast<Function>(C))
00811       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
00812     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00813       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
00814     else
00815       llvm_unreachable("Unknown constant pointer type!");
00816     break;
00817   case Type::VectorTyID: {
00818     unsigned elemNum;
00819     Type* ElemTy;
00820     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
00821     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
00822     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
00823 
00824     if (CDV) {
00825         elemNum = CDV->getNumElements();
00826         ElemTy = CDV->getElementType();
00827     } else if (CV || CAZ) {
00828         VectorType* VTy = dyn_cast<VectorType>(C->getType());
00829         elemNum = VTy->getNumElements();
00830         ElemTy = VTy->getElementType();
00831     } else {
00832         llvm_unreachable("Unknown constant vector type!");
00833     }
00834 
00835     Result.AggregateVal.resize(elemNum);
00836     // Check if vector holds floats.
00837     if(ElemTy->isFloatTy()) {
00838       if (CAZ) {
00839         GenericValue floatZero;
00840         floatZero.FloatVal = 0.f;
00841         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00842                   floatZero);
00843         break;
00844       }
00845       if(CV) {
00846         for (unsigned i = 0; i < elemNum; ++i)
00847           if (!isa<UndefValue>(CV->getOperand(i)))
00848             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
00849               CV->getOperand(i))->getValueAPF().convertToFloat();
00850         break;
00851       }
00852       if(CDV)
00853         for (unsigned i = 0; i < elemNum; ++i)
00854           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
00855 
00856       break;
00857     }
00858     // Check if vector holds doubles.
00859     if (ElemTy->isDoubleTy()) {
00860       if (CAZ) {
00861         GenericValue doubleZero;
00862         doubleZero.DoubleVal = 0.0;
00863         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00864                   doubleZero);
00865         break;
00866       }
00867       if(CV) {
00868         for (unsigned i = 0; i < elemNum; ++i)
00869           if (!isa<UndefValue>(CV->getOperand(i)))
00870             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
00871               CV->getOperand(i))->getValueAPF().convertToDouble();
00872         break;
00873       }
00874       if(CDV)
00875         for (unsigned i = 0; i < elemNum; ++i)
00876           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
00877 
00878       break;
00879     }
00880     // Check if vector holds integers.
00881     if (ElemTy->isIntegerTy()) {
00882       if (CAZ) {
00883         GenericValue intZero;     
00884         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
00885         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00886                   intZero);
00887         break;
00888       }
00889       if(CV) {
00890         for (unsigned i = 0; i < elemNum; ++i)
00891           if (!isa<UndefValue>(CV->getOperand(i)))
00892             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
00893                                             CV->getOperand(i))->getValue();
00894           else {
00895             Result.AggregateVal[i].IntVal =
00896               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
00897           }
00898         break;
00899       }
00900       if(CDV)
00901         for (unsigned i = 0; i < elemNum; ++i)
00902           Result.AggregateVal[i].IntVal = APInt(
00903             CDV->getElementType()->getPrimitiveSizeInBits(),
00904             CDV->getElementAsInteger(i));
00905 
00906       break;
00907     }
00908     llvm_unreachable("Unknown constant pointer type!");
00909   }
00910   break;
00911 
00912   default:
00913     SmallString<256> Msg;
00914     raw_svector_ostream OS(Msg);
00915     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
00916     report_fatal_error(OS.str());
00917   }
00918 
00919   return Result;
00920 }
00921 
00922 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
00923 /// with the integer held in IntVal.
00924 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
00925                              unsigned StoreBytes) {
00926   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
00927   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
00928 
00929   if (sys::IsLittleEndianHost) {
00930     // Little-endian host - the source is ordered from LSB to MSB.  Order the
00931     // destination from LSB to MSB: Do a straight copy.
00932     memcpy(Dst, Src, StoreBytes);
00933   } else {
00934     // Big-endian host - the source is an array of 64 bit words ordered from
00935     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
00936     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
00937     while (StoreBytes > sizeof(uint64_t)) {
00938       StoreBytes -= sizeof(uint64_t);
00939       // May not be aligned so use memcpy.
00940       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
00941       Src += sizeof(uint64_t);
00942     }
00943 
00944     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
00945   }
00946 }
00947 
00948 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
00949                                          GenericValue *Ptr, Type *Ty) {
00950   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
00951 
00952   switch (Ty->getTypeID()) {
00953   default:
00954     dbgs() << "Cannot store value of type " << *Ty << "!\n";
00955     break;
00956   case Type::IntegerTyID:
00957     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
00958     break;
00959   case Type::FloatTyID:
00960     *((float*)Ptr) = Val.FloatVal;
00961     break;
00962   case Type::DoubleTyID:
00963     *((double*)Ptr) = Val.DoubleVal;
00964     break;
00965   case Type::X86_FP80TyID:
00966     memcpy(Ptr, Val.IntVal.getRawData(), 10);
00967     break;
00968   case Type::PointerTyID:
00969     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
00970     if (StoreBytes != sizeof(PointerTy))
00971       memset(&(Ptr->PointerVal), 0, StoreBytes);
00972 
00973     *((PointerTy*)Ptr) = Val.PointerVal;
00974     break;
00975   case Type::VectorTyID:
00976     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
00977       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
00978         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
00979       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
00980         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
00981       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
00982         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
00983         StoreIntToMemory(Val.AggregateVal[i].IntVal, 
00984           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
00985       }
00986     }
00987     break;
00988   }
00989 
00990   if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
00991     // Host and target are different endian - reverse the stored bytes.
00992     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
00993 }
00994 
00995 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
00996 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
00997 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
00998   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
00999   uint8_t *Dst = reinterpret_cast<uint8_t *>(
01000                    const_cast<uint64_t *>(IntVal.getRawData()));
01001 
01002   if (sys::IsLittleEndianHost)
01003     // Little-endian host - the destination must be ordered from LSB to MSB.
01004     // The source is ordered from LSB to MSB: Do a straight copy.
01005     memcpy(Dst, Src, LoadBytes);
01006   else {
01007     // Big-endian - the destination is an array of 64 bit words ordered from
01008     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
01009     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
01010     // a word.
01011     while (LoadBytes > sizeof(uint64_t)) {
01012       LoadBytes -= sizeof(uint64_t);
01013       // May not be aligned so use memcpy.
01014       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
01015       Dst += sizeof(uint64_t);
01016     }
01017 
01018     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
01019   }
01020 }
01021 
01022 /// FIXME: document
01023 ///
01024 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
01025                                           GenericValue *Ptr,
01026                                           Type *Ty) {
01027   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
01028 
01029   switch (Ty->getTypeID()) {
01030   case Type::IntegerTyID:
01031     // An APInt with all words initially zero.
01032     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
01033     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
01034     break;
01035   case Type::FloatTyID:
01036     Result.FloatVal = *((float*)Ptr);
01037     break;
01038   case Type::DoubleTyID:
01039     Result.DoubleVal = *((double*)Ptr);
01040     break;
01041   case Type::PointerTyID:
01042     Result.PointerVal = *((PointerTy*)Ptr);
01043     break;
01044   case Type::X86_FP80TyID: {
01045     // This is endian dependent, but it will only work on x86 anyway.
01046     // FIXME: Will not trap if loading a signaling NaN.
01047     uint64_t y[2];
01048     memcpy(y, Ptr, 10);
01049     Result.IntVal = APInt(80, y);
01050     break;
01051   }
01052   case Type::VectorTyID: {
01053     const VectorType *VT = cast<VectorType>(Ty);
01054     const Type *ElemT = VT->getElementType();
01055     const unsigned numElems = VT->getNumElements();
01056     if (ElemT->isFloatTy()) {
01057       Result.AggregateVal.resize(numElems);
01058       for (unsigned i = 0; i < numElems; ++i)
01059         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
01060     }
01061     if (ElemT->isDoubleTy()) {
01062       Result.AggregateVal.resize(numElems);
01063       for (unsigned i = 0; i < numElems; ++i)
01064         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
01065     }
01066     if (ElemT->isIntegerTy()) {
01067       GenericValue intZero;
01068       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
01069       intZero.IntVal = APInt(elemBitWidth, 0);
01070       Result.AggregateVal.resize(numElems, intZero);
01071       for (unsigned i = 0; i < numElems; ++i)
01072         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
01073           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
01074     }
01075   break;
01076   }
01077   default:
01078     SmallString<256> Msg;
01079     raw_svector_ostream OS(Msg);
01080     OS << "Cannot load value of type " << *Ty << "!";
01081     report_fatal_error(OS.str());
01082   }
01083 }
01084 
01085 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
01086   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
01087   DEBUG(Init->dump());
01088   if (isa<UndefValue>(Init))
01089     return;
01090   
01091   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
01092     unsigned ElementSize =
01093       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
01094     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
01095       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
01096     return;
01097   }
01098   
01099   if (isa<ConstantAggregateZero>(Init)) {
01100     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
01101     return;
01102   }
01103   
01104   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
01105     unsigned ElementSize =
01106       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
01107     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
01108       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
01109     return;
01110   }
01111   
01112   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
01113     const StructLayout *SL =
01114       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
01115     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
01116       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
01117     return;
01118   }
01119 
01120   if (const ConstantDataSequential *CDS =
01121                dyn_cast<ConstantDataSequential>(Init)) {
01122     // CDS is already laid out in host memory order.
01123     StringRef Data = CDS->getRawDataValues();
01124     memcpy(Addr, Data.data(), Data.size());
01125     return;
01126   }
01127 
01128   if (Init->getType()->isFirstClassType()) {
01129     GenericValue Val = getConstantValue(Init);
01130     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
01131     return;
01132   }
01133 
01134   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
01135   llvm_unreachable("Unknown constant type to initialize memory with!");
01136 }
01137 
01138 /// EmitGlobals - Emit all of the global variables to memory, storing their
01139 /// addresses into GlobalAddress.  This must make sure to copy the contents of
01140 /// their initializers into the memory.
01141 void ExecutionEngine::emitGlobals() {
01142   // Loop over all of the global variables in the program, allocating the memory
01143   // to hold them.  If there is more than one module, do a prepass over globals
01144   // to figure out how the different modules should link together.
01145   std::map<std::pair<std::string, Type*>,
01146            const GlobalValue*> LinkedGlobalsMap;
01147 
01148   if (Modules.size() != 1) {
01149     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
01150       Module &M = *Modules[m];
01151       for (const auto &GV : M.globals()) {
01152         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
01153             GV.hasAppendingLinkage() || !GV.hasName())
01154           continue;// Ignore external globals and globals with internal linkage.
01155 
01156         const GlobalValue *&GVEntry =
01157           LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
01158 
01159         // If this is the first time we've seen this global, it is the canonical
01160         // version.
01161         if (!GVEntry) {
01162           GVEntry = &GV;
01163           continue;
01164         }
01165 
01166         // If the existing global is strong, never replace it.
01167         if (GVEntry->hasExternalLinkage())
01168           continue;
01169 
01170         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
01171         // symbol.  FIXME is this right for common?
01172         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
01173           GVEntry = &GV;
01174       }
01175     }
01176   }
01177 
01178   std::vector<const GlobalValue*> NonCanonicalGlobals;
01179   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
01180     Module &M = *Modules[m];
01181     for (const auto &GV : M.globals()) {
01182       // In the multi-module case, see what this global maps to.
01183       if (!LinkedGlobalsMap.empty()) {
01184         if (const GlobalValue *GVEntry =
01185               LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
01186           // If something else is the canonical global, ignore this one.
01187           if (GVEntry != &GV) {
01188             NonCanonicalGlobals.push_back(&GV);
01189             continue;
01190           }
01191         }
01192       }
01193 
01194       if (!GV.isDeclaration()) {
01195         addGlobalMapping(&GV, getMemoryForGV(&GV));
01196       } else {
01197         // External variable reference. Try to use the dynamic loader to
01198         // get a pointer to it.
01199         if (void *SymAddr =
01200             sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
01201           addGlobalMapping(&GV, SymAddr);
01202         else {
01203           report_fatal_error("Could not resolve external global address: "
01204                             +GV.getName());
01205         }
01206       }
01207     }
01208 
01209     // If there are multiple modules, map the non-canonical globals to their
01210     // canonical location.
01211     if (!NonCanonicalGlobals.empty()) {
01212       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
01213         const GlobalValue *GV = NonCanonicalGlobals[i];
01214         const GlobalValue *CGV =
01215           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
01216         void *Ptr = getPointerToGlobalIfAvailable(CGV);
01217         assert(Ptr && "Canonical global wasn't codegen'd!");
01218         addGlobalMapping(GV, Ptr);
01219       }
01220     }
01221 
01222     // Now that all of the globals are set up in memory, loop through them all
01223     // and initialize their contents.
01224     for (const auto &GV : M.globals()) {
01225       if (!GV.isDeclaration()) {
01226         if (!LinkedGlobalsMap.empty()) {
01227           if (const GlobalValue *GVEntry =
01228                 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
01229             if (GVEntry != &GV)  // Not the canonical variable.
01230               continue;
01231         }
01232         EmitGlobalVariable(&GV);
01233       }
01234     }
01235   }
01236 }
01237 
01238 // EmitGlobalVariable - This method emits the specified global variable to the
01239 // address specified in GlobalAddresses, or allocates new memory if it's not
01240 // already in the map.
01241 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
01242   void *GA = getPointerToGlobalIfAvailable(GV);
01243 
01244   if (!GA) {
01245     // If it's not already specified, allocate memory for the global.
01246     GA = getMemoryForGV(GV);
01247 
01248     // If we failed to allocate memory for this global, return.
01249     if (!GA) return;
01250 
01251     addGlobalMapping(GV, GA);
01252   }
01253 
01254   // Don't initialize if it's thread local, let the client do it.
01255   if (!GV->isThreadLocal())
01256     InitializeMemory(GV->getInitializer(), GA);
01257 
01258   Type *ElTy = GV->getType()->getElementType();
01259   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
01260   NumInitBytes += (unsigned)GVSize;
01261   ++NumGlobals;
01262 }
01263 
01264 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
01265   : EE(EE), GlobalAddressMap(this) {
01266 }
01267 
01268 sys::Mutex *
01269 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
01270   return &EES->EE.lock;
01271 }
01272 
01273 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
01274                                                       const GlobalValue *Old) {
01275   void *OldVal = EES->GlobalAddressMap.lookup(Old);
01276   EES->GlobalAddressReverseMap.erase(OldVal);
01277 }
01278 
01279 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
01280                                                     const GlobalValue *,
01281                                                     const GlobalValue *) {
01282   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
01283                    " RAUW on a value it has a global mapping for.");
01284 }