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