IndirectionUtils.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. //===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/Triple.h"
  11. #include "llvm/ExecutionEngine/JITLink/x86_64.h"
  12. #include "llvm/ExecutionEngine/Orc/OrcABISupport.h"
  13. #include "llvm/IR/IRBuilder.h"
  14. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  15. #include "llvm/MC/MCInstrAnalysis.h"
  16. #include "llvm/Support/Format.h"
  17. #include "llvm/Transforms/Utils/Cloning.h"
  18. #include <sstream>
  19. #define DEBUG_TYPE "orc"
  20. using namespace llvm;
  21. using namespace llvm::orc;
  22. namespace {
  23. class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
  24. public:
  25. using CompileFunction = JITCompileCallbackManager::CompileFunction;
  26. CompileCallbackMaterializationUnit(SymbolStringPtr Name,
  27. CompileFunction Compile)
  28. : MaterializationUnit(Interface(
  29. SymbolFlagsMap({{Name, JITSymbolFlags::Exported}}), nullptr)),
  30. Name(std::move(Name)), Compile(std::move(Compile)) {}
  31. StringRef getName() const override { return "<Compile Callbacks>"; }
  32. private:
  33. void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
  34. SymbolMap Result;
  35. Result[Name] = JITEvaluatedSymbol(Compile(), JITSymbolFlags::Exported);
  36. // No dependencies, so these calls cannot fail.
  37. cantFail(R->notifyResolved(Result));
  38. cantFail(R->notifyEmitted());
  39. }
  40. void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
  41. llvm_unreachable("Discard should never occur on a LMU?");
  42. }
  43. SymbolStringPtr Name;
  44. CompileFunction Compile;
  45. };
  46. } // namespace
  47. namespace llvm {
  48. namespace orc {
  49. TrampolinePool::~TrampolinePool() = default;
  50. void IndirectStubsManager::anchor() {}
  51. Expected<JITTargetAddress>
  52. JITCompileCallbackManager::getCompileCallback(CompileFunction Compile) {
  53. if (auto TrampolineAddr = TP->getTrampoline()) {
  54. auto CallbackName =
  55. ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
  56. std::lock_guard<std::mutex> Lock(CCMgrMutex);
  57. AddrToSymbol[*TrampolineAddr] = CallbackName;
  58. cantFail(
  59. CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
  60. std::move(CallbackName), std::move(Compile))));
  61. return *TrampolineAddr;
  62. } else
  63. return TrampolineAddr.takeError();
  64. }
  65. JITTargetAddress JITCompileCallbackManager::executeCompileCallback(
  66. JITTargetAddress TrampolineAddr) {
  67. SymbolStringPtr Name;
  68. {
  69. std::unique_lock<std::mutex> Lock(CCMgrMutex);
  70. auto I = AddrToSymbol.find(TrampolineAddr);
  71. // If this address is not associated with a compile callback then report an
  72. // error to the execution session and return ErrorHandlerAddress to the
  73. // callee.
  74. if (I == AddrToSymbol.end()) {
  75. Lock.unlock();
  76. std::string ErrMsg;
  77. {
  78. raw_string_ostream ErrMsgStream(ErrMsg);
  79. ErrMsgStream << "No compile callback for trampoline at "
  80. << format("0x%016" PRIx64, TrampolineAddr);
  81. }
  82. ES.reportError(
  83. make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode()));
  84. return ErrorHandlerAddress;
  85. } else
  86. Name = I->second;
  87. }
  88. if (auto Sym =
  89. ES.lookup(makeJITDylibSearchOrder(
  90. &CallbacksJD, JITDylibLookupFlags::MatchAllSymbols),
  91. Name))
  92. return Sym->getAddress();
  93. else {
  94. llvm::dbgs() << "Didn't find callback.\n";
  95. // If anything goes wrong materializing Sym then report it to the session
  96. // and return the ErrorHandlerAddress;
  97. ES.reportError(Sym.takeError());
  98. return ErrorHandlerAddress;
  99. }
  100. }
  101. Expected<std::unique_ptr<JITCompileCallbackManager>>
  102. createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES,
  103. JITTargetAddress ErrorHandlerAddress) {
  104. switch (T.getArch()) {
  105. default:
  106. return make_error<StringError>(
  107. std::string("No callback manager available for ") + T.str(),
  108. inconvertibleErrorCode());
  109. case Triple::aarch64:
  110. case Triple::aarch64_32: {
  111. typedef orc::LocalJITCompileCallbackManager<orc::OrcAArch64> CCMgrT;
  112. return CCMgrT::Create(ES, ErrorHandlerAddress);
  113. }
  114. case Triple::x86: {
  115. typedef orc::LocalJITCompileCallbackManager<orc::OrcI386> CCMgrT;
  116. return CCMgrT::Create(ES, ErrorHandlerAddress);
  117. }
  118. case Triple::loongarch64: {
  119. typedef orc::LocalJITCompileCallbackManager<orc::OrcLoongArch64> CCMgrT;
  120. return CCMgrT::Create(ES, ErrorHandlerAddress);
  121. }
  122. case Triple::mips: {
  123. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Be> CCMgrT;
  124. return CCMgrT::Create(ES, ErrorHandlerAddress);
  125. }
  126. case Triple::mipsel: {
  127. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips32Le> CCMgrT;
  128. return CCMgrT::Create(ES, ErrorHandlerAddress);
  129. }
  130. case Triple::mips64:
  131. case Triple::mips64el: {
  132. typedef orc::LocalJITCompileCallbackManager<orc::OrcMips64> CCMgrT;
  133. return CCMgrT::Create(ES, ErrorHandlerAddress);
  134. }
  135. case Triple::riscv64: {
  136. typedef orc::LocalJITCompileCallbackManager<orc::OrcRiscv64> CCMgrT;
  137. return CCMgrT::Create(ES, ErrorHandlerAddress);
  138. }
  139. case Triple::x86_64: {
  140. if (T.getOS() == Triple::OSType::Win32) {
  141. typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_Win32> CCMgrT;
  142. return CCMgrT::Create(ES, ErrorHandlerAddress);
  143. } else {
  144. typedef orc::LocalJITCompileCallbackManager<orc::OrcX86_64_SysV> CCMgrT;
  145. return CCMgrT::Create(ES, ErrorHandlerAddress);
  146. }
  147. }
  148. }
  149. }
  150. std::function<std::unique_ptr<IndirectStubsManager>()>
  151. createLocalIndirectStubsManagerBuilder(const Triple &T) {
  152. switch (T.getArch()) {
  153. default:
  154. return [](){
  155. return std::make_unique<
  156. orc::LocalIndirectStubsManager<orc::OrcGenericABI>>();
  157. };
  158. case Triple::aarch64:
  159. case Triple::aarch64_32:
  160. return [](){
  161. return std::make_unique<
  162. orc::LocalIndirectStubsManager<orc::OrcAArch64>>();
  163. };
  164. case Triple::x86:
  165. return [](){
  166. return std::make_unique<
  167. orc::LocalIndirectStubsManager<orc::OrcI386>>();
  168. };
  169. case Triple::loongarch64:
  170. return []() {
  171. return std::make_unique<
  172. orc::LocalIndirectStubsManager<orc::OrcLoongArch64>>();
  173. };
  174. case Triple::mips:
  175. return [](){
  176. return std::make_unique<
  177. orc::LocalIndirectStubsManager<orc::OrcMips32Be>>();
  178. };
  179. case Triple::mipsel:
  180. return [](){
  181. return std::make_unique<
  182. orc::LocalIndirectStubsManager<orc::OrcMips32Le>>();
  183. };
  184. case Triple::mips64:
  185. case Triple::mips64el:
  186. return [](){
  187. return std::make_unique<
  188. orc::LocalIndirectStubsManager<orc::OrcMips64>>();
  189. };
  190. case Triple::riscv64:
  191. return []() {
  192. return std::make_unique<
  193. orc::LocalIndirectStubsManager<orc::OrcRiscv64>>();
  194. };
  195. case Triple::x86_64:
  196. if (T.getOS() == Triple::OSType::Win32) {
  197. return [](){
  198. return std::make_unique<
  199. orc::LocalIndirectStubsManager<orc::OrcX86_64_Win32>>();
  200. };
  201. } else {
  202. return [](){
  203. return std::make_unique<
  204. orc::LocalIndirectStubsManager<orc::OrcX86_64_SysV>>();
  205. };
  206. }
  207. }
  208. }
  209. Constant* createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr) {
  210. Constant *AddrIntVal =
  211. ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
  212. Constant *AddrPtrVal =
  213. ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
  214. PointerType::get(&FT, 0));
  215. return AddrPtrVal;
  216. }
  217. GlobalVariable* createImplPointer(PointerType &PT, Module &M,
  218. const Twine &Name, Constant *Initializer) {
  219. auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
  220. Initializer, Name, nullptr,
  221. GlobalValue::NotThreadLocal, 0, true);
  222. IP->setVisibility(GlobalValue::HiddenVisibility);
  223. return IP;
  224. }
  225. void makeStub(Function &F, Value &ImplPointer) {
  226. assert(F.isDeclaration() && "Can't turn a definition into a stub.");
  227. assert(F.getParent() && "Function isn't in a module.");
  228. Module &M = *F.getParent();
  229. BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
  230. IRBuilder<> Builder(EntryBlock);
  231. LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
  232. std::vector<Value*> CallArgs;
  233. for (auto &A : F.args())
  234. CallArgs.push_back(&A);
  235. CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
  236. Call->setTailCall();
  237. Call->setAttributes(F.getAttributes());
  238. if (F.getReturnType()->isVoidTy())
  239. Builder.CreateRetVoid();
  240. else
  241. Builder.CreateRet(Call);
  242. }
  243. std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
  244. std::vector<GlobalValue *> PromotedGlobals;
  245. for (auto &GV : M.global_values()) {
  246. bool Promoted = true;
  247. // Rename if necessary.
  248. if (!GV.hasName())
  249. GV.setName("__orc_anon." + Twine(NextId++));
  250. else if (GV.getName().startswith("\01L"))
  251. GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
  252. else if (GV.hasLocalLinkage())
  253. GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
  254. else
  255. Promoted = false;
  256. if (GV.hasLocalLinkage()) {
  257. GV.setLinkage(GlobalValue::ExternalLinkage);
  258. GV.setVisibility(GlobalValue::HiddenVisibility);
  259. Promoted = true;
  260. }
  261. GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
  262. if (Promoted)
  263. PromotedGlobals.push_back(&GV);
  264. }
  265. return PromotedGlobals;
  266. }
  267. Function* cloneFunctionDecl(Module &Dst, const Function &F,
  268. ValueToValueMapTy *VMap) {
  269. Function *NewF =
  270. Function::Create(cast<FunctionType>(F.getValueType()),
  271. F.getLinkage(), F.getName(), &Dst);
  272. NewF->copyAttributesFrom(&F);
  273. if (VMap) {
  274. (*VMap)[&F] = NewF;
  275. auto NewArgI = NewF->arg_begin();
  276. for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
  277. ++ArgI, ++NewArgI)
  278. (*VMap)[&*ArgI] = &*NewArgI;
  279. }
  280. return NewF;
  281. }
  282. void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
  283. ValueMaterializer *Materializer,
  284. Function *NewF) {
  285. assert(!OrigF.isDeclaration() && "Nothing to move");
  286. if (!NewF)
  287. NewF = cast<Function>(VMap[&OrigF]);
  288. else
  289. assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
  290. assert(NewF && "Function mapping missing from VMap.");
  291. assert(NewF->getParent() != OrigF.getParent() &&
  292. "moveFunctionBody should only be used to move bodies between "
  293. "modules.");
  294. SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
  295. CloneFunctionInto(NewF, &OrigF, VMap,
  296. CloneFunctionChangeType::DifferentModule, Returns, "",
  297. nullptr, nullptr, Materializer);
  298. OrigF.deleteBody();
  299. }
  300. GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
  301. ValueToValueMapTy *VMap) {
  302. GlobalVariable *NewGV = new GlobalVariable(
  303. Dst, GV.getValueType(), GV.isConstant(),
  304. GV.getLinkage(), nullptr, GV.getName(), nullptr,
  305. GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
  306. NewGV->copyAttributesFrom(&GV);
  307. if (VMap)
  308. (*VMap)[&GV] = NewGV;
  309. return NewGV;
  310. }
  311. void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
  312. ValueToValueMapTy &VMap,
  313. ValueMaterializer *Materializer,
  314. GlobalVariable *NewGV) {
  315. assert(OrigGV.hasInitializer() && "Nothing to move");
  316. if (!NewGV)
  317. NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
  318. else
  319. assert(VMap[&OrigGV] == NewGV &&
  320. "Incorrect global variable mapping in VMap.");
  321. assert(NewGV->getParent() != OrigGV.getParent() &&
  322. "moveGlobalVariableInitializer should only be used to move "
  323. "initializers between modules");
  324. NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
  325. nullptr, Materializer));
  326. }
  327. GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
  328. ValueToValueMapTy &VMap) {
  329. assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
  330. auto *NewA = GlobalAlias::create(OrigA.getValueType(),
  331. OrigA.getType()->getPointerAddressSpace(),
  332. OrigA.getLinkage(), OrigA.getName(), &Dst);
  333. NewA->copyAttributesFrom(&OrigA);
  334. VMap[&OrigA] = NewA;
  335. return NewA;
  336. }
  337. void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
  338. ValueToValueMapTy &VMap) {
  339. auto *MFs = Src.getModuleFlagsMetadata();
  340. if (!MFs)
  341. return;
  342. for (auto *MF : MFs->operands())
  343. Dst.addModuleFlag(MapMetadata(MF, VMap));
  344. }
  345. Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym,
  346. jitlink::LinkGraph &G,
  347. MCDisassembler &Disassembler,
  348. MCInstrAnalysis &MIA) {
  349. // AArch64 appears to already come with the necessary relocations. Among other
  350. // architectures, only x86_64 is currently implemented here.
  351. if (G.getTargetTriple().getArch() != Triple::x86_64)
  352. return Error::success();
  353. raw_null_ostream CommentStream;
  354. auto &STI = Disassembler.getSubtargetInfo();
  355. // Determine the function bounds
  356. auto &B = Sym.getBlock();
  357. assert(!B.isZeroFill() && "expected content block");
  358. auto SymAddress = Sym.getAddress();
  359. auto SymStartInBlock =
  360. (const uint8_t *)B.getContent().data() + Sym.getOffset();
  361. auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
  362. auto Content = ArrayRef(SymStartInBlock, SymSize);
  363. LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
  364. SmallDenseSet<uintptr_t, 8> ExistingRelocations;
  365. for (auto &E : B.edges()) {
  366. if (E.isRelocation())
  367. ExistingRelocations.insert(E.getOffset());
  368. }
  369. size_t I = 0;
  370. while (I < Content.size()) {
  371. MCInst Instr;
  372. uint64_t InstrSize = 0;
  373. uint64_t InstrStart = SymAddress.getValue() + I;
  374. auto DecodeStatus = Disassembler.getInstruction(
  375. Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
  376. if (DecodeStatus != MCDisassembler::Success) {
  377. LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
  378. << InstrStart);
  379. return make_error<StringError>(
  380. formatv("failed to disassemble at address {0:x16}", InstrStart),
  381. inconvertibleErrorCode());
  382. }
  383. // Advance to the next instruction.
  384. I += InstrSize;
  385. // Check for a PC-relative address equal to the symbol itself.
  386. auto PCRelAddr =
  387. MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
  388. if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
  389. continue;
  390. auto RelocOffInInstr =
  391. MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
  392. if (!RelocOffInInstr || InstrSize - *RelocOffInInstr != 4) {
  393. LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
  394. << InstrStart);
  395. continue;
  396. }
  397. auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
  398. SymAddress + Sym.getOffset();
  399. if (ExistingRelocations.contains(RelocOffInBlock))
  400. continue;
  401. LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
  402. B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
  403. }
  404. return Error::success();
  405. }
  406. } // End namespace orc.
  407. } // End namespace llvm.