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
13
14#include "llvm/ADT/ScopeExit.h"
17
18#define DEBUG_TYPE "orc"
19
20namespace llvm {
21namespace orc {
22namespace rt_bootstrap {
23
25 assert(Slabs.empty() && "shutdown not called?");
26}
27
29 std::error_code EC;
32 if (EC)
33 return errorCodeToError(EC);
34 std::lock_guard<std::mutex> Lock(M);
35 assert(!Slabs.count(MB.base()) && "Duplicate allocation addr");
36 Slabs[MB.base()].Size = Size;
37 return ExecutorAddr::fromPtr(MB.base());
38}
39
42 if (FR.Segments.empty()) {
43 if (FR.Actions.empty())
44 return make_error<StringError>("Finalization request is empty",
46 else
47 return make_error<StringError>("Finalization actions attached to empty "
48 "finalization request",
50 }
51
52 ExecutorAddrRange RR(FR.Segments.front().Addr, FR.Segments.front().Addr);
53
54 std::vector<sys::MemoryBlock> MBsToReset;
55 llvm::scope_exit ResetMBs([&]() {
56 for (auto &MB : MBsToReset)
60 RR.size());
61 });
62
63 // Copy content and apply permissions.
64 for (auto &Seg : FR.Segments) {
65 RR.Start = std::min(RR.Start, Seg.Addr);
66 RR.End = std::max(RR.End, Seg.Addr + Seg.Size);
67
68 // Check segment ranges.
69 if (LLVM_UNLIKELY(Seg.Size < Seg.Content.size()))
71 formatv("Segment {0:x} content size ({1:x} bytes) "
72 "exceeds segment size ({2:x} bytes)",
73 Seg.Addr.getValue(), Seg.Content.size(), Seg.Size),
75 ExecutorAddr SegEnd = Seg.Addr + ExecutorAddrDiff(Seg.Size);
76 if (LLVM_UNLIKELY(Seg.Addr < RR.Start || SegEnd > RR.End))
78 formatv("Segment {0:x} -- {1:x} crosses boundary of "
79 "allocation {2:x} -- {3:x}",
80 Seg.Addr, SegEnd, RR.Start, RR.End),
82
83 char *Mem = Seg.Addr.toPtr<char *>();
84 if (!Seg.Content.empty())
85 memcpy(Mem, Seg.Content.data(), Seg.Content.size());
86 memset(Mem + Seg.Content.size(), 0, Seg.Size - Seg.Content.size());
87 assert(Seg.Size <= std::numeric_limits<size_t>::max());
88
89 sys::MemoryBlock MB(Mem, Seg.Size);
91 MB, toSysMemoryProtectionFlags(Seg.RAG.Prot)))
92 return errorCodeToError(EC);
93
94 MBsToReset.push_back(MB);
95
96 if ((Seg.RAG.Prot & MemProt::Exec) == MemProt::Exec)
98 }
99
100 auto DeallocActions = runFinalizeActions(FR.Actions);
101 if (!DeallocActions)
102 return DeallocActions.takeError();
103
104 {
105 std::lock_guard<std::mutex> Lock(M);
106 auto Region = createRegionInfo(RR, "In initialize");
107 if (!Region)
108 return Region.takeError();
109 Region->DeallocActions = std::move(*DeallocActions);
110 }
111
112 // Successful initialization.
113 ResetMBs.release();
114
115 return RR.Start;
116}
117
119 const std::vector<ExecutorAddr> &InitKeys) {
120 Error Err = Error::success();
121
122 for (auto &KeyAddr : llvm::reverse(InitKeys)) {
123 std::vector<shared::WrapperFunctionCall> DeallocActions;
124 {
125 std::scoped_lock<std::mutex> Lock(M);
126 auto Slab = getSlabInfo(KeyAddr, "In deinitialize");
127 if (!Slab) {
128 Err = joinErrors(std::move(Err), Slab.takeError());
129 continue;
130 }
131
132 auto RI = getRegionInfo(*Slab, KeyAddr, "In deinitialize");
133 if (!RI) {
134 Err = joinErrors(std::move(Err), RI.takeError());
135 continue;
136 }
137
138 DeallocActions = std::move(RI->DeallocActions);
139 }
140
141 Err = joinErrors(std::move(Err),
142 runDeallocActions(std::move(DeallocActions)));
143 }
144
145 return Err;
146}
147
149 const std::vector<ExecutorAddr> &Bases) {
150 Error Err = Error::success();
151
152 // TODO: Prohibit new initializations within the slabs being removed?
153 for (auto &Base : llvm::reverse(Bases)) {
154 std::vector<shared::WrapperFunctionCall> DeallocActions;
156
157 {
158 std::scoped_lock<std::mutex> Lock(M);
159
160 auto SlabI = Slabs.find(Base.toPtr<void *>());
161 if (SlabI == Slabs.end()) {
162 Err = joinErrors(
163 std::move(Err),
164 make_error<StringError>("In release, " + formatv("{0:x}", Base) +
165 " is not part of any reserved "
166 "address range",
168 continue;
169 }
170
171 auto &Slab = SlabI->second;
172
173 for (auto &[Addr, Region] : Slab.Regions)
174 llvm::copy(Region.DeallocActions, back_inserter(DeallocActions));
175
176 MB = {Base.toPtr<void *>(), Slab.Size};
177
178 Slabs.erase(SlabI);
179 }
180
181 Err = joinErrors(std::move(Err), runDeallocActions(DeallocActions));
182 if (auto EC = sys::Memory::releaseMappedMemory(MB))
183 Err = joinErrors(std::move(Err), errorCodeToError(EC));
184 }
185
186 return Err;
187}
188
190
191 // TODO: Prevent new allocations during shutdown.
192 std::vector<ExecutorAddr> Bases;
193 {
194 std::scoped_lock<std::mutex> Lock(M);
195 for (auto &[Base, Slab] : Slabs)
196 Bases.push_back(ExecutorAddr::fromPtr(Base));
197 }
198
199 return release(Bases);
200}
201
205 namespace sps_ci = rt::sps_ci;
206 M[Mangle.mangledCopy(sps_ci::SimpleNativeMemoryMapInstanceName)] =
208 M[Mangle.mangledCopy(sps_ci::MemMgrReserve::Name)] =
209 ExecutorAddr::fromPtr(reserveWrapper);
210 M[Mangle.mangledCopy(sps_ci::MemMgrInitialize::Name)] =
211 ExecutorAddr::fromPtr(initializeWrapper);
212 M[Mangle.mangledCopy(sps_ci::MemMgrDeinitialize::Name)] =
213 ExecutorAddr::fromPtr(deinitializeWrapper);
214 M[Mangle.mangledCopy(sps_ci::MemMgrRelease::Name)] =
215 ExecutorAddr::fromPtr(releaseWrapper);
216}
217
219SimpleExecutorMemoryManager::getSlabInfo(ExecutorAddr A, StringRef Context) {
220 auto MakeBadSlabError = [&]() {
222 Context + ", address " + formatv("{0:x}", A) +
223 " is not part of any reserved address range",
225 };
226
227 auto I = Slabs.upper_bound(A.toPtr<void *>());
228 if (I == Slabs.begin())
229 return MakeBadSlabError();
230 --I;
231 if (!ExecutorAddrRange(ExecutorAddr::fromPtr(I->first), I->second.Size)
232 .contains(A))
233 return MakeBadSlabError();
234
235 return I->second;
236}
237
239SimpleExecutorMemoryManager::getSlabInfo(ExecutorAddrRange R,
240 StringRef Context) {
241 auto MakeBadSlabError = [&]() {
243 Context + ", range " + formatv("{0:x}", R) +
244 " is not part of any reserved address range",
246 };
247
248 auto I = Slabs.upper_bound(R.Start.toPtr<void *>());
249 if (I == Slabs.begin())
250 return MakeBadSlabError();
251 --I;
252 if (!ExecutorAddrRange(ExecutorAddr::fromPtr(I->first), I->second.Size)
253 .contains(R))
254 return MakeBadSlabError();
255
256 return I->second;
257}
258
259Expected<SimpleExecutorMemoryManager::RegionInfo &>
260SimpleExecutorMemoryManager::createRegionInfo(ExecutorAddrRange R,
261 StringRef Context) {
262
263 auto Slab = getSlabInfo(R, Context);
264 if (!Slab)
265 return Slab.takeError();
266
267 auto MakeBadRegionError = [&](ExecutorAddrRange Other, bool Prev) {
268 return make_error<StringError>(Context + ", region " + formatv("{0:x}", R) +
269 " overlaps " +
270 (Prev ? "previous" : "following") +
271 " region " + formatv("{0:x}", Other),
273 };
274
275 auto I = Slab->Regions.upper_bound(R.Start);
276 if (I != Slab->Regions.begin()) {
277 auto J = std::prev(I);
278 ExecutorAddrRange PrevRange(J->first, J->second.Size);
279 if (PrevRange.overlaps(R))
280 return MakeBadRegionError(PrevRange, true);
281 }
282 if (I != Slab->Regions.end()) {
283 ExecutorAddrRange NextRange(I->first, I->second.Size);
284 if (NextRange.overlaps(R))
285 return MakeBadRegionError(NextRange, false);
286 }
287
288 auto &RInfo = Slab->Regions[R.Start];
289 RInfo.Size = R.size();
290 return RInfo;
291}
292
293Expected<SimpleExecutorMemoryManager::RegionInfo &>
294SimpleExecutorMemoryManager::getRegionInfo(SlabInfo &Slab, ExecutorAddr A,
295 StringRef Context) {
296 auto I = Slab.Regions.find(A);
297 if (I == Slab.Regions.end())
299 Context + ", address " + formatv("{0:x}", A) +
300 " does not correspond to the start of any initialized region",
302
303 return I->second;
304}
305
306Expected<SimpleExecutorMemoryManager::RegionInfo &>
307SimpleExecutorMemoryManager::getRegionInfo(ExecutorAddr A, StringRef Context) {
308 auto Slab = getSlabInfo(A, Context);
309 if (!Slab)
310 return Slab.takeError();
311
312 return getRegionInfo(*Slab, A, Context);
313}
314
315llvm::orc::shared::CWrapperFunctionBuffer
316SimpleExecutorMemoryManager::reserveWrapper(const char *ArgData,
317 size_t ArgSize) {
318 return shared::WrapperFunction<rt::sps_ci::MemMgrReserve::SPSSig>::handle(
319 ArgData, ArgSize,
322 .release();
323}
324
325llvm::orc::shared::CWrapperFunctionBuffer
326SimpleExecutorMemoryManager::initializeWrapper(const char *ArgData,
327 size_t ArgSize) {
328 return shared::WrapperFunction<rt::sps_ci::MemMgrInitialize::SPSSig>::handle(
329 ArgData, ArgSize,
332 .release();
333}
334
335llvm::orc::shared::CWrapperFunctionBuffer
336SimpleExecutorMemoryManager::deinitializeWrapper(const char *ArgData,
337 size_t ArgSize) {
338 return shared::WrapperFunction<rt::sps_ci::MemMgrDeinitialize::SPSSig>::
339 handle(ArgData, ArgSize,
342 .release();
343}
344
345llvm::orc::shared::CWrapperFunctionBuffer
346SimpleExecutorMemoryManager::releaseWrapper(const char *ArgData,
347 size_t ArgSize) {
348 return shared::WrapperFunction<rt::sps_ci::MemMgrRelease::SPSSig>::handle(
349 ArgData, ArgSize,
352 .release();
353}
354
355} // namespace rt_bootstrap
356} // end namespace orc
357} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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:129
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
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.
Applies linker name-mangling for a target.
Definition Mangler.h:31
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....
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
LLVM_ABI std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition Host.cpp:2653
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:408
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:1901
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