LLVM 24.0.0git
IndirectionUtils.cpp
Go to the documentation of this file.
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
12#include "llvm/IR/IRBuilder.h"
13#include "llvm/IR/Module.h"
18
19#define DEBUG_TYPE "orc"
20
21using namespace llvm;
22using namespace llvm::orc;
23
24namespace {
25
26class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
27public:
28 using CompileFunction = JITCompileCallbackManager::CompileFunction;
29
30 CompileCallbackMaterializationUnit(SymbolStringPtr Name,
31 CompileFunction Compile)
32 : MaterializationUnit(Interface(
33 SymbolFlagsMap({{Name, JITSymbolFlags::Exported}}), nullptr)),
34 Name(std::move(Name)), Compile(std::move(Compile)) {}
35
36 StringRef getName() const override { return "<Compile Callbacks>"; }
37
38private:
39 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
41 Result[Name] = {Compile(), JITSymbolFlags::Exported};
42 // No dependencies, so these calls cannot fail.
43 cantFail(R->notifyResolved(Result));
44 cantFail(R->notifyEmitted({}));
45 }
46
47 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
48 llvm_unreachable("Discard should never occur on a LMU?");
49 }
50
51 SymbolStringPtr Name;
52 CompileFunction Compile;
53};
54
55} // namespace
56
57namespace llvm {
58namespace orc {
59
61void IndirectStubsManager::anchor() {}
62
63Expected<ExecutorAddr>
65 if (auto TrampolineAddr = TP->getTrampoline()) {
66 auto CallbackName =
67 ES.intern(std::string("cc") + std::to_string(++NextCallbackId));
68
69 std::lock_guard<std::mutex> Lock(CCMgrMutex);
70 AddrToSymbol[*TrampolineAddr] = CallbackName;
72 CallbacksJD.define(std::make_unique<CompileCallbackMaterializationUnit>(
73 std::move(CallbackName), std::move(Compile))));
74 return *TrampolineAddr;
75 } else
76 return TrampolineAddr.takeError();
77}
78
81 SymbolStringPtr Name;
82
83 {
84 std::unique_lock<std::mutex> Lock(CCMgrMutex);
85 auto I = AddrToSymbol.find(TrampolineAddr);
86
87 // If this address is not associated with a compile callback then report an
88 // error to the execution session and return ErrorHandlerAddress to the
89 // callee.
90 if (I == AddrToSymbol.end()) {
91 Lock.unlock();
92 ES.reportError(
93 make_error<StringError>("No compile callback for trampoline at " +
94 formatv("{0:x}", TrampolineAddr),
96 return ErrorHandlerAddress;
97 } else
98 Name = I->second;
99 }
100
101 if (auto Sym =
102 ES.lookup(makeJITDylibSearchOrder(
104 Name))
105 return Sym->getAddress();
106 else {
107 llvm::dbgs() << "Didn't find callback.\n";
108 // If anything goes wrong materializing Sym then report it to the session
109 // and return the ErrorHandlerAddress;
110 ES.reportError(Sym.takeError());
111 return ErrorHandlerAddress;
112 }
113}
114
116 for (auto &[Name, Dest] : NewDests)
117 if (auto Err = updatePointer(*Name, Dest.getAddress()))
118 return Err;
119 return Error::success();
120}
121
123 std::unique_ptr<MaterializationResponsibility> MR, SymbolMap InitialDests) {
124 StubInitsMap StubInits;
125 for (auto &[Name, Dest] : InitialDests)
126 StubInits[*Name] = {Dest.getAddress(), Dest.getFlags()};
127 if (auto Err = createStubs(StubInits)) {
128 MR->getExecutionSession().reportError(std::move(Err));
129 return MR->failMaterialization();
130 }
131 SymbolMap Stubs;
132 for (auto &[Name, Dest] : InitialDests) {
133 auto StubSym = findStub(*Name, false);
134 assert(StubSym.getAddress() && "Stub symbol should be present");
135 Stubs[Name] = StubSym;
136 }
137 if (auto Err = MR->notifyResolved(Stubs)) {
138 MR->getExecutionSession().reportError(std::move(Err));
139 return MR->failMaterialization();
140 }
141 if (auto Err = MR->notifyEmitted({})) {
142 MR->getExecutionSession().reportError(std::move(Err));
143 return MR->failMaterialization();
144 }
145}
146
149 ExecutorAddr ErrorHandlerAddress) {
150 switch (T.getArch()) {
151 default:
153 std::string("No callback manager available for ") + T.str(),
155 case Triple::aarch64:
156 case Triple::aarch64_32: {
158 return CCMgrT::Create(ES, ErrorHandlerAddress);
159 }
160
161 case Triple::x86: {
163 return CCMgrT::Create(ES, ErrorHandlerAddress);
164 }
165
166 case Triple::loongarch64: {
168 return CCMgrT::Create(ES, ErrorHandlerAddress);
169 }
170
171 case Triple::mips: {
173 return CCMgrT::Create(ES, ErrorHandlerAddress);
174 }
175 case Triple::mipsel: {
177 return CCMgrT::Create(ES, ErrorHandlerAddress);
178 }
179
180 case Triple::mips64:
181 case Triple::mips64el: {
183 return CCMgrT::Create(ES, ErrorHandlerAddress);
184 }
185
186 case Triple::riscv64: {
188 return CCMgrT::Create(ES, ErrorHandlerAddress);
189 }
190
191 case Triple::systemz: {
193 return CCMgrT::Create(ES, ErrorHandlerAddress);
194 }
195
196 case Triple::x86_64: {
197 if (T.getOS() == Triple::OSType::Win32) {
199 return CCMgrT::Create(ES, ErrorHandlerAddress);
200 } else {
202 return CCMgrT::Create(ES, ErrorHandlerAddress);
203 }
204 }
205
206 }
207}
208
209std::function<std::unique_ptr<IndirectStubsManager>()>
211 switch (T.getArch()) {
212 default:
213 return [](){
214 return std::make_unique<
216 };
217
218 case Triple::aarch64:
220 return [](){
221 return std::make_unique<
223 };
224
225 case Triple::x86:
226 return [](){
227 return std::make_unique<
229 };
230
232 return []() {
233 return std::make_unique<
235 };
236
237 case Triple::mips:
238 return [](){
239 return std::make_unique<
241 };
242
243 case Triple::mipsel:
244 return [](){
245 return std::make_unique<
247 };
248
249 case Triple::mips64:
250 case Triple::mips64el:
251 return [](){
252 return std::make_unique<
254 };
255
256 case Triple::riscv64:
257 return []() {
258 return std::make_unique<
260 };
261
262 case Triple::systemz:
263 return []() {
264 return std::make_unique<
266 };
267
268 case Triple::x86_64:
269 if (T.getOS() == Triple::OSType::Win32) {
270 return [](){
271 return std::make_unique<
273 };
274 } else {
275 return [](){
276 return std::make_unique<
278 };
279 }
280
281 }
282}
283
285 Constant *AddrIntVal =
286 ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr.getValue());
288 AddrIntVal, PointerType::get(FT.getContext(), 0));
289 return AddrPtrVal;
290}
291
293 const Twine &Name, Constant *Initializer) {
294 auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
295 Initializer, Name, nullptr,
297 IP->setVisibility(GlobalValue::HiddenVisibility);
298 return IP;
299}
300
301void makeStub(Function &F, Value &ImplPointer) {
302 assert(F.isDeclaration() && "Can't turn a definition into a stub.");
303 assert(F.getParent() && "Function isn't in a module.");
304 Module &M = *F.getParent();
305 BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
306 IRBuilder<> Builder(EntryBlock);
307 LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
308 std::vector<Value*> CallArgs;
309 for (auto &A : F.args())
310 CallArgs.push_back(&A);
311 CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
312 Call->setTailCall();
313 Call->setAttributes(F.getAttributes());
314 if (F.getReturnType()->isVoidTy())
315 Builder.CreateRetVoid();
316 else
317 Builder.CreateRet(Call);
318}
319
320std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
321 std::vector<GlobalValue *> PromotedGlobals;
322
323 for (auto &GV : M.global_values()) {
324 bool Promoted = true;
325
326 // Rename if necessary.
327 if (!GV.hasName())
328 GV.setName("__orc_anon." + Twine(NextId++));
329 else if (GV.getName().starts_with("\01L"))
330 GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
331 else if (GV.hasLocalLinkage())
332 GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
333 else
334 Promoted = false;
335
336 if (GV.hasLocalLinkage()) {
337 GV.setLinkage(GlobalValue::ExternalLinkage);
338 GV.setVisibility(GlobalValue::HiddenVisibility);
339 Promoted = true;
340 }
341 GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
342
343 if (Promoted)
344 PromotedGlobals.push_back(&GV);
345 }
346
347 return PromotedGlobals;
348}
349
351 ValueToValueMapTy *VMap) {
352 Function *NewF =
353 Function::Create(F.getFunctionType(), F.getLinkage(), F.getName(), &Dst);
354 NewF->copyAttributesFrom(&F);
355
356 if (VMap) {
357 (*VMap)[&F] = NewF;
358 auto NewArgI = NewF->arg_begin();
359 for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
360 ++ArgI, ++NewArgI)
361 (*VMap)[&*ArgI] = &*NewArgI;
362 }
363
364 return NewF;
365}
366
368 ValueToValueMapTy *VMap) {
369 GlobalVariable *NewGV = new GlobalVariable(
370 Dst, GV.getValueType(), GV.isConstant(),
371 GV.getLinkage(), nullptr, GV.getName(), nullptr,
373 NewGV->copyAttributesFrom(&GV);
374 if (VMap)
375 (*VMap)[&GV] = NewGV;
376 return NewGV;
377}
378
380 ValueToValueMapTy &VMap) {
381 assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
382 auto *NewA = GlobalAlias::create(OrigA.getValueType(),
384 OrigA.getLinkage(), OrigA.getName(), &Dst);
385 NewA->copyAttributesFrom(&OrigA);
386 VMap[&OrigA] = NewA;
387 return NewA;
388}
389
392 MCDisassembler &Disassembler,
393 MCInstrAnalysis &MIA) {
394 // AArch64 appears to already come with the necessary relocations. Among other
395 // architectures, only x86_64 is currently implemented here.
396 if (G.getTargetTriple().getArch() != Triple::x86_64)
397 return Error::success();
398
399 raw_null_ostream CommentStream;
400 auto &STI = Disassembler.getSubtargetInfo();
401
402 // Determine the function bounds
403 auto &B = Sym.getBlock();
404 assert(!B.isZeroFill() && "expected content block");
405 auto SymAddress = Sym.getAddress();
406 auto SymStartInBlock =
407 (const uint8_t *)B.getContent().data() + Sym.getOffset();
408 auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
409 auto Content = ArrayRef(SymStartInBlock, SymSize);
410
411 LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
412
413 SmallDenseSet<uintptr_t, 8> ExistingRelocations;
414 for (auto &E : B.edges()) {
415 if (E.isRelocation())
416 ExistingRelocations.insert(E.getOffset());
417 }
418
419 size_t I = 0;
420 while (I < Content.size()) {
421 MCInst Instr;
422 uint64_t InstrSize = 0;
423 uint64_t InstrStart = SymAddress.getValue() + I;
424 auto DecodeStatus = Disassembler.getInstruction(
425 Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
427 LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
428 << InstrStart);
430 formatv("failed to disassemble at address {0:x16}", InstrStart),
432 }
433 // Advance to the next instruction.
434 I += InstrSize;
435
436 // Check for a PC-relative address equal to the symbol itself.
437 auto PCRelAddr =
438 MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
439 if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
440 continue;
441
442 auto RelocOffInInstr =
443 MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
444 if (!RelocOffInInstr || InstrSize - *RelocOffInInstr != 4) {
445 LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
446 << InstrStart);
447 continue;
448 }
449
450 auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
451 SymAddress + Sym.getOffset();
452 if (ExistingRelocations.contains(RelocOffInBlock))
453 continue;
454
455 LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
456 B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
457 }
458 return Error::success();
459}
460
461} // End namespace orc.
462} // End namespace llvm.
MCDisassembler::DecodeStatus DecodeStatus
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
static StringRef getName(Value *V)
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is an important base class in LLVM.
Definition Constant.h:44
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
arg_iterator arg_begin()
Definition Function.h:862
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
const Constant * getAliasee() const
Definition GlobalAlias.h:87
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:695
LinkageTypes getLinkage() const
ThreadLocalMode getThreadLocalMode() const
PointerType * getType() const
Global values are always pointers.
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Type * getValueType() const
LLVM_ABI void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition Globals.cpp:650
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
An instruction for reading from memory.
Superclass for all disassemblers.
const MCSubtargetInfo & getSubtargetInfo() const
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address, raw_ostream &CStream) const =0
Returns the disassembly of a single instruction.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
virtual std::optional< uint64_t > getMemoryOperandRelocationOffset(const MCInst &Inst, uint64_t Size) const
Given an instruction with a memory operand that could require relocation, returns the offset within t...
virtual std::optional< uint64_t > evaluateMemoryOperandAddress(const MCInst &Inst, const MCSubtargetInfo *STI, uint64_t Addr, uint64_t Size) const
Given an instruction tries to get the address of a memory operand.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Class to represent pointers.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ loongarch64
Definition Triple.h:66
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
An ExecutionSession represents a running JIT program.
Definition Core.h:1096
Represents an address in the executor process.
uint64_t getValue() const
virtual ExecutorSymbolDef findStub(StringRef Name, bool ExportedStubsOnly)=0
Find the stub with the given name.
StringMap< std::pair< ExecutorAddr, JITSymbolFlags > > StubInitsMap
Map type for initializing the manager. See init.
virtual Error updatePointer(StringRef Name, ExecutorAddr NewAddr)=0
Change the value of the implementation pointer for the stub.
virtual Error createStubs(const StubInitsMap &StubInits)=0
Create StubInits.size() stubs with the given names, target addresses, and flags.
void emitRedirectableSymbols(std::unique_ptr< MaterializationResponsibility > MR, SymbolMap InitialDests) override
Emit redirectable symbol.
Error redirect(JITDylib &JD, const SymbolMap &NewDests) override
— RedirectableSymbolManager implementation —
LLVM_ABI ExecutorAddr executeCompileCallback(ExecutorAddr TrampolineAddr)
Execute the callback for the given trampoline id.
LLVM_ABI Expected< ExecutorAddr > getCompileCallback(CompileFunction Compile)
Reserve a compile callback.
std::function< ExecutorAddr()> CompileFunction
Represents a JIT'd dynamic library.
Definition Core.h:668
IndirectStubsManager implementation for the host architecture, e.g.
Manage compile callbacks for in-process JITs.
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
LLVM_ABI std::vector< GlobalValue * > operator()(Module &M)
Promote symbols in the given module.
Pointer to a pooled string representing a symbol name.
A raw_ostream that discards all output.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:147
LLVM_ABI Constant * createIRTypedAddress(FunctionType &FT, ExecutorAddr Addr)
Build a function pointer of FunctionType with the given constant address.
LLVM_ABI Expected< std::unique_ptr< JITCompileCallbackManager > > createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES, ExecutorAddr ErrorHandlerAddress)
Create a local compile callback manager.
LLVM_ABI void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
LLVM_ABI Error addFunctionPointerRelocationsToCurrentSymbol(jitlink::Symbol &Sym, jitlink::LinkGraph &G, MCDisassembler &Disassembler, MCInstrAnalysis &MIA)
Introduce relocations to Sym in its own definition if there are any pointers formed via PC-relative a...
LLVM_ABI GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
LLVM_ABI std::function< std::unique_ptr< IndirectStubsManager >()> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indirect stubs manager builder.
LLVM_ABI GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
LLVM_ABI GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module.
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
ArrayRef(const T &OneElt) -> ArrayRef< T >
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy