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