xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/IndirectionUtils.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
100b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
110b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
12*349cc55cSDimitry Andric #include "llvm/ExecutionEngine/JITLink/x86_64.h"
130b57cec5SDimitry Andric #include "llvm/ExecutionEngine/Orc/OrcABISupport.h"
140b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
15*349cc55cSDimitry Andric #include "llvm/MC/MCDisassembler/MCDisassembler.h"
16*349cc55cSDimitry Andric #include "llvm/MC/MCInstrAnalysis.h"
170b57cec5SDimitry Andric #include "llvm/Support/Format.h"
180b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
190b57cec5SDimitry Andric #include <sstream>
200b57cec5SDimitry Andric 
21*349cc55cSDimitry Andric #define DEBUG_TYPE "orc"
22*349cc55cSDimitry Andric 
230b57cec5SDimitry Andric using namespace llvm;
240b57cec5SDimitry Andric using namespace llvm::orc;
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric namespace {
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
290b57cec5SDimitry Andric public:
300b57cec5SDimitry Andric   using CompileFunction = JITCompileCallbackManager::CompileFunction;
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric   CompileCallbackMaterializationUnit(SymbolStringPtr Name,
33e8d8bef9SDimitry Andric                                      CompileFunction Compile)
340b57cec5SDimitry Andric       : MaterializationUnit(SymbolFlagsMap({{Name, JITSymbolFlags::Exported}}),
35e8d8bef9SDimitry Andric                             nullptr),
360b57cec5SDimitry Andric         Name(std::move(Name)), Compile(std::move(Compile)) {}
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric   StringRef getName() const override { return "<Compile Callbacks>"; }
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric private:
41e8d8bef9SDimitry Andric   void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
420b57cec5SDimitry Andric     SymbolMap Result;
430b57cec5SDimitry Andric     Result[Name] = JITEvaluatedSymbol(Compile(), JITSymbolFlags::Exported);
448bcb0991SDimitry Andric     // No dependencies, so these calls cannot fail.
45e8d8bef9SDimitry Andric     cantFail(R->notifyResolved(Result));
46e8d8bef9SDimitry Andric     cantFail(R->notifyEmitted());
470b57cec5SDimitry Andric   }
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
500b57cec5SDimitry Andric     llvm_unreachable("Discard should never occur on a LMU?");
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric   SymbolStringPtr Name;
540b57cec5SDimitry Andric   CompileFunction Compile;
550b57cec5SDimitry Andric };
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric } // namespace
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric namespace llvm {
600b57cec5SDimitry Andric namespace orc {
610b57cec5SDimitry Andric 
62e8d8bef9SDimitry Andric TrampolinePool::~TrampolinePool() {}
630b57cec5SDimitry Andric void IndirectStubsManager::anchor() {}
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric Expected<JITTargetAddress>
660b57cec5SDimitry Andric JITCompileCallbackManager::getCompileCallback(CompileFunction Compile) {
670b57cec5SDimitry Andric   if (auto TrampolineAddr = TP->getTrampoline()) {
680b57cec5SDimitry Andric     auto CallbackName =
690b57cec5SDimitry Andric         ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric     std::lock_guard<std::mutex> Lock(CCMgrMutex);
720b57cec5SDimitry Andric     AddrToSymbol[*TrampolineAddr] = CallbackName;
73e8d8bef9SDimitry Andric     cantFail(
74e8d8bef9SDimitry Andric         CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
75e8d8bef9SDimitry Andric             std::move(CallbackName), std::move(Compile))));
760b57cec5SDimitry Andric     return *TrampolineAddr;
770b57cec5SDimitry Andric   } else
780b57cec5SDimitry Andric     return TrampolineAddr.takeError();
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric JITTargetAddress JITCompileCallbackManager::executeCompileCallback(
820b57cec5SDimitry Andric     JITTargetAddress TrampolineAddr) {
830b57cec5SDimitry Andric   SymbolStringPtr Name;
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   {
860b57cec5SDimitry Andric     std::unique_lock<std::mutex> Lock(CCMgrMutex);
870b57cec5SDimitry Andric     auto I = AddrToSymbol.find(TrampolineAddr);
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric     // If this address is not associated with a compile callback then report an
900b57cec5SDimitry Andric     // error to the execution session and return ErrorHandlerAddress to the
910b57cec5SDimitry Andric     // callee.
920b57cec5SDimitry Andric     if (I == AddrToSymbol.end()) {
930b57cec5SDimitry Andric       Lock.unlock();
940b57cec5SDimitry Andric       std::string ErrMsg;
950b57cec5SDimitry Andric       {
960b57cec5SDimitry Andric         raw_string_ostream ErrMsgStream(ErrMsg);
970b57cec5SDimitry Andric         ErrMsgStream << "No compile callback for trampoline at "
980b57cec5SDimitry Andric                      << format("0x%016" PRIx64, TrampolineAddr);
990b57cec5SDimitry Andric       }
1000b57cec5SDimitry Andric       ES.reportError(
1010b57cec5SDimitry Andric           make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()));
1020b57cec5SDimitry Andric       return ErrorHandlerAddress;
1030b57cec5SDimitry Andric     } else
1040b57cec5SDimitry Andric       Name = I->second;
1050b57cec5SDimitry Andric   }
1060b57cec5SDimitry Andric 
107480093f4SDimitry Andric   if (auto Sym =
108480093f4SDimitry Andric           ES.lookup(makeJITDylibSearchOrder(
109480093f4SDimitry Andric                         &CallbacksJD, JITDylibLookupFlags::MatchAllSymbols),
110480093f4SDimitry Andric                     Name))
1110b57cec5SDimitry Andric     return Sym->getAddress();
1120b57cec5SDimitry Andric   else {
1130b57cec5SDimitry Andric     llvm::dbgs() << "Didn't find callback.\n";
1140b57cec5SDimitry Andric     // If anything goes wrong materializing Sym then report it to the session
1150b57cec5SDimitry Andric     // and return the ErrorHandlerAddress;
1160b57cec5SDimitry Andric     ES.reportError(Sym.takeError());
1170b57cec5SDimitry Andric     return ErrorHandlerAddress;
1180b57cec5SDimitry Andric   }
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric Expected<std::unique_ptr<JITCompileCallbackManager>>
1220b57cec5SDimitry Andric createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES,
1230b57cec5SDimitry Andric                                   JITTargetAddress ErrorHandlerAddress) {
1240b57cec5SDimitry Andric   switch (T.getArch()) {
1250b57cec5SDimitry Andric   default:
1260b57cec5SDimitry Andric     return make_error<StringError>(
1270b57cec5SDimitry Andric         std::string("No callback manager available for ") + T.str(),
1280b57cec5SDimitry Andric         inconvertibleErrorCode());
1298bcb0991SDimitry Andric   case Triple::aarch64:
1308bcb0991SDimitry Andric   case Triple::aarch64_32: {
1310b57cec5SDimitry Andric     typedef orc::LocalJITCompileCallbackManager<orc::OrcAArch64> CCMgrT;
1320b57cec5SDimitry Andric     return CCMgrT::Create(ES, ErrorHandlerAddress);
1330b57cec5SDimitry Andric     }
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric     case Triple::x86: {
1360b57cec5SDimitry Andric       typedef orc::LocalJITCompileCallbackManager<orc::OrcI386> CCMgrT;
1370b57cec5SDimitry Andric       return CCMgrT::Create(ES, ErrorHandlerAddress);
1380b57cec5SDimitry Andric     }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric     case Triple::mips: {
1410b57cec5SDimitry Andric       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Be> CCMgrT;
1420b57cec5SDimitry Andric       return CCMgrT::Create(ES, ErrorHandlerAddress);
1430b57cec5SDimitry Andric     }
1440b57cec5SDimitry Andric     case Triple::mipsel: {
1450b57cec5SDimitry Andric       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Le> CCMgrT;
1460b57cec5SDimitry Andric       return CCMgrT::Create(ES, ErrorHandlerAddress);
1470b57cec5SDimitry Andric     }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric     case Triple::mips64:
1500b57cec5SDimitry Andric     case Triple::mips64el: {
1510b57cec5SDimitry Andric       typedef orc::LocalJITCompileCallbackManager<orc::OrcMips64> CCMgrT;
1520b57cec5SDimitry Andric       return CCMgrT::Create(ES, ErrorHandlerAddress);
1530b57cec5SDimitry Andric     }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     case Triple::x86_64: {
1560b57cec5SDimitry Andric       if (T.getOS() == Triple::OSType::Win32) {
1570b57cec5SDimitry Andric         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_Win32> CCMgrT;
1580b57cec5SDimitry Andric         return CCMgrT::Create(ES, ErrorHandlerAddress);
1590b57cec5SDimitry Andric       } else {
1600b57cec5SDimitry Andric         typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_SysV> CCMgrT;
1610b57cec5SDimitry Andric         return CCMgrT::Create(ES, ErrorHandlerAddress);
1620b57cec5SDimitry Andric       }
1630b57cec5SDimitry Andric     }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   }
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric std::function<std::unique_ptr<IndirectStubsManager>()>
1690b57cec5SDimitry Andric createLocalIndirectStubsManagerBuilder(const Triple &T) {
1700b57cec5SDimitry Andric   switch (T.getArch()) {
1710b57cec5SDimitry Andric     default:
1720b57cec5SDimitry Andric       return [](){
1738bcb0991SDimitry Andric         return std::make_unique<
1740b57cec5SDimitry Andric                        orc::LocalIndirectStubsManager<orc::OrcGenericABI>>();
1750b57cec5SDimitry Andric       };
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric     case Triple::aarch64:
1788bcb0991SDimitry Andric     case Triple::aarch64_32:
1790b57cec5SDimitry Andric       return [](){
1808bcb0991SDimitry Andric         return std::make_unique<
1810b57cec5SDimitry Andric                        orc::LocalIndirectStubsManager<orc::OrcAArch64>>();
1820b57cec5SDimitry Andric       };
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric     case Triple::x86:
1850b57cec5SDimitry Andric       return [](){
1868bcb0991SDimitry Andric         return std::make_unique<
1870b57cec5SDimitry Andric                        orc::LocalIndirectStubsManager<orc::OrcI386>>();
1880b57cec5SDimitry Andric       };
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric     case Triple::mips:
1910b57cec5SDimitry Andric       return [](){
1928bcb0991SDimitry Andric           return std::make_unique<
1930b57cec5SDimitry Andric                       orc::LocalIndirectStubsManager<orc::OrcMips32Be>>();
1940b57cec5SDimitry Andric       };
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric     case Triple::mipsel:
1970b57cec5SDimitry Andric       return [](){
1988bcb0991SDimitry Andric           return std::make_unique<
1990b57cec5SDimitry Andric                       orc::LocalIndirectStubsManager<orc::OrcMips32Le>>();
2000b57cec5SDimitry Andric       };
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric     case Triple::mips64:
2030b57cec5SDimitry Andric     case Triple::mips64el:
2040b57cec5SDimitry Andric       return [](){
2058bcb0991SDimitry Andric           return std::make_unique<
2060b57cec5SDimitry Andric                       orc::LocalIndirectStubsManager<orc::OrcMips64>>();
2070b57cec5SDimitry Andric       };
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric     case Triple::x86_64:
2100b57cec5SDimitry Andric       if (T.getOS() == Triple::OSType::Win32) {
2110b57cec5SDimitry Andric         return [](){
2128bcb0991SDimitry Andric           return std::make_unique<
2130b57cec5SDimitry Andric                      orc::LocalIndirectStubsManager<orc::OrcX86_64_Win32>>();
2140b57cec5SDimitry Andric         };
2150b57cec5SDimitry Andric       } else {
2160b57cec5SDimitry Andric         return [](){
2178bcb0991SDimitry Andric           return std::make_unique<
2180b57cec5SDimitry Andric                      orc::LocalIndirectStubsManager<orc::OrcX86_64_SysV>>();
2190b57cec5SDimitry Andric         };
2200b57cec5SDimitry Andric       }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric   }
2230b57cec5SDimitry Andric }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric Constant* createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr) {
2260b57cec5SDimitry Andric   Constant *AddrIntVal =
2270b57cec5SDimitry Andric     ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
2280b57cec5SDimitry Andric   Constant *AddrPtrVal =
2290b57cec5SDimitry Andric     ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
2300b57cec5SDimitry Andric                           PointerType::get(&FT, 0));
2310b57cec5SDimitry Andric   return AddrPtrVal;
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric GlobalVariable* createImplPointer(PointerType &PT, Module &M,
2350b57cec5SDimitry Andric                                   const Twine &Name, Constant *Initializer) {
2360b57cec5SDimitry Andric   auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
2370b57cec5SDimitry Andric                                Initializer, Name, nullptr,
2380b57cec5SDimitry Andric                                GlobalValue::NotThreadLocal, 0, true);
2390b57cec5SDimitry Andric   IP->setVisibility(GlobalValue::HiddenVisibility);
2400b57cec5SDimitry Andric   return IP;
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric void makeStub(Function &F, Value &ImplPointer) {
2440b57cec5SDimitry Andric   assert(F.isDeclaration() && "Can't turn a definition into a stub.");
2450b57cec5SDimitry Andric   assert(F.getParent() && "Function isn't in a module.");
2460b57cec5SDimitry Andric   Module &M = *F.getParent();
2470b57cec5SDimitry Andric   BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
2480b57cec5SDimitry Andric   IRBuilder<> Builder(EntryBlock);
2490b57cec5SDimitry Andric   LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
2500b57cec5SDimitry Andric   std::vector<Value*> CallArgs;
2510b57cec5SDimitry Andric   for (auto &A : F.args())
2520b57cec5SDimitry Andric     CallArgs.push_back(&A);
2530b57cec5SDimitry Andric   CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
2540b57cec5SDimitry Andric   Call->setTailCall();
2550b57cec5SDimitry Andric   Call->setAttributes(F.getAttributes());
2560b57cec5SDimitry Andric   if (F.getReturnType()->isVoidTy())
2570b57cec5SDimitry Andric     Builder.CreateRetVoid();
2580b57cec5SDimitry Andric   else
2590b57cec5SDimitry Andric     Builder.CreateRet(Call);
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
2630b57cec5SDimitry Andric   std::vector<GlobalValue *> PromotedGlobals;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   for (auto &GV : M.global_values()) {
2660b57cec5SDimitry Andric     bool Promoted = true;
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric     // Rename if necessary.
2690b57cec5SDimitry Andric     if (!GV.hasName())
2700b57cec5SDimitry Andric       GV.setName("__orc_anon." + Twine(NextId++));
2710b57cec5SDimitry Andric     else if (GV.getName().startswith("\01L"))
2720b57cec5SDimitry Andric       GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
2730b57cec5SDimitry Andric     else if (GV.hasLocalLinkage())
2740b57cec5SDimitry Andric       GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
2750b57cec5SDimitry Andric     else
2760b57cec5SDimitry Andric       Promoted = false;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric     if (GV.hasLocalLinkage()) {
2790b57cec5SDimitry Andric       GV.setLinkage(GlobalValue::ExternalLinkage);
2800b57cec5SDimitry Andric       GV.setVisibility(GlobalValue::HiddenVisibility);
2810b57cec5SDimitry Andric       Promoted = true;
2820b57cec5SDimitry Andric     }
2830b57cec5SDimitry Andric     GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric     if (Promoted)
2860b57cec5SDimitry Andric       PromotedGlobals.push_back(&GV);
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   return PromotedGlobals;
2900b57cec5SDimitry Andric }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric Function* cloneFunctionDecl(Module &Dst, const Function &F,
2930b57cec5SDimitry Andric                             ValueToValueMapTy *VMap) {
2940b57cec5SDimitry Andric   Function *NewF =
2950b57cec5SDimitry Andric     Function::Create(cast<FunctionType>(F.getValueType()),
2960b57cec5SDimitry Andric                      F.getLinkage(), F.getName(), &Dst);
2970b57cec5SDimitry Andric   NewF->copyAttributesFrom(&F);
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   if (VMap) {
3000b57cec5SDimitry Andric     (*VMap)[&F] = NewF;
3010b57cec5SDimitry Andric     auto NewArgI = NewF->arg_begin();
3020b57cec5SDimitry Andric     for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
3030b57cec5SDimitry Andric          ++ArgI, ++NewArgI)
3040b57cec5SDimitry Andric       (*VMap)[&*ArgI] = &*NewArgI;
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   return NewF;
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
3110b57cec5SDimitry Andric                       ValueMaterializer *Materializer,
3120b57cec5SDimitry Andric                       Function *NewF) {
3130b57cec5SDimitry Andric   assert(!OrigF.isDeclaration() && "Nothing to move");
3140b57cec5SDimitry Andric   if (!NewF)
3150b57cec5SDimitry Andric     NewF = cast<Function>(VMap[&OrigF]);
3160b57cec5SDimitry Andric   else
3170b57cec5SDimitry Andric     assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
3180b57cec5SDimitry Andric   assert(NewF && "Function mapping missing from VMap.");
3190b57cec5SDimitry Andric   assert(NewF->getParent() != OrigF.getParent() &&
3200b57cec5SDimitry Andric          "moveFunctionBody should only be used to move bodies between "
3210b57cec5SDimitry Andric          "modules.");
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
324fe6060f1SDimitry Andric   CloneFunctionInto(NewF, &OrigF, VMap,
325fe6060f1SDimitry Andric                     CloneFunctionChangeType::DifferentModule, Returns, "",
326fe6060f1SDimitry Andric                     nullptr, nullptr, Materializer);
3270b57cec5SDimitry Andric   OrigF.deleteBody();
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
3310b57cec5SDimitry Andric                                         ValueToValueMapTy *VMap) {
3320b57cec5SDimitry Andric   GlobalVariable *NewGV = new GlobalVariable(
3330b57cec5SDimitry Andric       Dst, GV.getValueType(), GV.isConstant(),
3340b57cec5SDimitry Andric       GV.getLinkage(), nullptr, GV.getName(), nullptr,
3350b57cec5SDimitry Andric       GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
3360b57cec5SDimitry Andric   NewGV->copyAttributesFrom(&GV);
3370b57cec5SDimitry Andric   if (VMap)
3380b57cec5SDimitry Andric     (*VMap)[&GV] = NewGV;
3390b57cec5SDimitry Andric   return NewGV;
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
3430b57cec5SDimitry Andric                                    ValueToValueMapTy &VMap,
3440b57cec5SDimitry Andric                                    ValueMaterializer *Materializer,
3450b57cec5SDimitry Andric                                    GlobalVariable *NewGV) {
3460b57cec5SDimitry Andric   assert(OrigGV.hasInitializer() && "Nothing to move");
3470b57cec5SDimitry Andric   if (!NewGV)
3480b57cec5SDimitry Andric     NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
3490b57cec5SDimitry Andric   else
3500b57cec5SDimitry Andric     assert(VMap[&OrigGV] == NewGV &&
3510b57cec5SDimitry Andric            "Incorrect global variable mapping in VMap.");
3520b57cec5SDimitry Andric   assert(NewGV->getParent() != OrigGV.getParent() &&
3530b57cec5SDimitry Andric          "moveGlobalVariableInitializer should only be used to move "
3540b57cec5SDimitry Andric          "initializers between modules");
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
3570b57cec5SDimitry Andric                                  nullptr, Materializer));
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
3610b57cec5SDimitry Andric                                   ValueToValueMapTy &VMap) {
3620b57cec5SDimitry Andric   assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
3630b57cec5SDimitry Andric   auto *NewA = GlobalAlias::create(OrigA.getValueType(),
3640b57cec5SDimitry Andric                                    OrigA.getType()->getPointerAddressSpace(),
3650b57cec5SDimitry Andric                                    OrigA.getLinkage(), OrigA.getName(), &Dst);
3660b57cec5SDimitry Andric   NewA->copyAttributesFrom(&OrigA);
3670b57cec5SDimitry Andric   VMap[&OrigA] = NewA;
3680b57cec5SDimitry Andric   return NewA;
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
3720b57cec5SDimitry Andric                               ValueToValueMapTy &VMap) {
3730b57cec5SDimitry Andric   auto *MFs = Src.getModuleFlagsMetadata();
3740b57cec5SDimitry Andric   if (!MFs)
3750b57cec5SDimitry Andric     return;
3760b57cec5SDimitry Andric   for (auto *MF : MFs->operands())
3770b57cec5SDimitry Andric     Dst.addModuleFlag(MapMetadata(MF, VMap));
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
380*349cc55cSDimitry Andric Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym,
381*349cc55cSDimitry Andric                                                    jitlink::LinkGraph &G,
382*349cc55cSDimitry Andric                                                    MCDisassembler &Disassembler,
383*349cc55cSDimitry Andric                                                    MCInstrAnalysis &MIA) {
384*349cc55cSDimitry Andric   // AArch64 appears to already come with the necessary relocations. Among other
385*349cc55cSDimitry Andric   // architectures, only x86_64 is currently implemented here.
386*349cc55cSDimitry Andric   if (G.getTargetTriple().getArch() != Triple::x86_64)
387*349cc55cSDimitry Andric     return Error::success();
388*349cc55cSDimitry Andric 
389*349cc55cSDimitry Andric   raw_null_ostream CommentStream;
390*349cc55cSDimitry Andric   auto &STI = Disassembler.getSubtargetInfo();
391*349cc55cSDimitry Andric 
392*349cc55cSDimitry Andric   // Determine the function bounds
393*349cc55cSDimitry Andric   auto &B = Sym.getBlock();
394*349cc55cSDimitry Andric   assert(!B.isZeroFill() && "expected content block");
395*349cc55cSDimitry Andric   auto SymAddress = Sym.getAddress();
396*349cc55cSDimitry Andric   auto SymStartInBlock =
397*349cc55cSDimitry Andric       (const uint8_t *)B.getContent().data() + Sym.getOffset();
398*349cc55cSDimitry Andric   auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
399*349cc55cSDimitry Andric   auto Content = makeArrayRef(SymStartInBlock, SymSize);
400*349cc55cSDimitry Andric 
401*349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
402*349cc55cSDimitry Andric 
403*349cc55cSDimitry Andric   SmallDenseSet<uintptr_t, 8> ExistingRelocations;
404*349cc55cSDimitry Andric   for (auto &E : B.edges()) {
405*349cc55cSDimitry Andric     if (E.isRelocation())
406*349cc55cSDimitry Andric       ExistingRelocations.insert(E.getOffset());
407*349cc55cSDimitry Andric   }
408*349cc55cSDimitry Andric 
409*349cc55cSDimitry Andric   size_t I = 0;
410*349cc55cSDimitry Andric   while (I < Content.size()) {
411*349cc55cSDimitry Andric     MCInst Instr;
412*349cc55cSDimitry Andric     uint64_t InstrSize = 0;
413*349cc55cSDimitry Andric     uint64_t InstrStart = SymAddress + I;
414*349cc55cSDimitry Andric     auto DecodeStatus = Disassembler.getInstruction(
415*349cc55cSDimitry Andric         Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
416*349cc55cSDimitry Andric     if (DecodeStatus != MCDisassembler::Success) {
417*349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
418*349cc55cSDimitry Andric                         << InstrStart);
419*349cc55cSDimitry Andric       return make_error<StringError>(
420*349cc55cSDimitry Andric           formatv("failed to disassemble at address {0:x16}", InstrStart),
421*349cc55cSDimitry Andric           inconvertibleErrorCode());
422*349cc55cSDimitry Andric     }
423*349cc55cSDimitry Andric     // Advance to the next instruction.
424*349cc55cSDimitry Andric     I += InstrSize;
425*349cc55cSDimitry Andric 
426*349cc55cSDimitry Andric     // Check for a PC-relative address equal to the symbol itself.
427*349cc55cSDimitry Andric     auto PCRelAddr =
428*349cc55cSDimitry Andric         MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
429*349cc55cSDimitry Andric     if (!PCRelAddr.hasValue() || PCRelAddr.getValue() != SymAddress)
430*349cc55cSDimitry Andric       continue;
431*349cc55cSDimitry Andric 
432*349cc55cSDimitry Andric     auto RelocOffInInstr =
433*349cc55cSDimitry Andric         MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
434*349cc55cSDimitry Andric     if (!RelocOffInInstr.hasValue() ||
435*349cc55cSDimitry Andric         InstrSize - RelocOffInInstr.getValue() != 4) {
436*349cc55cSDimitry Andric       LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
437*349cc55cSDimitry Andric                         << InstrStart);
438*349cc55cSDimitry Andric       continue;
439*349cc55cSDimitry Andric     }
440*349cc55cSDimitry Andric 
441*349cc55cSDimitry Andric     auto RelocOffInBlock =
442*349cc55cSDimitry Andric         InstrStart + *RelocOffInInstr - SymAddress + Sym.getOffset();
443*349cc55cSDimitry Andric     if (ExistingRelocations.contains(RelocOffInBlock))
444*349cc55cSDimitry Andric       continue;
445*349cc55cSDimitry Andric 
446*349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
447*349cc55cSDimitry Andric     B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
448*349cc55cSDimitry Andric   }
449*349cc55cSDimitry Andric   return Error::success();
450*349cc55cSDimitry Andric }
451*349cc55cSDimitry Andric 
4520b57cec5SDimitry Andric } // End namespace orc.
4530b57cec5SDimitry Andric } // End namespace llvm.
454