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