14#define DEBUG_TYPE "jitlink"
26 for (
auto &Sec :
G.sections()) {
28 if (Sec.blocks().empty() ||
32 auto &Seg = Segments[{Sec.getMemProt(), Sec.getMemLifetime()}];
33 for (
auto *
B : Sec.blocks())
35 Seg.ContentBlocks.push_back(
B);
37 Seg.ZeroFillBlocks.push_back(
B);
43 if (
LHS->getSection().getOrdinal() !=
RHS->getSection().getOrdinal())
44 return LHS->getSection().getOrdinal() <
RHS->getSection().getOrdinal();
45 if (
LHS->getAddress() !=
RHS->getAddress())
46 return LHS->getAddress() <
RHS->getAddress();
47 return LHS->getSize() <
RHS->getSize();
50 LLVM_DEBUG(
dbgs() <<
"Generated BasicLayout for " <<
G.getName() <<
":\n");
51 for (
auto &KV : Segments) {
52 auto &Seg = KV.second;
57 for (
auto *
B : Seg.ContentBlocks) {
59 Seg.ContentSize +=
B->getSize();
60 Seg.Alignment = std::max(Seg.Alignment,
Align(
B->getAlignment()));
63 uint64_t SegEndOffset = Seg.ContentSize;
64 for (
auto *
B : Seg.ZeroFillBlocks) {
66 SegEndOffset +=
B->getSize();
67 Seg.Alignment = std::max(Seg.Alignment,
Align(
B->getAlignment()));
69 Seg.ZeroFillSize = SegEndOffset - Seg.ContentSize;
72 dbgs() <<
" Seg " << KV.first
73 <<
": content-size=" <<
formatv(
"{0:x}", Seg.ContentSize)
74 <<
", zero-fill-size=" <<
formatv(
"{0:x}", Seg.ZeroFillSize)
75 <<
", align=" <<
formatv(
"{0:x}", Seg.Alignment.value()) <<
"\n";
86 auto &Seg = KV.second;
89 return make_error<StringError>(
"Segment alignment greater than page size",
103 for (
auto &KV : Segments) {
104 auto &Seg = KV.second;
106 assert(!(Seg.ContentBlocks.empty() && Seg.ZeroFillBlocks.empty()) &&
107 "Empty section recorded?");
109 for (
auto *
B : Seg.ContentBlocks) {
112 Seg.NextWorkingMemOffset =
alignToBlock(Seg.NextWorkingMemOffset, *
B);
115 B->setAddress(Seg.Addr);
116 Seg.Addr +=
B->getSize();
120 memcpy(Seg.WorkingMem + Seg.NextWorkingMemOffset,
B->getContent().data(),
122 B->setMutableContent(
123 {Seg.WorkingMem + Seg.NextWorkingMemOffset,
B->getSize()});
124 Seg.NextWorkingMemOffset +=
B->getSize();
127 for (
auto *
B : Seg.ZeroFillBlocks) {
131 B->setAddress(Seg.Addr);
132 Seg.Addr +=
B->getSize();
135 Seg.ContentBlocks.clear();
136 Seg.ZeroFillBlocks.clear();
151 "AllocGroup has changed. Section names below must be updated");
153 "__---.standard",
"__R--.standard",
"__-W-.standard",
"__RW-.standard",
154 "__--X.standard",
"__R-X.standard",
"__-WX.standard",
"__RWX.standard",
155 "__---.finalize",
"__R--.finalize",
"__-W-.finalize",
"__RW-.finalize",
156 "__--X.finalize",
"__R-X.finalize",
"__-WX.finalize",
"__RWX.finalize"};
158 auto G = std::make_unique<LinkGraph>(
"",
Triple(), 0,
163 for (
auto &KV : Segments) {
165 auto &Seg = KV.second;
168 "NoAlloc segments are not supported by SimpleSegmentAlloc");
171 AGSectionNames[
static_cast<unsigned>(AG.getMemProt()) |
172 static_cast<bool>(AG.getMemLifetime()) << 3];
174 auto &Sec = G->createSection(AGSectionName, AG.getMemProt());
175 Sec.setMemLifetime(AG.getMemLifetime());
177 if (Seg.ContentSize != 0) {
181 G->createMutableContentBlock(Sec, G->allocateBuffer(Seg.ContentSize),
182 NextAddr, Seg.ContentAlign.value(), 0);
183 ContentBlocks[AG] = &
B;
184 NextAddr += Seg.ContentSize;
191 [G = std::move(G), ContentBlocks = std::move(ContentBlocks),
192 OnCreated = std::move(OnCreated)](
195 OnCreated(Alloc.takeError());
198 std::move(ContentBlocks),
206 std::promise<MSVCPExpected<SimpleSegmentAlloc>> AllocP;
207 auto AllocF = AllocP.get_future();
208 Create(MemMgr, JD, std::move(Segments),
210 AllocP.set_value(std::move(Result));
222 auto I = ContentBlocks.find(AG);
223 if (
I != ContentBlocks.end()) {
224 auto &
B = *
I->second;
225 return {
B.getAddress(),
B.getAlreadyMutableContent()};
231 std::unique_ptr<LinkGraph>
G,
233 std::unique_ptr<JITLinkMemoryManager::InFlightAlloc>
Alloc)
243 : MemMgr(MemMgr),
G(&
G), BL(
std::
move(BL)),
244 StandardSegments(
std::
move(StandardSegments)),
245 FinalizationSegments(
std::
move(FinalizationSegments)) {}
248 assert(!G &&
"InFlight alloc neither abandoned nor finalized");
254 if (
auto Err = applyProtections()) {
255 OnFinalized(std::move(Err));
260 auto DeallocActions = runFinalizeActions(G->
allocActions());
261 if (!DeallocActions) {
262 OnFinalized(DeallocActions.takeError());
280 OnFinalized(MemMgr.createFinalizedAlloc(std::move(StandardSegments),
281 std::move(*DeallocActions)));
298 OnAbandoned(std::move(Err));
302 Error applyProtections() {
304 const auto &AG = KV.first;
305 auto &Seg = KV.second;
307 auto Prot = toSysMemoryProtectionFlags(AG.getMemProt());
310 alignTo(Seg.ContentSize + Seg.ZeroFillSize, MemMgr.PageSize);
320 InProcessMemoryManager &MemMgr;
330 return std::make_unique<InProcessMemoryManager>(*PageSize);
332 return PageSize.takeError();
340 OnAllocated(make_error<StringError>(
"Page size is not a power of 2",
349 auto SegsSizes = BL.getContiguousPageBasedLayoutSizes(PageSize);
351 OnAllocated(SegsSizes.takeError());
357 if (SegsSizes->total() > std::numeric_limits<size_t>::max()) {
358 OnAllocated(make_error<JITLinkError>(
359 "Total requested size " +
formatv(
"{0:x}", SegsSizes->total()) +
360 " for graph " +
G.getName() +
" exceeds address space"));
392 StandardSegsMem = {Slab.
base(),
393 static_cast<size_t>(SegsSizes->StandardSegs)};
394 FinalizeSegsMem = {(
void *)((
char *)Slab.
base() + SegsSizes->StandardSegs),
395 static_cast<size_t>(SegsSizes->FinalizeSegs)};
402 dbgs() <<
"InProcessMemoryManager allocated:\n";
403 if (SegsSizes->StandardSegs)
404 dbgs() <<
formatv(
" [ {0:x16} -- {1:x16} ]", NextStandardSegAddr,
406 <<
" to stardard segs\n";
408 dbgs() <<
" no standard segs\n";
409 if (SegsSizes->FinalizeSegs)
410 dbgs() <<
formatv(
" [ {0:x16} -- {1:x16} ]", NextFinalizeSegAddr,
412 <<
" to finalize segs\n";
414 dbgs() <<
" no finalize segs\n";
418 for (
auto &KV : BL.segments()) {
420 auto &Seg = KV.second;
423 ? NextStandardSegAddr
424 : NextFinalizeSegAddr;
426 Seg.WorkingMem = SegAddr.toPtr<
char *>();
429 SegAddr +=
alignTo(Seg.ContentSize + Seg.ZeroFillSize, PageSize);
432 if (
auto Err = BL.apply()) {
433 OnAllocated(std::move(Err));
437 OnAllocated(std::make_unique<IPInFlightAlloc>(*
this,
G, std::move(BL),
438 std::move(StandardSegsMem),
439 std::move(FinalizeSegsMem)));
444 std::vector<sys::MemoryBlock> StandardSegmentsList;
445 std::vector<std::vector<orc::shared::WrapperFunctionCall>> DeallocActionsList;
448 std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
449 for (
auto &
Alloc : Allocs) {
450 auto *FA =
Alloc.release().toPtr<FinalizedAllocInfo *>();
451 StandardSegmentsList.push_back(std::move(FA->StandardSegments));
452 DeallocActionsList.push_back(std::move(FA->DeallocActions));
453 FA->~FinalizedAllocInfo();
454 FinalizedAllocInfos.Deallocate(FA);
460 while (!DeallocActionsList.empty()) {
461 auto &DeallocActions = DeallocActionsList.back();
462 auto &StandardSegments = StandardSegmentsList.back();
465 while (!DeallocActions.empty()) {
466 if (
auto Err = DeallocActions.back().runWithSPSRetErrorMerged())
467 DeallocErr =
joinErrors(std::move(DeallocErr), std::move(Err));
468 DeallocActions.pop_back();
475 DeallocActionsList.pop_back();
476 StandardSegmentsList.pop_back();
479 OnDeallocated(std::move(DeallocErr));
483InProcessMemoryManager::createFinalizedAlloc(
485 std::vector<orc::shared::WrapperFunctionCall> DeallocActions) {
486 std::lock_guard<std::mutex> Lock(FinalizedAllocsMutex);
487 auto *FA = FinalizedAllocInfos.Allocate<FinalizedAllocInfo>();
488 new (FA) FinalizedAllocInfo(
489 {std::move(StandardSegments), std::move(DeallocActions)});
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_LIKELY(EXPR)
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
Provides a library for accessing information about this process and other processes on the operating ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
StringRef - Represent a constant reference to a string, i.e.
Triple - Helper class for working with autoconf configuration names.
BasicLayout simplifies the implementation of JITLinkMemoryManagers.
orc::shared::AllocActions & graphAllocActions()
Returns a reference to the AllocActions in the graph.
Error apply()
Apply the layout to the graph.
Expected< ContiguousPageBasedLayoutSizes > getContiguousPageBasedLayoutSizes(uint64_t PageSize)
Returns the total number of required to allocate all segments (with each segment padded out to page s...
iterator_range< SegmentMap::iterator > segments()
Returns an iterator over the segments of the layout.
BasicLayout(LinkGraph &G)
An Addressable with content and edges.
void abandon(OnAbandonedFunction OnAbandoned) override
Called prior to finalization if the allocation should be abandoned.
IPInFlightAlloc(InProcessMemoryManager &MemMgr, LinkGraph &G, BasicLayout BL, sys::MemoryBlock StandardSegments, sys::MemoryBlock FinalizationSegments)
void finalize(OnFinalizedFunction OnFinalized) override
Called to transfer working memory to the target and apply finalization.
A JITLinkMemoryManager that allocates in-process memory.
static Expected< std::unique_ptr< InProcessMemoryManager > > Create()
Attempts to auto-detect the host page size.
void deallocate(std::vector< FinalizedAlloc > Alloc, OnDeallocatedFunction OnDeallocated) override
Deallocate a list of allocation objects.
void allocate(const JITLinkDylib *JD, LinkGraph &G, OnAllocatedFunction OnAllocated) override
Start the allocation process.
Represents a finalized allocation.
Represents an allocation which has not been finalized yet.
Manages allocations of JIT memory.
virtual void allocate(const JITLinkDylib *JD, LinkGraph &G, OnAllocatedFunction OnAllocated)=0
Start the allocation process.
virtual ~JITLinkMemoryManager()
orc::shared::AllocActions & allocActions()
Accessor for the AllocActions object for this graph.
A utility class for making simple allocations using JITLinkMemoryManager.
SimpleSegmentAlloc(SimpleSegmentAlloc &&)
SegmentInfo getSegInfo(orc::AllocGroup AG)
Returns the SegmentInfo for the given group.
SimpleSegmentAlloc & operator=(SimpleSegmentAlloc &&)
static void Create(JITLinkMemoryManager &MemMgr, const JITLinkDylib *JD, SegmentMap Segments, OnCreatedFunction OnCreated)
A pair of memory protections and allocation policies.
static constexpr unsigned NumGroups
Represents an address in the executor process.
uint64_t getValue() const
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
This class encapsulates the notion of a memory block which has an address and a size.
size_t allocatedSize() const
The size as it was allocated.
static std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC)
This method allocates a block of memory that is suitable for loading dynamically generated code (e....
static void InvalidateInstructionCache(const void *Addr, size_t Len)
InvalidateInstructionCache - Before the JIT can run a block of code that has been emitted it must inv...
static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags)
This method sets the protection flags for a block of memory to the state specified by /p Flags.
static Expected< unsigned > getPageSize()
Get the process's page size.
unique_function is a type-erasing functor similar to std::function.
uint64_t alignToBlock(uint64_t Addr, const Block &B)
std::vector< AllocActionCallPair > AllocActions
A vector of allocation actions to be run for this allocation.
@ NoAlloc
NoAlloc memory should not be allocated by the JITLinkMemoryManager at all.
@ Standard
Standard memory should be allocated by the allocator and then deallocated when the deallocate method ...
This is an optimization pass for GlobalISel generic memory operations.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
void sort(IteratorTy Start, IteratorTy End)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Implement std::hash so that hash_code can be used in STL containers.
This struct is a compact representation of a valid (non-zero power of two) alignment.
A convenience class that further groups segments based on memory deallocation policy.
Describes the segment working memory and executor address.