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