LLVM 24.0.0git
SimpleExecutorMemoryManager.cpp
Go to the documentation of this file.
1//===- SimpleExecuorMemoryManagare.cpp - Simple executor-side memory mgmt -===//
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
11#include "llvm/ADT/ScopeExit.h"
15
16#define DEBUG_TYPE "orc"
17
18namespace llvm {
19namespace orc {
20namespace rt_bootstrap {
21
23 assert(Slabs.empty() && "shutdown not called?");
24}
25
27 std::error_code EC;
30 if (EC)
31 return errorCodeToError(EC);
32 std::lock_guard<std::mutex> Lock(M);
33 assert(!Slabs.count(MB.base()) && "Duplicate allocation addr");
34 Slabs[MB.base()].Size = Size;
35 return ExecutorAddr::fromPtr(MB.base());
36}
37
40 if (FR.Segments.empty()) {
41 if (FR.Actions.empty())
42 return make_error<StringError>("Finalization request is empty",
44 else
45 return make_error<StringError>("Finalization actions attached to empty "
46 "finalization request",
48 }
49
50 ExecutorAddrRange RR(FR.Segments.front().Addr, FR.Segments.front().Addr);
51
52 std::vector<sys::MemoryBlock> MBsToReset;
53 llvm::scope_exit ResetMBs([&]() {
54 for (auto &MB : MBsToReset)
58 RR.size());
59 });
60
61 // Copy content and apply permissions.
62 for (auto &Seg : FR.Segments) {
63 RR.Start = std::min(RR.Start, Seg.Addr);
64 RR.End = std::max(RR.End, Seg.Addr + Seg.Size);
65
66 // Check segment ranges.
67 if (LLVM_UNLIKELY(Seg.Size < Seg.Content.size()))
69 formatv("Segment {0:x} content size ({1:x} bytes) "
70 "exceeds segment size ({2:x} bytes)",
71 Seg.Addr.getValue(), Seg.Content.size(), Seg.Size),
73 ExecutorAddr SegEnd = Seg.Addr + ExecutorAddrDiff(Seg.Size);
74 if (LLVM_UNLIKELY(Seg.Addr < RR.Start || SegEnd > RR.End))
76 formatv("Segment {0:x} -- {1:x} crosses boundary of "
77 "allocation {2:x} -- {3:x}",
78 Seg.Addr, SegEnd, RR.Start, RR.End),
80
81 char *Mem = Seg.Addr.toPtr<char *>();
82 if (!Seg.Content.empty())
83 memcpy(Mem, Seg.Content.data(), Seg.Content.size());
84 memset(Mem + Seg.Content.size(), 0, Seg.Size - Seg.Content.size());
85 assert(Seg.Size <= std::numeric_limits<size_t>::max());
86
87 sys::MemoryBlock MB(Mem, Seg.Size);
89 MB, toSysMemoryProtectionFlags(Seg.RAG.Prot)))
90 return errorCodeToError(EC);
91
92 MBsToReset.push_back(MB);
93
94 if ((Seg.RAG.Prot & MemProt::Exec) == MemProt::Exec)
96 }
97
98 auto DeallocActions = runFinalizeActions(FR.Actions);
99 if (!DeallocActions)
100 return DeallocActions.takeError();
101
102 {
103 std::lock_guard<std::mutex> Lock(M);
104 auto Region = createRegionInfo(RR, "In initialize");
105 if (!Region)
106 return Region.takeError();
107 Region->DeallocActions = std::move(*DeallocActions);
108 }
109
110 // Successful initialization.
111 ResetMBs.release();
112
113 return RR.Start;
114}
115
117 const std::vector<ExecutorAddr> &InitKeys) {
118 Error Err = Error::success();
119
120 for (auto &KeyAddr : llvm::reverse(InitKeys)) {
121 std::vector<shared::WrapperFunctionCall> DeallocActions;
122 {
123 std::scoped_lock<std::mutex> Lock(M);
124 auto Slab = getSlabInfo(KeyAddr, "In deinitialize");
125 if (!Slab) {
126 Err = joinErrors(std::move(Err), Slab.takeError());
127 continue;
128 }
129
130 auto RI = getRegionInfo(*Slab, KeyAddr, "In deinitialize");
131 if (!RI) {
132 Err = joinErrors(std::move(Err), RI.takeError());
133 continue;
134 }
135
136 DeallocActions = std::move(RI->DeallocActions);
137 }
138
139 Err = joinErrors(std::move(Err),
140 runDeallocActions(std::move(DeallocActions)));
141 }
142
143 return Err;
144}
145
147 const std::vector<ExecutorAddr> &Bases) {
148 Error Err = Error::success();
149
150 // TODO: Prohibit new initializations within the slabs being removed?
151 for (auto &Base : llvm::reverse(Bases)) {
152 std::vector<shared::WrapperFunctionCall> DeallocActions;
154
155 {
156 std::scoped_lock<std::mutex> Lock(M);
157
158 auto SlabI = Slabs.find(Base.toPtr<void *>());
159 if (SlabI == Slabs.end()) {
160 Err = joinErrors(
161 std::move(Err),
162 make_error<StringError>("In release, " + formatv("{0:x}", Base) +
163 " is not part of any reserved "
164 "address range",
166 continue;
167 }
168
169 auto &Slab = SlabI->second;
170
171 for (auto &[Addr, Region] : Slab.Regions)
172 llvm::copy(Region.DeallocActions, back_inserter(DeallocActions));
173
174 MB = {Base.toPtr<void *>(), Slab.Size};
175
176 Slabs.erase(SlabI);
177 }
178
179 Err = joinErrors(std::move(Err), runDeallocActions(DeallocActions));
180 if (auto EC = sys::Memory::releaseMappedMemory(MB))
181 Err = joinErrors(std::move(Err), errorCodeToError(EC));
182 }
183
184 return Err;
185}
186
188
189 // TODO: Prevent new allocations during shutdown.
190 std::vector<ExecutorAddr> Bases;
191 {
192 std::scoped_lock<std::mutex> Lock(M);
193 for (auto &[Base, Slab] : Slabs)
194 Bases.push_back(ExecutorAddr::fromPtr(Base));
195 }
196
197 return release(Bases);
198}
199
204 ExecutorAddr::fromPtr(&reserveWrapper);
206 ExecutorAddr::fromPtr(&initializeWrapper);
208 ExecutorAddr::fromPtr(&deinitializeWrapper);
210 ExecutorAddr::fromPtr(&releaseWrapper);
211
212 {
213 // Also provide SimpleNativeMemoryMap symbols for compatibility.
214 // FIXME: We should codify a "simple" memory manager interface and make
215 // SimpleExecutorMemoryManager its LLVM-based implementation, and
216 // SimpleNativeMemoryMap its ORC-runtime implementation.
217 namespace sps_ci = rt::sps_ci;
218 M[sps_ci::SimpleNativeMemoryMapInstanceName] = ExecutorAddr::fromPtr(this);
219 M[sps_ci::MemMgrReserve::Name] = ExecutorAddr::fromPtr(reserveWrapper);
220 M[sps_ci::MemMgrInitialize::Name] =
221 ExecutorAddr::fromPtr(initializeWrapper);
222 M[sps_ci::MemMgrDeinitialize::Name] =
223 ExecutorAddr::fromPtr(deinitializeWrapper);
224 M[sps_ci::MemMgrRelease::Name] = ExecutorAddr::fromPtr(releaseWrapper);
225 }
226}
227
229SimpleExecutorMemoryManager::getSlabInfo(ExecutorAddr A, StringRef Context) {
230 auto MakeBadSlabError = [&]() {
232 Context + ", address " + formatv("{0:x}", A) +
233 " is not part of any reserved address range",
235 };
236
237 auto I = Slabs.upper_bound(A.toPtr<void *>());
238 if (I == Slabs.begin())
239 return MakeBadSlabError();
240 --I;
241 if (!ExecutorAddrRange(ExecutorAddr::fromPtr(I->first), I->second.Size)
242 .contains(A))
243 return MakeBadSlabError();
244
245 return I->second;
246}
247
249SimpleExecutorMemoryManager::getSlabInfo(ExecutorAddrRange R,
250 StringRef Context) {
251 auto MakeBadSlabError = [&]() {
253 Context + ", range " + formatv("{0:x}", R) +
254 " is not part of any reserved address range",
256 };
257
258 auto I = Slabs.upper_bound(R.Start.toPtr<void *>());
259 if (I == Slabs.begin())
260 return MakeBadSlabError();
261 --I;
262 if (!ExecutorAddrRange(ExecutorAddr::fromPtr(I->first), I->second.Size)
263 .contains(R))
264 return MakeBadSlabError();
265
266 return I->second;
267}
268
269Expected<SimpleExecutorMemoryManager::RegionInfo &>
270SimpleExecutorMemoryManager::createRegionInfo(ExecutorAddrRange R,
271 StringRef Context) {
272
273 auto Slab = getSlabInfo(R, Context);
274 if (!Slab)
275 return Slab.takeError();
276
277 auto MakeBadRegionError = [&](ExecutorAddrRange Other, bool Prev) {
278 return make_error<StringError>(Context + ", region " + formatv("{0:x}", R) +
279 " overlaps " +
280 (Prev ? "previous" : "following") +
281 " region " + formatv("{0:x}", Other),
283 };
284
285 auto I = Slab->Regions.upper_bound(R.Start);
286 if (I != Slab->Regions.begin()) {
287 auto J = std::prev(I);
288 ExecutorAddrRange PrevRange(J->first, J->second.Size);
289 if (PrevRange.overlaps(R))
290 return MakeBadRegionError(PrevRange, true);
291 }
292 if (I != Slab->Regions.end()) {
293 ExecutorAddrRange NextRange(I->first, I->second.Size);
294 if (NextRange.overlaps(R))
295 return MakeBadRegionError(NextRange, false);
296 }
297
298 auto &RInfo = Slab->Regions[R.Start];
299 RInfo.Size = R.size();
300 return RInfo;
301}
302
303Expected<SimpleExecutorMemoryManager::RegionInfo &>
304SimpleExecutorMemoryManager::getRegionInfo(SlabInfo &Slab, ExecutorAddr A,
305 StringRef Context) {
306 auto I = Slab.Regions.find(A);
307 if (I == Slab.Regions.end())
309 Context + ", address " + formatv("{0:x}", A) +
310 " does not correspond to the start of any initialized region",
312
313 return I->second;
314}
315
316Expected<SimpleExecutorMemoryManager::RegionInfo &>
317SimpleExecutorMemoryManager::getRegionInfo(ExecutorAddr A, StringRef Context) {
318 auto Slab = getSlabInfo(A, Context);
319 if (!Slab)
320 return Slab.takeError();
321
322 return getRegionInfo(*Slab, A, Context);
323}
324
325llvm::orc::shared::CWrapperFunctionBuffer
326SimpleExecutorMemoryManager::reserveWrapper(const char *ArgData,
327 size_t ArgSize) {
328 return shared::WrapperFunction<rt::sps_ci::MemMgrReserve::SPSSig>::handle(
329 ArgData, ArgSize,
332 .release();
333}
334
335llvm::orc::shared::CWrapperFunctionBuffer
336SimpleExecutorMemoryManager::initializeWrapper(const char *ArgData,
337 size_t ArgSize) {
338 return shared::WrapperFunction<rt::sps_ci::MemMgrInitialize::SPSSig>::handle(
339 ArgData, ArgSize,
342 .release();
343}
344
345llvm::orc::shared::CWrapperFunctionBuffer
346SimpleExecutorMemoryManager::deinitializeWrapper(const char *ArgData,
347 size_t ArgSize) {
348 return shared::WrapperFunction<rt::sps_ci::MemMgrDeinitialize::SPSSig>::
349 handle(ArgData, ArgSize,
352 .release();
353}
354
355llvm::orc::shared::CWrapperFunctionBuffer
356SimpleExecutorMemoryManager::releaseWrapper(const char *ArgData,
357 size_t ArgSize) {
358 return shared::WrapperFunction<rt::sps_ci::MemMgrRelease::SPSSig>::handle(
359 ArgData, ArgSize,
362 .release();
363}
364
365} // namespace rt_bootstrap
366} // end namespace orc
367} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:344
#define I(x, y, z)
Definition MD5.cpp:57
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
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
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:128
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Represents an address in the executor process.
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
std::enable_if_t< std::is_pointer< T >::value, T > toPtr(WrapFn &&Wrap=WrapFn()) const
Cast this ExecutorAddr to a pointer of the given type.
Error deinitialize(const std::vector< ExecutorAddr > &InitKeys)
Error release(const std::vector< ExecutorAddr > &Bases)
Expected< ExecutorAddr > initialize(tpctypes::FinalizeRequest &FR)
void addBootstrapSymbols(StringMap< ExecutorAddr > &M) override
This class encapsulates the notion of a memory block which has an address and a size.
Definition Memory.h:33
static LLVM_ABI 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 LLVM_ABI std::error_code releaseMappedMemory(MemoryBlock &Block)
This method releases a block of memory that was allocated with the allocateMappedMemory method.
static LLVM_ABI 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 LLVM_ABI 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....
LLVM_ABI const char * SimpleExecutorMemoryManagerInitializeWrapperName
LLVM_ABI const char * SimpleExecutorMemoryManagerReserveWrapperName
LLVM_ABI const char * SimpleExecutorMemoryManagerReleaseWrapperName
LLVM_ABI const char * SimpleExecutorMemoryManagerDeinitializeWrapperName
LLVM_ABI const char * SimpleExecutorMemoryManagerInstanceName
MethodWrapperHandler< RetT, ClassT, ArgTs... > makeMethodWrapperHandler(RetT(ClassT::*Method)(ArgTs...))
Create a MethodWrapperHandler object from the given method pointer.
uint64_t ExecutorAddrDiff
sys::Memory::ProtectionFlags toSysMemoryProtectionFlags(MemProt MP)
Convert a MemProt value to a corresponding sys::Memory::ProtectionFlags value.
Definition MemoryFlags.h:44
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)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
Represents an address range in the exceutor process.
ExecutorAddrDiff size() const
bool contains(ExecutorAddr Addr) const
std::vector< SegFinalizeRequest > Segments