LLVM 19.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
10#include "llvm/ADT/STLExtras.h"
13#include "llvm/IR/IRBuilder.h"
16#include "llvm/Support/Format.h"
19#include <sstream>
20
21#define DEBUG_TYPE "orc"
22
23using namespace llvm;
24using namespace llvm::orc;
25
26namespace {
27
28class CompileCallbackMaterializationUnit : public orc::MaterializationUnit {
29public:
30 using CompileFunction = JITCompileCallbackManager::CompileFunction;
31
32 CompileCallbackMaterializationUnit(SymbolStringPtr Name,
33 CompileFunction Compile)
34 : MaterializationUnit(Interface(
36 Name(std::move(Name)), Compile(std::move(Compile)) {}
37
38 StringRef getName() const override { return "<Compile Callbacks>"; }
39
40private:
41 void materialize(std::unique_ptr<MaterializationResponsibility> R) override {
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
54 CompileFunction Compile;
55};
56
57} // namespace
58
59namespace llvm {
60namespace orc {
61
63void IndirectStubsManager::anchor() {}
64
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;
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
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),
98 return ErrorHandlerAddress;
99 } else
100 Name = I->second;
101 }
102
103 if (auto Sym =
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
119 ExecutorAddr ErrorHandlerAddress) {
120 switch (T.getArch()) {
121 default:
122 return make_error<StringError>(
123 std::string("No callback manager available for ") + T.str(),
125 case Triple::aarch64:
126 case Triple::aarch64_32: {
128 return CCMgrT::Create(ES, ErrorHandlerAddress);
129 }
130
131 case Triple::x86: {
133 return CCMgrT::Create(ES, ErrorHandlerAddress);
134 }
135
136 case Triple::loongarch64: {
138 return CCMgrT::Create(ES, ErrorHandlerAddress);
139 }
140
141 case Triple::mips: {
143 return CCMgrT::Create(ES, ErrorHandlerAddress);
144 }
145 case Triple::mipsel: {
147 return CCMgrT::Create(ES, ErrorHandlerAddress);
148 }
149
150 case Triple::mips64:
151 case Triple::mips64el: {
153 return CCMgrT::Create(ES, ErrorHandlerAddress);
154 }
155
156 case Triple::riscv64: {
158 return CCMgrT::Create(ES, ErrorHandlerAddress);
159 }
160
161 case Triple::x86_64: {
162 if (T.getOS() == Triple::OSType::Win32) {
164 return CCMgrT::Create(ES, ErrorHandlerAddress);
165 } else {
167 return CCMgrT::Create(ES, ErrorHandlerAddress);
168 }
169 }
170
171 }
172}
173
174std::function<std::unique_ptr<IndirectStubsManager>()>
176 switch (T.getArch()) {
177 default:
178 return [](){
179 return std::make_unique<
181 };
182
183 case Triple::aarch64:
185 return [](){
186 return std::make_unique<
188 };
189
190 case Triple::x86:
191 return [](){
192 return std::make_unique<
194 };
195
197 return []() {
198 return std::make_unique<
200 };
201
202 case Triple::mips:
203 return [](){
204 return std::make_unique<
206 };
207
208 case Triple::mipsel:
209 return [](){
210 return std::make_unique<
212 };
213
214 case Triple::mips64:
215 case Triple::mips64el:
216 return [](){
217 return std::make_unique<
219 };
220
221 case Triple::riscv64:
222 return []() {
223 return std::make_unique<
225 };
226
227 case Triple::x86_64:
228 if (T.getOS() == Triple::OSType::Win32) {
229 return [](){
230 return std::make_unique<
232 };
233 } else {
234 return [](){
235 return std::make_unique<
237 };
238 }
239
240 }
241}
242
244 Constant *AddrIntVal =
245 ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr.getValue());
246 Constant *AddrPtrVal =
247 ConstantExpr::getIntToPtr(AddrIntVal, PointerType::get(&FT, 0));
248 return AddrPtrVal;
249}
250
252 const Twine &Name, Constant *Initializer) {
253 auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
254 Initializer, Name, nullptr,
256 IP->setVisibility(GlobalValue::HiddenVisibility);
257 return IP;
258}
259
260void makeStub(Function &F, Value &ImplPointer) {
261 assert(F.isDeclaration() && "Can't turn a definition into a stub.");
262 assert(F.getParent() && "Function isn't in a module.");
263 Module &M = *F.getParent();
264 BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
265 IRBuilder<> Builder(EntryBlock);
266 LoadInst *ImplAddr = Builder.CreateLoad(F.getType(), &ImplPointer);
267 std::vector<Value*> CallArgs;
268 for (auto &A : F.args())
269 CallArgs.push_back(&A);
270 CallInst *Call = Builder.CreateCall(F.getFunctionType(), ImplAddr, CallArgs);
271 Call->setTailCall();
272 Call->setAttributes(F.getAttributes());
273 if (F.getReturnType()->isVoidTy())
274 Builder.CreateRetVoid();
275 else
276 Builder.CreateRet(Call);
277}
278
279std::vector<GlobalValue *> SymbolLinkagePromoter::operator()(Module &M) {
280 std::vector<GlobalValue *> PromotedGlobals;
281
282 for (auto &GV : M.global_values()) {
283 bool Promoted = true;
284
285 // Rename if necessary.
286 if (!GV.hasName())
287 GV.setName("__orc_anon." + Twine(NextId++));
288 else if (GV.getName().starts_with("\01L"))
289 GV.setName("__" + GV.getName().substr(1) + "." + Twine(NextId++));
290 else if (GV.hasLocalLinkage())
291 GV.setName("__orc_lcl." + GV.getName() + "." + Twine(NextId++));
292 else
293 Promoted = false;
294
295 if (GV.hasLocalLinkage()) {
296 GV.setLinkage(GlobalValue::ExternalLinkage);
297 GV.setVisibility(GlobalValue::HiddenVisibility);
298 Promoted = true;
299 }
300 GV.setUnnamedAddr(GlobalValue::UnnamedAddr::None);
301
302 if (Promoted)
303 PromotedGlobals.push_back(&GV);
304 }
305
306 return PromotedGlobals;
307}
308
310 ValueToValueMapTy *VMap) {
311 Function *NewF =
312 Function::Create(cast<FunctionType>(F.getValueType()),
313 F.getLinkage(), F.getName(), &Dst);
314 NewF->copyAttributesFrom(&F);
315
316 if (VMap) {
317 (*VMap)[&F] = NewF;
318 auto NewArgI = NewF->arg_begin();
319 for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
320 ++ArgI, ++NewArgI)
321 (*VMap)[&*ArgI] = &*NewArgI;
322 }
323
324 return NewF;
325}
326
328 ValueToValueMapTy *VMap) {
329 GlobalVariable *NewGV = new GlobalVariable(
330 Dst, GV.getValueType(), GV.isConstant(),
331 GV.getLinkage(), nullptr, GV.getName(), nullptr,
333 NewGV->copyAttributesFrom(&GV);
334 if (VMap)
335 (*VMap)[&GV] = NewGV;
336 return NewGV;
337}
338
340 ValueToValueMapTy &VMap) {
341 assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
342 auto *NewA = GlobalAlias::create(OrigA.getValueType(),
344 OrigA.getLinkage(), OrigA.getName(), &Dst);
345 NewA->copyAttributesFrom(&OrigA);
346 VMap[&OrigA] = NewA;
347 return NewA;
348}
349
352 MCDisassembler &Disassembler,
353 MCInstrAnalysis &MIA) {
354 // AArch64 appears to already come with the necessary relocations. Among other
355 // architectures, only x86_64 is currently implemented here.
356 if (G.getTargetTriple().getArch() != Triple::x86_64)
357 return Error::success();
358
359 raw_null_ostream CommentStream;
360 auto &STI = Disassembler.getSubtargetInfo();
361
362 // Determine the function bounds
363 auto &B = Sym.getBlock();
364 assert(!B.isZeroFill() && "expected content block");
365 auto SymAddress = Sym.getAddress();
366 auto SymStartInBlock =
367 (const uint8_t *)B.getContent().data() + Sym.getOffset();
368 auto SymSize = Sym.getSize() ? Sym.getSize() : B.getSize() - Sym.getOffset();
369 auto Content = ArrayRef(SymStartInBlock, SymSize);
370
371 LLVM_DEBUG(dbgs() << "Adding self-relocations to " << Sym.getName() << "\n");
372
373 SmallDenseSet<uintptr_t, 8> ExistingRelocations;
374 for (auto &E : B.edges()) {
375 if (E.isRelocation())
376 ExistingRelocations.insert(E.getOffset());
377 }
378
379 size_t I = 0;
380 while (I < Content.size()) {
381 MCInst Instr;
382 uint64_t InstrSize = 0;
383 uint64_t InstrStart = SymAddress.getValue() + I;
384 auto DecodeStatus = Disassembler.getInstruction(
385 Instr, InstrSize, Content.drop_front(I), InstrStart, CommentStream);
387 LLVM_DEBUG(dbgs() << "Aborting due to disassembly failure at address "
388 << InstrStart);
389 return make_error<StringError>(
390 formatv("failed to disassemble at address {0:x16}", InstrStart),
392 }
393 // Advance to the next instruction.
394 I += InstrSize;
395
396 // Check for a PC-relative address equal to the symbol itself.
397 auto PCRelAddr =
398 MIA.evaluateMemoryOperandAddress(Instr, &STI, InstrStart, InstrSize);
399 if (!PCRelAddr || *PCRelAddr != SymAddress.getValue())
400 continue;
401
402 auto RelocOffInInstr =
403 MIA.getMemoryOperandRelocationOffset(Instr, InstrSize);
404 if (!RelocOffInInstr || InstrSize - *RelocOffInInstr != 4) {
405 LLVM_DEBUG(dbgs() << "Skipping unknown self-relocation at "
406 << InstrStart);
407 continue;
408 }
409
410 auto RelocOffInBlock = orc::ExecutorAddr(InstrStart) + *RelocOffInInstr -
411 SymAddress + Sym.getOffset();
412 if (ExistingRelocations.contains(RelocOffInBlock))
413 continue;
414
415 LLVM_DEBUG(dbgs() << "Adding delta32 self-relocation at " << InstrStart);
416 B.addEdge(jitlink::x86_64::Delta32, RelocOffInBlock, Sym, /*Addend=*/-4);
417 }
418 return Error::success();
419}
420
421} // End namespace orc.
422} // End namespace llvm.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
T Content
uint64_t Addr
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:198
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2126
This is an important base class in LLVM.
Definition: Constant.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Class to represent function types.
Definition: DerivedTypes.h:103
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:162
arg_iterator arg_begin()
Definition: Function.h:810
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:781
const Constant * getAliasee() const
Definition: GlobalAlias.h:84
static 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:518
LinkageTypes getLinkage() const
Definition: GlobalValue.h:545
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
Type * getValueType() const
Definition: GlobalValue.h:296
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:482
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:1089
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1789
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition: IRBuilder.h:1084
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2395
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2649
An instruction for reading from memory.
Definition: Instructions.h:184
Superclass for all disassemblers.
const MCSubtargetInfo & getSubtargetInfo() const
DecodeStatus
Ternary decode status.
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:184
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:65
Class to represent pointers.
Definition: DerivedTypes.h:646
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:679
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ loongarch64
Definition: Triple.h:62
@ mips64el
Definition: Triple.h:67
@ aarch64_32
Definition: Triple.h:53
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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:129
static IntegerType * getInt64Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:185
An ExecutionSession represents a running JIT program.
Definition: Core.h:1425
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1563
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1482
void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1786
Represents an address in the executor process.
ExecutorAddr executeCompileCallback(ExecutorAddr TrampolineAddr)
Execute the callback for the given trampoline id.
Expected< ExecutorAddr > getCompileCallback(CompileFunction Compile)
Reserve a compile callback.
std::function< ExecutorAddr()> CompileFunction
Represents a JIT'd dynamic library.
Definition: Core.h:989
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1911
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,...
Definition: Core.h:693
virtual StringRef getName() const =0
Return the name of this materialization unit.
virtual void materialize(std::unique_ptr< MaterializationResponsibility > R)=0
Implementations of this method should materialize all symbols in the materialzation unit,...
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.
Definition: raw_ostream.h:723
#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:166
Constant * createIRTypedAddress(FunctionType &FT, ExecutorAddr Addr)
Build a function pointer of FunctionType with the given constant address.
Expected< std::unique_ptr< JITCompileCallbackManager > > createLocalCompileCallbackManager(const Triple &T, ExecutionSession &ES, ExecutorAddr ErrorHandlerAddress)
Create a local compile callback manager.
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
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...
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
Definition: Core.h:124
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
std::function< std::unique_ptr< IndirectStubsManager >()> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indirect stubs manager builder.
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
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.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:90
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:749