jam 0.0.1
A compacting generational garbage collector for C++26
Loading...
Searching...
No Matches
heap.ccm
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Edward Kmett <ekmett@gmail.com>
2// SPDX-License-Identifier: BSD-2-Clause OR Apache-2.0
3
8module;
9#include <hint.h>
10#include <cstdio>
11#include <cstdlib>
12#include <algorithm>
13#include <array>
14#include <atomic>
15#include <cassert>
16#include <cstddef>
17#include <concepts>
18#include <compare>
19#include <limits>
20#include <memory>
21#include <map>
22#include <tuple>
23#include <type_traits>
24#include <variant>
25#include <utility>
26#include <vector>
27#include <deque>
28#include <unordered_map>
29
30#include <bit>
31#include <cstdint>
32#include <cstring>
33#include <functional>
34#include <span>
35#include <stdexcept>
36
37#if defined(__APPLE__)
38// Keep the SDK assert builtin in the global module across module boundaries.
39extern "C" long __builtin_expect(long, long) noexcept;
40#endif
41
42export module jam.heap;
43import jam.mapping;
44import work;
45import jam.packed;
46export import jam.units;
47namespace jam {
48export class heap;
49export template<class T> class root;
50export template<class T> class ptr;
51export template<class T> class weak_ptr;
52export template<class T> class weak_root;
53export template<class T> class weak;
54
57export template<class V>
58concept visitor = std::same_as<typename V::heap_type, heap>;
59
60namespace detail {
61template<class T, class H = heap>
62concept member_trace = requires(T & value, typename H::visitor & visit) {
63 value.trace(visit);
64};
65template<class T, class H = heap>
66concept cooperative_trace = requires(typename H::visitor & visit, ptr<T> const & at) {
67 T::trace(visit, at);
68};
69template<class T, class H = heap>
70concept allocation_trace = requires(T const & value, typename H::visitor & visit) {
71 { value.claim_and_trace(visit) } noexcept -> std::same_as<void>;
72};
73template<class T>
74concept has_allocation_trace = requires { &T::claim_and_trace; } || allocation_trace<T>;
75template<class T>
76concept has_trace = requires { &T::trace; } || member_trace<T> || cooperative_trace<T>;
77
78export struct structural_tracer {};
79template<class T, class... Members>
80struct member_manifest {
81 std::tuple<Members T::*...> members;
82 template<class Visitor>
83 static constexpr bool accepts = (requires(Visitor & visit, Members const & value) {
84 visit(value);
85 } && ...);
86};
87template<class T, class Descriptor> inline constexpr bool manifest_for = false;
88template<class T, class... Members>
89inline constexpr bool manifest_for<T, member_manifest<T, Members...>> = true;
90template<class T>
91concept has_manifest = requires {
92 requires manifest_for<T, std::remove_cvref_t<decltype(T::manifest)>>;
93};
94struct invalid_tracer {};
95}
96
113export template<class T, class... Members> requires (std::is_object_v<Members> && ...)
114[[nodiscard]] consteval auto make_manifest(Members T::*... members) {
115 if (((members == nullptr) || ...)) throw "manifest members must not be null";
116 return detail::member_manifest<T, Members...>{{members...}};
117}
118
125export template<class T>
126struct leaf {
128 template<class Visitor>
129 static constexpr void trace(Visitor &, T const &) noexcept {}
130};
131
139export template<class T>
140struct tracer : std::conditional_t<requires { T::manifest; } || detail::has_allocation_trace<T>, detail::invalid_tracer, leaf<T>> {};
141
147export template<class T> requires detail::has_trace<T>
148struct tracer<T> {
150 template<class Visitor>
151 static constexpr auto trace(Visitor & visit, T const & value)
152 noexcept(noexcept(value.trace(visit))) -> decltype(value.trace(visit)) {
153 return value.trace(visit);
154 }
155
156 template<class Visitor>
157 static constexpr decltype(auto) trace(Visitor & visit, ptr<T> const & at) noexcept
158 requires requires { T::trace(visit, at); } {
159 return T::trace(visit, at);
160 }
161};
162
163namespace detail {
164template<class T, class H>
165concept traceable_in = (!has_allocation_trace<T> || allocation_trace<T, H>)
166 && (allocation_trace<T, H> || requires(T const & value, typename H::visitor & visit) {
167 sizeof(T);
168 tracer<T>::trace(visit, value);
169} || requires(ptr<T> const & at, typename H::visitor & visit) {
170 sizeof(T);
171 tracer<T>::trace(visit, at);
172});
173}
174
181export template<class T>
182concept traceable = detail::traceable_in<T, heap>;
183
184export namespace detail {
185template<class T> inline constexpr bool is_ptr = false;
186template<class T> inline constexpr bool is_ptr<ptr<T>> = true;
187template<class T> inline constexpr bool is_weak_ptr = false;
188template<class T> inline constexpr bool is_weak_ptr<weak_ptr<T>> = true;
189template<class T, class Visitor>
190concept visits = requires(Visitor & visit, std::remove_reference_t<T> const & value) {
191 tracer<std::remove_cvref_t<T>>::trace(visit, value);
192};
193}
194
197export template<class T>
198struct tracer<ptr<T>> {
200 template<visitor Visitor>
201 static constexpr void trace(Visitor & visit, ptr<T> const & value)
202 noexcept(noexcept(visit(value))) {
203 visit(value);
204 }
205};
206
209export template<class T>
210struct tracer<weak_ptr<T>> {
212 template<visitor Visitor>
213 static constexpr void trace(Visitor & visit, weak_ptr<T> const & value)
214 noexcept(noexcept(visit(value))) { visit(value); }
215};
216
217export namespace detail {
218template<class Visitor, class... Ts>
219constexpr void trace_parts(Visitor & visit, Ts const &... values) noexcept {
220 auto part = [&](auto const & value) constexpr noexcept {
221 if constexpr (requires { visit(value); }) visit(value);
222 else tracer<std::remove_cvref_t<decltype(value)>>::trace(visit, value);
223 };
224 (part(values), ...);
225}
226}
227
230export template<class... Ts>
231struct tracer<std::tuple<Ts...>> : detail::structural_tracer {
233 template<class Visitor>
234 static constexpr void trace(Visitor & visit, std::tuple<Ts...> const & value)
235 requires (detail::visits<Ts, Visitor> && ...) {
236 std::apply([&](auto const &... part) constexpr {
237 detail::trace_parts(visit, part...);
238 }, value);
239 }
240};
241
244export template<class T, std::size_t N>
245struct tracer<std::array<T, N>> : detail::structural_tracer {
247 template<class Visitor>
248 static constexpr void trace(Visitor & visit, std::array<T, N> const & value)
249 requires detail::visits<T, Visitor> {
250 for (auto const & part : value) detail::trace_parts(visit, part);
251 }
252};
253
256export template<class... Ts>
257struct tracer<std::variant<Ts...>> : detail::structural_tracer {
259 template<class Visitor>
260 static constexpr void trace(Visitor & visit, std::variant<Ts...> const & value)
261 requires (detail::visits<Ts, Visitor> && ...) {
262 if (value.valueless_by_exception()) return;
263 std::visit([&](auto const & part) constexpr {
264 detail::trace_parts(visit, part);
265 }, value);
266 }
267};
268
271export template<class T> requires (!detail::has_trace<T>) && detail::has_manifest<T>
272struct tracer<T> : detail::structural_tracer {
274 template<class Visitor>
275 static hint_inline constexpr void trace(Visitor & visit, T const & value) noexcept
276 requires std::remove_cvref_t<decltype(T::manifest)>::template accepts<Visitor> {
277 auto const & [...member] = T::manifest.members;
278 visit((value.*member)...);
279 }
280
281 template<class Visitor>
282 static void trace(Visitor & visit, ptr<T> const & at) noexcept
283 requires std::remove_cvref_t<decltype(T::manifest)>::template accepts<Visitor> {
284 visit.template trace_manifest<T>(at);
285 }
286};
287
288}
289
290namespace jam {
291
292namespace detail {
293#if defined(JAM_CONTEXT_X28)
294#if !defined(__aarch64__)
295#error "JAM_CONTEXT_X28 requires AArch64 and -ffixed-x28"
296#endif
297register heap * active_heap asm("x28");
298#else
299inline thread_local heap * active_heap = nullptr;
300#endif
301}
302
307export class heap_scope {
308 heap * previous;
309public:
311 [[nodiscard]] hint_inline explicit heap_scope(heap & arena) noexcept;
313 hint_inline ~heap_scope() noexcept { detail::active_heap = previous; }
314 heap_scope(heap_scope const &) = delete;
315 heap_scope & operator=(heap_scope const &) = delete;
316};
317
328export template<class T>
329class ptr {
330public:
332 using element_type = T;
334 using offset = std::uint32_t;
335
336private:
337 mutable offset position = 0;
338 hint_inline constexpr void update_barrier() noexcept;
339
340public:
342 constexpr ptr() noexcept = default;
344 constexpr ptr(std::same_as<std::nullptr_t> auto) noexcept {}
346 hint_inline explicit constexpr ptr(offset at) noexcept;
348 hint_inline constexpr ptr(ptr const & other) noexcept;
351 template<class U> requires (!std::same_as<T, U>) && std::derived_from<U, T>
352 && detail::allocation_trace<T> && requires(T * p) { static_cast<U *>(p); }
353 hint_inline constexpr ptr(ptr<U> const & other) noexcept;
354
355 hint_inline constexpr ptr & operator=(ptr const & other) noexcept;
357 hint_inline constexpr ptr(ptr && other) noexcept;
359 hint_inline constexpr ptr & operator=(ptr && other) noexcept;
361 hint_inline constexpr void swap(ptr & other) noexcept;
363 friend hint_inline constexpr void swap(ptr & left, ptr & right) noexcept { left.swap(right); }
365 hint_inline constexpr ~ptr() noexcept;
367 constexpr ptr & unsafe_assign(ptr const & other) noexcept { position = other.position; return *this; }
369 constexpr ptr & unsafe_assign(offset bits) noexcept { position = bits; return *this; }
371 [[nodiscard]] constexpr bool is_young() const noexcept { return (position & 0x80000000u) != 0; }
373 [[nodiscard]] constexpr offset local_offset() const noexcept { return position & 0x7fffffffu; }
375 [[nodiscard]] hint_inline hint_pure
376 constexpr offset get() const noexcept { return position; }
378 [[nodiscard]] hint_inline hint_pure
379 explicit constexpr operator bool() const noexcept {
380 return position != 0;
381 }
382
384 [[nodiscard]] hint_inline T * operator->() const noexcept;
386 [[nodiscard]] hint_inline T & operator*() const noexcept;
390 hint_inline void prefetch_marks() const noexcept;
394 hint_inline void prefetch() const noexcept;
397 [[nodiscard]] constexpr auto operator<=>(ptr const &) const noexcept = default;
398};
399
407export template<class T>
408class weak_ptr {
409public:
411 using element_type = T;
413 using offset = std::uint32_t;
414private:
415 mutable offset position = 0;
416 hint_inline constexpr void update_barrier() noexcept;
417public:
419 constexpr weak_ptr() noexcept = default;
421 constexpr weak_ptr(std::same_as<std::nullptr_t> auto) noexcept {}
423 hint_inline constexpr weak_ptr(ptr<T> const & value) noexcept;
425 hint_inline weak_ptr(root<T> const & value) noexcept;
427 template<class U> requires (!std::same_as<T, U>) && std::convertible_to<ptr<U>, ptr<T>>
428 hint_inline constexpr weak_ptr(ptr<U> const & value) noexcept : weak_ptr(ptr<T>{value}) {}
430 hint_inline constexpr weak_ptr(weak_ptr const & other) noexcept;
431 hint_inline constexpr weak_ptr & operator=(weak_ptr const & other) noexcept;
433 hint_inline constexpr weak_ptr(weak_ptr && other) noexcept;
435 hint_inline constexpr weak_ptr & operator=(weak_ptr && other) noexcept;
437 hint_inline constexpr ~weak_ptr() noexcept;
439 hint_inline constexpr void swap(weak_ptr & other) noexcept;
441 friend hint_inline constexpr void swap(weak_ptr & a, weak_ptr & b) noexcept { a.swap(b); }
443 constexpr weak_ptr & unsafe_assign(offset bits) noexcept { position = bits; return *this; }
445 constexpr weak_ptr & unsafe_assign(weak_ptr const & other) noexcept { return unsafe_assign(other.position); }
447 [[nodiscard]] hint_inline hint_pure constexpr offset get() const noexcept { return position; }
449 [[nodiscard]] constexpr bool is_young() const noexcept { return (position & 0x80000000u) != 0; }
451 [[nodiscard]] constexpr bool expired() const noexcept { return position == 0; }
454 [[nodiscard]] hint_inline root<T> lock() const noexcept requires traceable<T>;
456 [[nodiscard]] constexpr auto operator<=>(weak_ptr const &) const noexcept = default;
457};
458
459export template<class T> weak_ptr(ptr<T> const &) -> weak_ptr<T>;
461export template<class T> weak_ptr(root<T> const &) -> weak_ptr<T>;
462
475
477export struct heap_options {
483 std::size_t workers = 1;
485 std::size_t minor_collections = 7;
486};
487
502export class heap {
503 template<class T> friend class ptr;
504 template<class T> friend class weak_ptr;
505 template<class T> friend class weak;
506
507public:
511 [[nodiscard]] hint_pure hint_inline
512 static heap * current() noexcept { return detail::active_heap; }
513
515 using word = std::uint64_t;
517 using offset = std::uint32_t;
519 using bitmap = offset;
521 static constexpr offset null = 0;
523 static constexpr std::size_t block_words = 32;
525 static constexpr unsigned fields_per_word = 2;
527 using block = detail::heap_block;
530 template<class T> using ptr = jam::ptr<T>;
532 template<class T> using weak_ptr = jam::weak_ptr<T>;
533 static_assert(sizeof(std::size_t) == 8, "jam requires 64-bit addressing");
534 static_assert(sizeof(block) == 16);
535 static_assert(std::atomic_ref<bitmap>::is_always_lock_free);
536 static_assert(std::atomic_ref<word>::is_always_lock_free);
537
538 class visitor;
539
540private:
541 using trace_function = void (*)(visitor &, offset);
542 struct trace_job { offset at; trace_function trace; };
543 struct weak_entry {
544 trace_job key, value, finalizer;
545 void (*invoke)(heap &, weak_entry &) noexcept;
546 bool active = true;
547 weak_entry * previous_running = nullptr;
548 };
549 template<class F> struct finalizer_entry : weak_entry {
550 void (*runner)(F *) noexcept;
551 };
552
553public:
560 class root_handle {
561 friend class heap;
562 std::uint32_t slot = 0;
563 hint_inline void retain() noexcept {
564 if (slot) heap::current()->retain_root(slot);
565 }
566 hint_inline void detach() noexcept {
567 if (slot) heap::current()->release_root(std::exchange(slot, 0));
568 }
569 hint_inline root_handle(heap & arena, offset at, trace_function fn = nullptr) noexcept
570 : slot(arena.add_root(at, fn)) {}
571 public:
573 root_handle() noexcept = default;
575 hint_inline root_handle(root_handle const & other) noexcept : slot(other.slot) { retain(); }
577 hint_inline root_handle(root_handle && other) noexcept : slot(std::exchange(other.slot, 0)) {}
579 hint_inline root_handle & operator=(root_handle const & other) noexcept {
580 if (this != &other) { detach(); slot = other.slot; retain(); }
581 return *this;
582 }
583
584 hint_inline root_handle & operator=(root_handle && other) noexcept {
585 if (this != &other) { detach(); slot = std::exchange(other.slot, 0); }
586 return *this;
587 }
588
589 hint_inline ~root_handle() noexcept { detach(); }
591 [[nodiscard]] hint_inline offset get() const noexcept {
592 return slot ? heap::current()->root_slots[slot - 1].position : null;
593 }
594
595 [[nodiscard]] hint_inline offset operator*() const noexcept { return get(); }
597 [[nodiscard]] hint_inline explicit operator bool() const noexcept { return get() != null; }
598 };
599
605 class visitor {
606 friend class heap;
607 template<class T> friend struct jam::tracer;
608 heap & arena;
609 work::context<trace_job> & pending;
610 void const * record = nullptr;
611 offset record_offset = 0;
612 std::size_t record_bytes = 0;
613 visitor(heap & h, work::context<trace_job> & tasks) noexcept
614 : arena(h), pending(tasks) {}
615
616 [[nodiscard]] hint_inline std::size_t pointer_slot(void const * field) const noexcept {
617 auto const address = reinterpret_cast<std::uintptr_t>(field);
618 auto const begin = reinterpret_cast<std::uintptr_t>(record);
619 auto const delta = address - begin;
620 if (!record || address < begin || record_bytes < sizeof(offset)
621 || delta > record_bytes - sizeof(offset) || delta % sizeof(offset))
622 detail::heap_failure("typed visitor requires a field in its tracing value");
623 return delta / sizeof(offset);
624 }
625 template<class T>
626 hint_inline void enqueue(ptr<T> const & value) noexcept {
627 static_assert(traceable<T>, "reference target must support tracing");
628 if (value && (!arena.minor_collection || value.is_young())) pending.push({value.get(), &heap::template trace_record<T>});
629 }
630
631 // One mask window bounds stack use even for large, sparsely described records.
632 template<class T>
633 struct manifest_visit {
634 using heap_type = heap;
635 visitor & visit;
636 ptr<T> const * next = nullptr;
637 word bits = 0;
638 std::size_t first_slot = 0;
639
640 hint_inline void flush() noexcept {
641 visit.pointers(bits, first_slot);
642 bits = 0;
643 }
644 template<class U>
645 hint_inline void operator()(ptr<U> const & value) noexcept {
646 auto const slot = visit.pointer_slot(&value);
647 auto const window = slot & ~std::size_t{63};
648 if (window != first_slot) { flush(); first_slot = window; }
649 bits |= word{1} << (slot - first_slot);
650 if constexpr (std::same_as<T, U>) {
651 if (value) {
652 if (next) visit.enqueue(*next);
653 next = std::addressof(value);
654 }
655 } else visit.enqueue(value);
656 }
657 template<class U>
658 hint_inline void operator()(weak_ptr<U> const & value) noexcept { visit(value); }
659 template<class U>
660 hint_inline void operator()(U const & value) noexcept
661 requires (!detail::is_ptr<U> && !detail::is_weak_ptr<U>) && detail::visits<U, visitor> {
662 if constexpr (std::derived_from<tracer<U>, detail::structural_tracer>)
663 tracer<U>::trace(*this, value);
664 else visit(value); // Custom hooks keep the actual heap visitor.
665 }
666 template<class... Us>
667 hint_inline void operator()(Us const &... values) noexcept
668 requires (sizeof...(Us) != 1) && (detail::visits<Us, visitor> && ...) {
669 ((*this)(values), ...);
670 }
671 };
672
673 template<class T>
674 void trace_manifest(ptr<T> const & at) noexcept {
675 // Pointer fields stay put throughout marking; borrow the next edge.
676 auto const * current = std::addressof(at);
677 while (current) {
678 auto const * value = claim_target(*current);
679 if (!value) break;
680 manifest_visit<T> fields{*this};
681 tracer<T>::trace(fields, *value);
682 fields.flush();
683 current = fields.next;
684 poll();
685 }
686 }
687
688 public:
690 using heap_type = heap;
691 visitor(visitor const &) = delete;
692 visitor & operator=(visitor const &) = delete;
695 [[nodiscard]] hint_inline bool claim(offset start, std::size_t words = 1,
696 std::size_t alignment_bytes = 8) noexcept {
697 return arena.claim(start, words, alignment_bytes);
698 }
699
704 template<class T>
705 [[nodiscard]] hint_inline T const * claim_target(ptr<T> const & value) noexcept {
706 heap::require_record<T>();
707 if (!value || !claim(value.get(), record_words<T>, std::max(alignof(T), sizeof(word))))
708 return nullptr;
709 auto const * result = arena.template record_address<T>(value.get());
710 record = result;
711 record_offset = value.get();
712 record_bytes = sizeof(T);
713 return result;
714 }
715
718 template<class T>
719 [[nodiscard]] hint_inline T const * claim_target(T const * value) noexcept {
720 heap::require_record<T>();
721 if (!value) return nullptr;
722 auto const address = reinterpret_cast<std::uintptr_t>(value);
723 auto const old_delta = address - reinterpret_cast<std::uintptr_t>(arena.arena.data());
724 auto const young_delta = address - reinterpret_cast<std::uintptr_t>(arena.nursery.data());
725 bool const young = young_delta < arena.nursery.used() * sizeof(word);
726 auto const delta = young ? young_delta : old_delta;
727 if ((!young && old_delta >= arena.arena.used() * sizeof(word)) || delta % sizeof(word))
728 detail::heap_failure("claim_target requires a complete object in this heap");
729 auto const at = static_cast<offset>(delta / sizeof(word)) | (young ? young_bit : 0);
730 if (!claim(at, record_words<T>, std::max(alignof(T), sizeof(word)))) return nullptr;
731 record = value;
732 record_offset = at;
733 record_bytes = sizeof(T);
734 return value;
735 }
736
738 template<class T>
739 hint_inline void pointer(ptr<T> const & value) noexcept {
740 auto const heap_delta = std::size_t(record_offset & offset_mask) * sizeof(word) + pointer_slot(&value) * sizeof(offset);
741 arena.pointer((record_offset & young_bit) | static_cast<offset>(heap_delta / sizeof(word)),
742 static_cast<unsigned>((heap_delta % sizeof(word)) / sizeof(offset)));
743 }
744
746 template<class T>
747 hint_inline void pointer(weak_ptr<T> const & value) noexcept {
748 pointers(word{1}, pointer_slot(&value));
749 }
750
754 hint_inline void pointers(word bits, std::size_t first_slot = 0) noexcept {
755 if (!bits) return;
756 auto const slots = record_bytes / sizeof(offset);
757 if (!record || first_slot > slots
758 || static_cast<std::size_t>(std::bit_width(bits)) > slots - first_slot)
759 detail::heap_failure("pointer pattern exceeds its tracing value");
760 auto & g = arena.containing(record_offset);
761 auto const slot = std::size_t(record_offset & offset_mask) * fields_per_word + first_slot;
762 constexpr auto width = block_words * fields_per_word;
763 auto const shift = slot % width;
764 std::atomic_ref<word>{g.metadata[slot / width].pointers}
765 .fetch_or(bits << shift, std::memory_order_relaxed);
766 if (shift && (bits >> (width - shift)))
767 std::atomic_ref<word>{g.metadata[slot / width + 1].pointers}
768 .fetch_or(bits >> (width - shift), std::memory_order_relaxed);
769 }
770
772 template<class T>
773 [[nodiscard]] hint_inline T const * claim(ptr<T> const & value) noexcept {
774 pointer(value);
775 return claim_target(value);
776 }
777
781 hint_inline offset field(offset cell, unsigned slot = 0) noexcept {
782 arena.pointer(cell, slot);
783 auto const target = arena.field(cell, slot);
784 if (target != null && (!arena.minor_collection || (target & young_bit)))
785 pending.push({target, nullptr});
786 return target;
787 }
788
789 hint_inline void target(offset at) noexcept {
790 if (at && (!arena.minor_collection || (at & young_bit))) pending.push({at, nullptr});
791 }
792
795 template<class T>
796 hint_inline void operator()(T const & value) noexcept
797 requires (!detail::is_ptr<T> && !detail::is_weak_ptr<T>) && detail::visits<T, visitor> {
798 tracer<T>::trace(*this, value);
799 }
800
804 template<class T>
805 hint_inline ptr<T> operator()(ptr<T> const & value) noexcept {
806 // Defer target validation until use: deducing a recursive member hook's
807 // return type must not require that hook's own traceable constraint.
808 pointer(value);
809 enqueue(value);
810 return value;
811 }
812
813 template<class T>
814 hint_inline void operator()(weak_ptr<T> const & value) noexcept { pointer(value); }
816 template<class... Ts>
817 hint_inline void operator()(Ts const &... values) noexcept
818 requires (sizeof...(Ts) != 1) && (detail::visits<Ts, visitor> && ...) {
819 detail::trace_parts(*this, values...);
820 }
821
823 hint_inline void poll() noexcept { pending.poll(); }
824 };
825
826private:
827 template<class T>
828 static constexpr std::size_t record_words = (sizeof(T) + sizeof(word) - 1) / sizeof(word);
829
830 template<class T>
831 static consteval void require_record() noexcept {
832 // Byte relocation is a managed-storage precondition, not something a trace
833 // hook or a standard type trait proves. Compaction has no per-record type
834 // descriptor and never invokes a move constructor or destructor.
835 static_assert(std::is_object_v<T> && !std::is_const_v<T> && !std::is_volatile_v<T>,
836 "jam records must be unqualified objects that permit byte relocation");
837 static_assert(alignof(T) <= 64, "record alignment exceeds 64 bytes");
838 }
839
840 // Marking never changes mappings; no payload copy or stack snapshot is needed.
841 template<class T>
842 [[nodiscard]] hint_inline T * record_address(offset at) noexcept {
843 require_record<T>();
844 assert(at && (at & offset_mask) < containing(at).cursor
845 && record_words<T> <= containing(at).cursor - (at & offset_mask));
846 auto * p = decode(at);
847 if constexpr (std::is_trivially_copyable_v<T>) {
848 return static_cast<T *>(std::memmove(p, p, sizeof(T)));
849 } else {
850 // Nontrivial records use Jam's byte-relocation contract. This cast does
851 // not claim to establish arbitrary nontrivial lifetimes in ISO C++.
852 return reinterpret_cast<T *>(p);
853 }
854 }
855
856 template<class T>
857 static void trace_record(visitor & visit, offset at) noexcept {
858 require_record<T>();
859 static_assert(traceable<T>, "tracing hooks must accept the heap visitor");
860 if constexpr (detail::allocation_trace<T>) {
861 // Dispatch before claiming: only the dynamic override knows the extent.
862 visit.arena.template record_address<T>(at)->claim_and_trace(visit);
863 } else if constexpr (requires { tracer<T>::trace(visit, ptr<T>{at}); }) {
864 // Cooperative hooks receive an unclaimed entry and own the walk.
865 tracer<T>::trace(visit, ptr<T>{at});
866 } else if (auto const * value = visit.claim_target(ptr<T>{at})) {
867 tracer<T>::trace(visit, *value);
868 }
869 }
870
871public:
873 struct generation {
874 friend class heap;
875 private:
876 static constexpr offset young_bit = 0x80000000u;
877 static constexpr offset offset_mask = 0x7fffffffu;
878 struct settings { std::size_t page_words, reserved, minimum, bytes; generation_options policy; };
879 generation_options const policy;
880 detail::compactor const & compactor;
881 work::pool & workers;
882 std::size_t const page_word_count;
883 std::size_t const reserve_word_count;
884 std::size_t const minimum_capacity;
885 detail::heap_mapping storage;
886 word * view_base;
887 std::vector<block> metadata;
888 // One alignment nibble per 256 bytes.
889 // Low3 bits are a thermometer exponent (0,1,3,7); bit3 joins the next block.
890 // Atomic OR therefore implements max(k), even for simultaneous markers.
891 std::vector<std::uint8_t> alignment;
892 bool has_alignment = false;
893 std::size_t cursor = 1;
894 std::size_t origin = 0;
895 bool collecting = false;
896 void require_mutator() const noexcept {
897 if (collecting) detail::heap_failure("mutation during collection");
898 }
899 static constexpr unsigned block_shift = 5;
900 static constexpr std::size_t maximum_bytes = std::size_t{1} << 34;
901
902 [[nodiscard]] static constexpr bool valid_options(generation_options const & config) noexcept {
903 return config.capacity.count() != 0 && config.capacity <= config.maximum && config.maximum <= units::bytes{maximum_bytes}
904 && config.reserve.count() != 0 && config.reserve <= units::bytes{maximum_bytes / 2}
905 && config.shrink_shift < std::numeric_limits<std::size_t>::digits;
906 }
907 [[nodiscard]] static settings configure(generation_options config);
908 explicit generation(settings s, detail::compactor const & c, work::pool & w, std::byte * address) noexcept;
909 [[nodiscard]] static constexpr unsigned exponent(std::size_t bytes) noexcept {
910 if (!std::has_single_bit(bytes) || bytes < 8 || bytes > 64u)
911 detail::heap_failure("unsupported record alignment");
912 return std::countr_zero(bytes) - 3;
913 }
914 [[nodiscard]] unsigned flags(std::size_t index) const noexcept {
915 return (alignment[index >> 1] >> ((index & 1) * 4)) & 15;
916 }
917 hint_inline void add_flags(std::size_t index, unsigned bits) noexcept {
918 std::atomic_ref<std::uint8_t>{alignment[index >> 1]}.fetch_or(
919 static_cast<std::uint8_t>(bits << ((index & 1) * 4)), std::memory_order_relaxed);
920 }
921 hint_inline void note_record(offset first, std::size_t words, std::size_t bytes) noexcept {
922 assert(std::has_single_bit(bytes) && bytes >= 8 && bytes <= 64);
923 assert((static_cast<std::size_t>(first) * 8) % bytes == 0);
924 if (!words) return;
925 auto const k = std::countr_zero(bytes) - 3;
926 if (k) add_flags(first >> block_shift, (1u << k) - 1);
927 auto const last = (static_cast<std::size_t>(first) + words - 1) >> block_shift;
928 for (auto i = static_cast<std::size_t>(first) >> block_shift; i < last; ++i) add_flags(i, 8);
929 }
930 hint_inline void mark_range(offset first, std::size_t words) noexcept {
931 while (words != 0) {
932 auto const bit = static_cast<std::size_t>(first & (block_words - 1));
933 auto const count = std::min(words, block_words - bit);
934 std::atomic_ref<bitmap>{metadata[first >> block_shift].live}.fetch_or(
935 static_cast<bitmap>((~bitmap{0} >> (block_words - count)) << bit), std::memory_order_relaxed);
936 first += static_cast<offset>(count);
937 words -= count;
938 }
939 }
940 [[nodiscard]] static constexpr word pointer_cells(bitmap live) noexcept {
941 word x = live;
942 x = (x | (x << 16)) & 0x0000ffff0000ffffULL;
943 x = (x | (x << 8)) & 0x00ff00ff00ff00ffULL;
944 x = (x | (x << 4)) & 0x0f0f0f0f0f0f0f0fULL;
945 x = (x | (x << 2)) & 0x3333333333333333ULL;
946 x = (x | (x << 1)) & 0x5555555555555555ULL;
947 return x | (x << 1);
948 }
949 [[nodiscard]] std::uint8_t const * alignment_table() const noexcept {
950 return has_alignment ? alignment.data() : nullptr;
951 }
952 [[nodiscard]] offset base(block const & item) const noexcept {
953 return item.destination;
954 }
955 [[nodiscard]] offset forward(offset value) const noexcept {
956 if (value == null) return null;
957 assert(value < cursor);
958 auto const & item = metadata[value >> block_shift];
959 auto const bit = static_cast<bitmap>(bitmap{1} << (value & (block_words - 1)));
960 if (!(item.live & bit)) return null;
961 return base(item) + static_cast<offset>(std::popcount(detail::retained(item, alignment_table(), value >> block_shift) & (bit - 1)));
962 }
963 void resize(std::size_t words) noexcept;
964
965 generation(generation_options config, detail::compactor const & c, work::pool & w, std::byte * address);
966
967 public:
969 [[nodiscard]] std::size_t capacity() const noexcept { return storage.bytes() / 8; }
971 [[nodiscard]] std::size_t reserved() const noexcept { return reserve_word_count; }
973 [[nodiscard]] std::size_t used() const noexcept { return cursor; }
975 [[nodiscard]] std::size_t start() const noexcept { return origin; }
977 [[nodiscard]] std::size_t page_words() const noexcept { return page_word_count; }
979 template<class Self>
980 [[nodiscard]] hint_inline hint_pure
981 auto data(this Self & self hint_lifetimebound) noexcept
982 -> std::conditional_t<std::is_const_v<Self>, word const, word> * {
983 using cell = std::conditional_t<std::is_const_v<Self>, word const, word>;
984 return static_cast<cell *>(self.view_base);
985 }
986
987 [[nodiscard]] decltype(auto) operator[](this auto & self hint_lifetimebound, offset index) noexcept {
988 assert(index < self.cursor); return self.data()[index];
989 }
990
996 [[nodiscard]] offset field(offset cell, unsigned slot = 0) const noexcept {
997 assert(cell < cursor && slot < fields_per_word);
998 offset value;
999 auto const address = reinterpret_cast<std::byte const *>(data() + cell) + slot * sizeof(offset);
1000 std::memcpy(&value, address, sizeof(value));
1001 return value;
1002 }
1003
1011 void set_field(offset cell, offset value, unsigned slot = 0) noexcept {
1012 require_mutator();
1013 assert(cell < cursor && slot < fields_per_word);
1014 auto const address = reinterpret_cast<std::byte *>(data() + cell) + slot * sizeof(offset);
1015 std::memcpy(address, &value, sizeof(value));
1016 }
1017
1018 [[nodiscard]] std::span<block const> blocks() const noexcept { return metadata; }
1028 [[nodiscard]] offset allocate(std::size_t words, std::size_t alignment_bytes = 8) noexcept
1029 hint_diagnose_if(words == 0, "jam records must contain at least one cell")
1030 hint_diagnose_if(!std::has_single_bit(alignment_bytes) || alignment_bytes < 8 || alignment_bytes > 64u, "unsupported jam record alignment") {
1031 require_mutator();
1032 auto const k = exponent(alignment_bytes);
1033 auto const aligned = (cursor + (std::size_t{1} << k) - 1) & ~((std::size_t{1} << k) - 1);
1034 if (!words) detail::heap_failure("zero-word allocation");
1035 auto const limit = units::bytes{policy.maximum}.count() / 8 - reserve_word_count;
1036 if (aligned > limit || words > limit - aligned)
1037 detail::heap_failure("capacity overflow");
1038 while (words > capacity() - reserve_word_count - std::min(aligned, capacity() - reserve_word_count))
1039 resize(std::min(capacity() * 2, units::bytes{policy.maximum}.count() / 8));
1040 std::fill(data() + cursor, data() + aligned, word{0});
1041 cursor = aligned + words;
1042 return static_cast<offset>(aligned);
1043 }
1044
1045 void clear_marks() noexcept;
1054 void mark(offset first, std::size_t words = 1, std::size_t alignment_bytes = 8) noexcept {
1055 assert(first != null && first <= cursor && words <= cursor - first);
1056 note_record(first, words, alignment_bytes); mark_range(first, words);
1057 }
1058
1065 [[nodiscard]] hint_inline bool claim(offset first, std::size_t words = 1,
1066 std::size_t alignment_bytes = 8) noexcept {
1067 assert(first != null && words && first < cursor && words <= cursor - first);
1068 auto const bit = static_cast<bitmap>(bitmap{1} << (first & (block_words - 1)));
1069 auto const previous = std::atomic_ref<bitmap>{metadata[first >> block_shift].live}
1070 .fetch_or(bit, std::memory_order_relaxed);
1071 if ((previous & bit) != 0) return false;
1072 note_record(first, words, alignment_bytes);
1073 mark_range(first + 1, words - 1);
1074 return true;
1075 }
1076
1083 hint_inline void pointer(offset where, unsigned slot = 0) noexcept {
1084 assert(where != null && where < cursor && slot < fields_per_word);
1085 auto const bit = (where & (block_words - 1)) * fields_per_word + slot;
1086 std::atomic_ref<word>{metadata[where >> block_shift].pointers}
1087 .fetch_or(word{1} << bit, std::memory_order_relaxed);
1088 }
1089
1103 void compact(std::span<offset> roots = {}) noexcept;
1104
1105 private:
1106 [[nodiscard]] std::size_t prepare(std::size_t start, bool keep_null) noexcept;
1107 void move_to(word * target, detail::forwarding_tables tables) noexcept;
1108 void zero_gaps(word * target, std::size_t previous_end) const noexcept;
1109 void pack_into(std::vector<block> & output) const noexcept;
1110 void ensure(std::size_t words) noexcept;
1111 [[nodiscard]] std::size_t rotated_origin() const noexcept {
1112 return (origin + capacity() - reserve_word_count) % capacity();
1113 }
1114 [[nodiscard]] word * at_origin(std::size_t start) const noexcept {
1115 return reinterpret_cast<word *>(storage.data()) + start;
1116 }
1117 void adopt(std::size_t next_origin, std::size_t words) noexcept;
1118 template<bool tracks_starts = false> void reset(bitmap * starts = nullptr) noexcept;
1119 void compact_impl(std::span<offset> roots) noexcept;
1120 };
1121private:
1122 detail::compactor const compactor = detail::choose_compactor();
1123 work::pool workers;
1124 detail::generation_reservation reservation;
1125 generation arena;
1126 generation nursery;
1127 heap_options const policy;
1128 std::size_t minors_left;
1129 struct root_slot {
1130 offset position;
1131 std::uint32_t copies, previous, next;
1132 trace_function trace;
1133 };
1134 static_assert(sizeof(root_slot) == 24);
1135 std::vector<root_slot> root_slots;
1136 std::uint32_t roots_head = 0, free_root = 0;
1137 [[nodiscard]] hint_inline std::uint32_t add_root(offset at, trace_function trace) noexcept {
1138 assert(heap::current() == this);
1139 require_mutator();
1140 return at ? allocate_root(at, trace) : 0;
1141 }
1142 [[nodiscard]] std::uint32_t allocate_root(offset at, trace_function trace) noexcept;
1143 hint_inline void retain_root(std::uint32_t slot) noexcept {
1144 require_mutator();
1145 auto & count = root_slots[slot - 1].copies;
1146 if (count == std::numeric_limits<std::uint32_t>::max())
1147 detail::heap_failure("root reference count overflow");
1148 ++count;
1149 }
1150 hint_inline void release_root(std::uint32_t slot) noexcept {
1151 require_mutator();
1152 auto & entry = root_slots[slot - 1];
1153 if (--entry.copies) return;
1154 recycle_root(slot);
1155 }
1156 void recycle_root(std::uint32_t slot) noexcept;
1157 std::vector<std::shared_ptr<weak_entry>> weak_entries;
1158 std::deque<std::shared_ptr<weak_entry>> pending_finalizers;
1159 weak_entry * running_finalizer = nullptr;
1160 bool collecting = false;
1161 bool minor_collection = false;
1162 std::unordered_map<std::uint32_t, trace_function> remembered;
1163 // Callback identity distinguishes weak slots from raw strong slots (nullptr).
1164 // Weak slots participate in forwarding, never in the initial marking frontier.
1165 static void weak_slot(visitor &, offset) noexcept {}
1166 static constexpr unsigned block_shift = 5;
1167 static constexpr offset young_bit = 0x80000000u;
1168 static constexpr offset offset_mask = 0x7fffffffu;
1169 [[nodiscard]] static heap_options configure(heap_options config);
1170 struct configured {};
1171 heap(configured, heap_options config) noexcept;
1172 [[nodiscard]] hint_inline generation & containing(offset at) noexcept { return at & young_bit ? nursery : arena; }
1173 [[nodiscard]] hint_inline generation const & containing(offset at) const noexcept { return at & young_bit ? nursery : arena; }
1174 template<class Self>
1175 [[nodiscard]] hint_inline hint_pure
1176 auto decode(this Self & self hint_lifetimebound, offset bits) noexcept
1177 -> std::conditional_t<std::is_const_v<Self>, std::byte const, std::byte> * {
1178 using byte = std::conditional_t<std::is_const_v<Self>, std::byte const, std::byte>;
1179 // Carry selects the generation; the wrapped sum strips its tag and doubles the cell offset.
1180 std::uint32_t doubled;
1181 auto * base = (__builtin_add_overflow(bits, bits, &doubled) ? self.nursery : self.arena).data();
1182 return reinterpret_cast<byte *>(base) + std::size_t(doubled) * 4;
1183 }
1184 [[nodiscard]] hint_inline bool old_slot(void const * address, std::uint32_t & slot) const noexcept {
1185 auto const delta = reinterpret_cast<std::uintptr_t>(address) - reinterpret_cast<std::uintptr_t>(arena.storage.data());
1186 auto const bytes = arena.storage.bytes();
1187 if (delta >= 2 * bytes) return false;
1188 auto const physical = delta >= bytes ? delta - bytes : delta;
1189 auto const start = arena.origin * sizeof(word);
1190 auto const logical = physical >= start ? physical - start : physical + bytes - start;
1191 assert(logical % sizeof(offset) == 0 && logical / sizeof(offset) < 2 * arena.cursor);
1192 slot = static_cast<std::uint32_t>(logical / sizeof(offset));
1193 return true;
1194 }
1195 hint_inline void forget(void const * address) noexcept {
1196 std::uint32_t slot;
1197 if (old_slot(address, slot)) forget_slot(slot);
1198 }
1199 hint_noinline void forget_slot(std::uint32_t slot) noexcept;
1200 hint_noinline void remember_slot(std::uint32_t slot, trace_function trace) noexcept;
1201 void require_mutator() const noexcept {
1202 if (collecting) detail::heap_failure("mutation during collection");
1203 }
1204 [[nodiscard]] offset forward(offset value, bool minor) const noexcept {
1205 if (!value || (minor && !(value & young_bit))) return value;
1206 return containing(value).forward(value & offset_mask);
1207 }
1208 // Read only with the marking frontier drained; workers may otherwise own these bits.
1209 [[nodiscard]] bool marked(offset at) const noexcept {
1210 if (!at) return false;
1211 if (minor_collection && !(at & young_bit)) return true;
1212 auto const local = at & offset_mask;
1213 return (containing(at).metadata[local >> block_shift].live >> (local % block_words)) & 1;
1214 }
1215 void run_finalizer(std::shared_ptr<weak_entry> const & entry) noexcept;
1216 void drain_finalizers() noexcept;
1217 void finalize(std::shared_ptr<weak_entry> const & entry) noexcept;
1218 void compact_impl(std::span<offset> roots, bool minor = false, bool promote = false) noexcept;
1219
1220public:
1224 class host {
1225 public:
1227 class pin {
1228 friend class host;
1229 offset at_;
1230 std::size_t words_, references_ = 1, residue_;
1231 detail::heap_mapping alias_;
1232 pin(offset at, std::size_t words, std::size_t residue, detail::heap_mapping alias) noexcept
1233 : at_(at), words_(words), residue_(residue), alias_(std::move(alias)) {}
1234 public:
1235 [[nodiscard]] void * address() const noexcept { return alias_.data() + residue_ * sizeof(word); }
1236 [[nodiscard]] offset position() const noexcept { return at_; }
1237 };
1238
1239 struct gap { offset at; std::size_t words; };
1240 private:
1241 std::map<offset, std::unique_ptr<pin>> pins_;
1242 struct pin_run { std::size_t first, end, block_begin, block_end; };
1243 std::array<std::vector<pin_run>, 2> pin_runs;
1244 std::vector<gap> pin_gaps;
1245 std::vector<gap> source_gaps;
1246 // Pin padding affects ranks, never weak-target survival. Empty on the ordinary path.
1247 std::array<std::vector<bitmap>, 2> traced;
1248 [[nodiscard]] bool alive(offset at) const noexcept {
1249 if (!at) return false;
1250 if (owner.minor_collection && !(at & young_bit)) return true;
1251 auto const & live = traced[at >> 31];
1252 if (live.empty()) return owner.marked(at);
1253 auto const local = at & offset_mask;
1254 return (live[local / block_words] >> (local % block_words)) & 1u;
1255 }
1256 void prepare_pin_marks() noexcept;
1257 [[nodiscard]] std::size_t prepare_pinned(heap::generation & g, unsigned which,
1258 std::size_t start, bool keep_null) noexcept;
1259 std::array<std::vector<bitmap>, 2> starts_;
1260 template<bool tracks_starts> void finish_pinned() noexcept;
1261 template<bool tracks_starts> void finish_impl() noexcept;
1262 heap & owner;
1263 std::size_t const prefix;
1264 enum class phase { idle, marking, retry, prepared };
1265 phase state = phase::idle;
1266 std::size_t old_words = 0, young_words = 0;
1267 bool promoting = false, moving_pins = false;
1268#if defined(_WIN32)
1269 struct publication {
1270 detail::heap_mapping const * source;
1271 std::byte * target;
1272 std::size_t bytes;
1273 };
1274 mutable std::vector<publication> publications;
1275#endif
1276 public:
1278 enum class generation { old, young };
1283 explicit host(heap & storage, std::size_t prefix) noexcept;
1284 host(host const &) = delete;
1285 host & operator=(host const &) = delete;
1288 ~host() noexcept;
1294 void publish(generation which, void * target, std::size_t skip, std::size_t count) const noexcept;
1299 void unpublish(void * target, std::size_t count) const noexcept;
1303 [[nodiscard]] offset allocate(generation which, std::size_t words) noexcept {
1304 owner.require_mutator();
1305 return (which == generation::young ? owner.nursery.allocate(words) : owner.arena.allocate(words)) | (which == generation::young ? young_bit : 0);
1306 }
1307
1309 [[nodiscard]] pin * pin_object(offset at, std::size_t words) noexcept;
1311 void unpin(pin * value) noexcept;
1313 template<class F> void visit_pins(F && visit) const noexcept {
1314 for (auto const & [at, value] : pins_) visit(at);
1315 }
1316
1317 [[nodiscard]] std::span<gap const> gaps() const noexcept { return pin_gaps; }
1321 if (state != phase::idle) detail::heap_failure("enable starts during collection");
1322 if (!starts_[0].empty()) return;
1323 std::array<std::vector<bitmap>, 2> next;
1324 next[0].resize(owner.arena.metadata.size());
1325 next[1].resize(owner.nursery.metadata.size());
1326 starts_.swap(next);
1327 }
1328
1329 [[nodiscard]] bool tracks_starts() const noexcept { return !starts_[0].empty(); }
1332 void record_start(offset at) noexcept {
1333 auto const local = at & offset_mask;
1334 auto & bits = starts_[at >> 31];
1335 if ((state != phase::idle && state != phase::marking) || local < prefix ||
1336 bits.empty() || local / block_words >= bits.size())
1337 detail::heap_failure("invalid object start declaration");
1338 std::atomic_ref<bitmap>{bits[local / block_words]}.fetch_or(
1339 bitmap{1} << (local % block_words), std::memory_order_relaxed);
1340 }
1341
1342 [[nodiscard]] std::span<bitmap const> starts(generation which) const noexcept {
1343 return starts_[which == generation::young];
1344 }
1345
1347 void begin(bool minor) noexcept;
1352 template<class Trace>
1353 void trace(std::span<offset const> roots, Trace && trace,
1354 std::size_t marker_limit = 1, bool old_owners = false) noexcept
1355 requires std::is_nothrow_invocable_v<Trace &, visitor &, offset> {
1356 if (state != phase::marking || !marker_limit ||
1357 (old_owners && (!owner.minor_collection || marker_limit != 1)))
1358 detail::heap_failure("host trace outside marking phase");
1359 std::vector<trace_job> initial;
1360 initial.reserve(roots.size());
1361 for (auto at : roots)
1362 if (at && (!owner.minor_collection || old_owners || (at & young_bit))) initial.push_back({at, nullptr});
1363 owner.drain_jobs(trace, initial, marker_limit);
1364 }
1365
1366 [[nodiscard]] bool marked(offset at) const noexcept {
1367 if (state != phase::marking && state != phase::retry)
1368 detail::heap_failure("host liveness outside marking phase");
1369 return alive(at);
1370 }
1371
1375 [[nodiscard]] bool prepare(bool promote = false) noexcept;
1377 [[nodiscard]] offset forward(offset at) const noexcept {
1378 if (state != phase::prepared)
1379 detail::heap_failure("host forward outside prepared phase");
1380 return alive(at) ? owner.forward(at, owner.minor_collection) : null;
1381 }
1382
1385 void finish() noexcept;
1386 };
1387
1388 [[nodiscard]] char const * compactor_name() const noexcept { return compactor.name; }
1390 [[nodiscard]] std::size_t remembered_size() const noexcept { return remembered.size(); }
1392 template<class T> hint_inline void remember(ptr<T> const & value) noexcept {
1393 if (!value.is_young()) return;
1394 std::uint32_t slot;
1395 if (!old_slot(&value, slot)) return;
1396 remember_slot(slot, &heap::template trace_record<T>);
1397 }
1398
1399 template<class T> hint_inline void remember(std::span<ptr<T>> values) noexcept {
1400 if (values.empty()) return;
1401 std::uint32_t first;
1402 if (!old_slot(values.data(), first)) return;
1403 require_mutator();
1404 assert(std::size_t(first) + values.size() <= 2 * arena.cursor);
1405 for (std::size_t i = 0; i != values.size(); ++i)
1406 if (values[i].is_young()) remember_slot(first + static_cast<std::uint32_t>(i), &heap::template trace_record<T>);
1407 }
1408
1409 template<class T> hint_inline void remember(weak_ptr<T> const & value) noexcept {
1410 std::uint32_t slot;
1411 if (!old_slot(&value, slot)) return;
1412 if (value.is_young()) remember_slot(slot, &weak_slot); else forget_slot(slot);
1413 }
1414
1415 template<class T> hint_inline void remember(std::span<weak_ptr<T>> values) noexcept {
1416 if (values.empty()) return;
1417 std::uint32_t first;
1418 if (!old_slot(values.data(), first)) return;
1419 require_mutator();
1420 assert(std::size_t(first) + values.size() <= 2 * arena.cursor);
1421 for (std::size_t i = 0; i != values.size(); ++i) {
1422 auto const slot = first + static_cast<std::uint32_t>(i);
1423 if (values[i].is_young()) remember_slot(slot, &weak_slot); else forget_slot(slot);
1424 }
1425 }
1426
1431 explicit heap(heap_options config = {});
1433 [[nodiscard]] generation const & old() const noexcept { return arena; }
1435 [[nodiscard]] generation const & young() const noexcept { return nursery; }
1437 [[nodiscard]] heap_options configuration() const noexcept { return policy; }
1438 heap(heap const &) = delete;
1439 heap & operator=(heap const &) = delete;
1441 ~heap() noexcept;
1444 [[nodiscard]] hint_inline root_handle root(offset at) noexcept {
1445 assert(at == null || (at & offset_mask) < containing(at).cursor);
1446 return root_handle{*this, at};
1447 }
1448
1451 template<class T>
1452 [[nodiscard]] hint_inline jam::root<T> root(ptr<T> const & at) noexcept requires traceable<T> {
1453 require_record<T>();
1454 assert(!at || at.local_offset() < containing(at.get()).cursor);
1455 return jam::root<T>{root_handle{*this, at.get(), &heap::template trace_record<T>}};
1456 }
1457
1460 template<class T>
1461 [[nodiscard]] hint_inline jam::weak_root<T> weak_root(ptr<T> const & at) noexcept requires traceable<T> {
1462 require_record<T>();
1463 assert(!at || at.local_offset() < containing(at.get()).cursor);
1464 return jam::weak_root<T>{root_handle{*this, at.get(), &weak_slot}};
1465 }
1466
1471 template<traceable K, traceable V, traceable F>
1472 [[nodiscard]] jam::weak<V> mk_weak(ptr<K> const & key, ptr<V> const & value,
1473 ptr<F> const & finalizer, std::type_identity_t<void (*)(F *) noexcept> runner) noexcept;
1481 void collect() noexcept;
1484 void collect_major() noexcept;
1487 void collect_minor(bool promote = false) noexcept;
1500 template<class Trace>
1501 void collect(Trace && trace) noexcept
1502 requires std::is_nothrow_invocable_v<Trace &, visitor &, offset> {
1503 require_mutator();
1504 if (minors_left) {
1505 --minors_left;
1506 collect_minor(std::forward<Trace>(trace));
1507 } else collect_major(std::forward<Trace>(trace));
1508 }
1509
1512 template<class Trace>
1513 void collect_major(Trace && trace) noexcept
1514 requires std::is_nothrow_invocable_v<Trace &, visitor &, offset> {
1515 run_collection(std::forward<Trace>(trace), false, false);
1516 }
1517
1520 template<class Trace>
1521 void collect_minor(Trace && trace, bool promote = false) noexcept
1522 requires std::is_nothrow_invocable_v<Trace &, visitor &, offset> {
1523 run_collection(std::forward<Trace>(trace), true, promote);
1524 }
1525private:
1526 template<class Trace>
1527 void drain_jobs(Trace & trace, std::vector<trace_job> & initial, std::size_t marker_limit) noexcept {
1528 if (initial.empty()) return;
1529 auto const marker_count = std::min(marker_limit, workers.available_workers());
1530 auto group = workers.gig<trace_job>([this, &trace](work::context<trace_job> & pending) noexcept {
1531 heap_scope binding{*this};
1532 visitor visit{*this, pending};
1533 trace_job job;
1534 while (pending.pop(job)) {
1535 if (job.trace) job.trace(visit, job.at);
1536 else std::invoke(trace, visit, job.at);
1537 }
1538 }, {.concurrency = marker_count, .caller_only = marker_count == 1});
1539 group.push(std::span<trace_job const>{initial});
1540 group.close();
1541 group.join();
1542 initial.clear();
1543 }
1544 hint_inline void seed_job(std::vector<trace_job> & initial, trace_job job) noexcept {
1545 if (job.at && !marked(job.at)) initial.push_back(job);
1546 }
1547 [[nodiscard]] hint_inline std::vector<trace_job> begin_collection(bool minor) noexcept {
1548 require_mutator();
1549 // Compiler-only safepoint: publish mutator stores before tracing. Worker
1550 // synchronization is supplied by the pool; this is not a hardware fence.
1551 std::atomic_signal_fence(std::memory_order_seq_cst);
1552 collecting = true;
1553 minor_collection = minor;
1554 if (minor) nursery.clear_marks(); else clear_marks();
1555 // Each collection redeclares fields: conditional tracers may change which
1556 // slots are references. Raw clear_marks()/compact() retain their old contract.
1557 for (auto & item : nursery.metadata) item.pointers = 0;
1558 if (!minor) for (auto & item : arena.metadata) item.pointers = 0;
1559 std::vector<trace_job> initial;
1560 for (auto slot = roots_head; slot; slot = root_slots[slot - 1].next) {
1561 auto const & entry = root_slots[slot - 1];
1562 if (entry.trace != &weak_slot && entry.position != null && (!minor || (entry.position & young_bit)))
1563 initial.push_back({entry.position, entry.trace});
1564 }
1565 if (minor) for (auto const & [slot, callback] : remembered) {
1566 offset value;
1567 std::memcpy(&value, reinterpret_cast<std::byte const *>(arena.data()) + std::size_t(slot) * sizeof(offset), sizeof(value));
1568 if ((value & young_bit) && callback != &weak_slot) initial.push_back({value, callback});
1569 }
1570 for (auto const & entry : pending_finalizers) {
1571 seed_job(initial, entry->key);
1572 seed_job(initial, entry->finalizer);
1573 }
1574 for (auto * entry = running_finalizer; entry; entry = entry->previous_running) {
1575 seed_job(initial, entry->key);
1576 seed_job(initial, entry->finalizer);
1577 }
1578 return initial;
1579 }
1580 hint_inline void order_weak_entries() noexcept {
1581 std::stable_sort(weak_entries.begin(), weak_entries.end(), [](auto const & a, auto const & b) noexcept {
1582 return a->key.at < b->key.at;
1583 });
1584 }
1585 [[nodiscard]] hint_inline bool retain_weak(std::shared_ptr<weak_entry> const & entry,
1586 std::vector<trace_job> & initial) noexcept {
1587 if (marked(entry->key.at)) {
1588 seed_job(initial, entry->value);
1589 seed_job(initial, entry->finalizer);
1590 return true;
1591 }
1592 // Retire before retaining K/F: this entry never rearms, even on resurrection.
1593 entry->active = false;
1594 pending_finalizers.push_back(entry);
1595 seed_job(initial, entry->key);
1596 seed_job(initial, entry->finalizer);
1597 return false;
1598 }
1599 void finish_collection(bool minor, bool promote) noexcept {
1600 compact_impl({}, minor, promote);
1601 collecting = false; minor_collection = false;
1602 if (!minor) minors_left = policy.minor_collections;
1603 std::atomic_signal_fence(std::memory_order_seq_cst);
1604 drain_finalizers();
1605 }
1606 void run_collection(auto && trace, bool minor, bool promote) noexcept {
1607 std::size_t retained = 0;
1608 {
1609 auto initial = begin_collection(minor);
1610 drain_jobs(trace, initial, workers.available_workers());
1611 order_weak_entries();
1612 for (auto const & entry : weak_entries) {
1613 if (retain_weak(entry, initial)) weak_entries[retained++] = entry;
1614 drain_jobs(trace, initial, workers.available_workers());
1615 }
1616 }
1617 weak_entries.resize(retained);
1618 finish_collection(minor, promote);
1619 }
1620public:
1625 template<class T, class... Args>
1626 [[nodiscard]] ptr<T> mk(Args &&... args) noexcept requires traceable<T> {
1627 require_record<T>();
1628 static_assert(noexcept(T{std::forward<Args>(args)...}), "record construction must be noexcept");
1629 require_mutator();
1630 // Arguments can borrow the current nursery view. Construct before allocation
1631 // can remap it; transport the result under the managed byte-relocation contract.
1632 T const value{std::forward<Args>(args)...};
1633 auto const at = nursery.allocate(record_words<T>, std::max(alignof(T), sizeof(word)));
1634 std::fill_n(nursery.data() + at, record_words<T>, word{0});
1635 // Transport the complete representation, including a polymorphic vptr.
1636 std::memcpy(nursery.data() + at, static_cast<void const *>(&value), sizeof(T));
1637 return ptr<T>{young_bit | at};
1638 }
1639
1643 template<class T>
1644 [[nodiscard]] hint_inline T * address(ptr<T> const & at) noexcept requires traceable<T> {
1645 require_record<T>();
1646 assert(!collecting);
1647 return record_address<T>(at.get());
1648 }
1649
1652 template<class T>
1653 [[nodiscard]] T load(ptr<T> const & at) const noexcept requires traceable<T> {
1654 require_record<T>();
1655 assert(at && at.local_offset() < containing(at.get()).cursor
1656 && record_words<T> <= containing(at.get()).cursor - at.local_offset());
1657 return *std::launder(reinterpret_cast<T const *>(decode(at.get())));
1658 }
1659
1662 template<class T>
1663 void store(ptr<T> const & at, T const & value) noexcept requires traceable<T> {
1664 require_record<T>();
1665 require_mutator();
1666 heap_scope binding{*this};
1667 auto * destination = record_address<T>(at.get());
1668 if (destination != &value) *destination = value;
1669 }
1670 [[nodiscard]] std::size_t capacity() const noexcept { return arena.capacity(); }
1671 [[nodiscard]] std::size_t reserved() const noexcept { return arena.reserved(); }
1672 [[nodiscard]] std::size_t used() const noexcept { return arena.used() + nursery.used() - 1; }
1673 [[nodiscard]] std::size_t start() const noexcept { return arena.start(); }
1674 [[nodiscard]] std::size_t page_words() const noexcept { return arena.page_words(); }
1675 [[nodiscard]] hint_inline hint_pure auto * data(this auto & self) noexcept { return self.arena.data(); }
1676 [[nodiscard]] decltype(auto) operator[](this auto & self, offset index) noexcept { return self.containing(index)[index & offset_mask]; }
1677 [[nodiscard]] offset field(offset cell, unsigned slot = 0) const noexcept { return containing(cell).field(cell & offset_mask, slot); }
1678 void set_field(offset cell, offset value, unsigned slot = 0) noexcept { require_mutator(); containing(cell).set_field(cell & offset_mask, value, slot);
1679 if (!(cell & young_bit) && (value & young_bit)) remembered.insert_or_assign(cell * 2 + slot, nullptr); }
1680 [[nodiscard]] std::span<block const> blocks() const noexcept { return arena.blocks(); }
1681 [[nodiscard]] offset allocate(std::size_t words, std::size_t alignment_bytes = 8) noexcept {
1682 require_mutator(); return arena.allocate(words, alignment_bytes);
1683 }
1684 void clear_marks() noexcept { arena.clear_marks(); nursery.clear_marks(); }
1685 void mark(offset first, std::size_t words = 1, std::size_t alignment_bytes = 8) noexcept { containing(first).mark(first & offset_mask, words, alignment_bytes); }
1686 [[nodiscard]] hint_inline bool claim(offset first, std::size_t words = 1, std::size_t alignment_bytes = 8) noexcept {
1687 if (minor_collection && !(first & young_bit)) return false;
1688 return containing(first).claim(first & offset_mask, words, alignment_bytes);
1689 }
1690 hint_inline void pointer(offset where, unsigned slot = 0) noexcept { containing(where).pointer(where & offset_mask, slot); }
1691 void compact(std::span<offset> roots = {}) noexcept;
1692
1693};
1694
1695} // namespace jam
1696
1697// Keep the fixed marking queue's cold synchronization path in this module.
1698// Instantiating it in consumers trips Clang's handling of libstdc++ internal
1699// thread helpers shared by the Jam and Work global module fragments.
1701extern template void work::detail::state<jam::heap::trace_job>::communicate(lane &) noexcept;
1702template void work::detail::state<jam::heap::trace_job>::communicate(lane &) noexcept;
1704
1705namespace jam {
1706
1707inline heap_scope::heap_scope(heap & arena) noexcept : previous(heap::current()) {
1708 detail::active_heap = &arena;
1709}
1710
1715export template<class T>
1716class root : private heap::root_handle {
1717 using base = heap::root_handle;
1718 friend class heap;
1719 hint_inline explicit root(base value) noexcept : base(std::move(value)) {}
1720public:
1722 root() noexcept = default;
1725 hint_inline root(ptr<T> const & value) noexcept requires traceable<T> : root(heap::current()->root(value)) {}
1727 template<class U> requires (!std::same_as<T, U>) && std::convertible_to<ptr<U>, ptr<T>>
1728 hint_inline root(ptr<U> const & value) noexcept : root(ptr<T>{value}) {}
1729
1731 [[nodiscard]] hint_inline ptr<T> get() const noexcept { return ptr<T>{base::get()}; }
1733 [[nodiscard]] hint_inline operator ptr<T>() const noexcept { return get(); }
1735 [[nodiscard]] hint_inline T * operator->() const noexcept { return get().operator->(); }
1737 [[nodiscard]] hint_inline T & operator*() const noexcept { return *get(); }
1739 [[nodiscard]] hint_inline explicit operator bool() const noexcept { return base::get() != heap::null; }
1740};
1741
1748export template<class T>
1749class weak_root : private heap::root_handle {
1750 using base = heap::root_handle;
1751 friend class heap;
1752 hint_inline explicit weak_root(base value) noexcept : base(std::move(value)) {}
1753public:
1755 weak_root() noexcept = default;
1757 hint_inline weak_root(ptr<T> const & value) noexcept requires traceable<T>
1758 : weak_root(heap::current()->weak_root(value)) {}
1759
1760 hint_inline weak_root(root<T> const & value) noexcept requires traceable<T>
1761 : weak_root(value.get()) {}
1762
1763 template<class U> requires (!std::same_as<T, U>) && std::convertible_to<ptr<U>, ptr<T>>
1764 hint_inline weak_root(ptr<U> const & value) noexcept : weak_root(ptr<T>{value}) {}
1766 [[nodiscard]] hint_inline bool expired() const noexcept { return base::get() == heap::null; }
1769 [[nodiscard]] hint_inline root<T> lock() const noexcept requires traceable<T> {
1770 if (expired()) return {};
1771 return heap::current()->root(ptr<T>{base::get()});
1772 }
1773
1774 hint_inline void reset() noexcept { base::operator=(base{}); }
1776 hint_inline void swap(weak_root & other) noexcept {
1777 std::swap(static_cast<base &>(*this), static_cast<base &>(other));
1778 }
1779
1780 friend hint_inline void swap(weak_root & a, weak_root & b) noexcept { a.swap(b); }
1781};
1782
1787export template<class V>
1788class weak {
1789 friend class heap;
1790 std::shared_ptr<heap::weak_entry> entry;
1791 explicit weak(std::shared_ptr<heap::weak_entry> value) noexcept : entry(std::move(value)) {}
1792public:
1793 weak() noexcept = default;
1795 [[nodiscard]] bool expired() const noexcept { return !entry || !entry->active; }
1798 [[nodiscard]] hint_inline root<V> lock() const noexcept {
1799 if (expired()) return {};
1800 return heap::current()->root(ptr<V>{entry->value.at});
1801 }
1802
1804 hint_inline void finalize() const noexcept {
1805 // A callback may destroy the very handle used to invoke it.
1806 auto keep = entry;
1807 if (keep && keep->active) heap::current()->finalize(keep);
1808 }
1809};
1810
1811template<traceable K, traceable V, traceable F>
1812jam::weak<V> heap::mk_weak(ptr<K> const & key, ptr<V> const & value,
1813 ptr<F> const & finalizer, std::type_identity_t<void (*)(F *) noexcept> runner) noexcept {
1814 require_mutator();
1815 if (!runner) detail::heap_failure("mk_weak requires a runner");
1816 auto entry = std::make_shared<finalizer_entry<F>>();
1817 entry->key = {key.get(), &trace_record<K>};
1818 entry->value = {value.get(), &trace_record<V>};
1819 entry->finalizer = {finalizer.get(), &trace_record<F>};
1820 entry->runner = runner;
1821 entry->invoke = [](heap & owner, weak_entry & base) noexcept {
1822 auto & entry = static_cast<finalizer_entry<F> &>(base);
1823 entry.runner(entry.finalizer.at ? owner.template record_address<F>(entry.finalizer.at) : nullptr);
1824 };
1825 weak_entries.push_back(entry);
1826 return jam::weak<V>{std::move(entry)};
1827}
1828
1829template<class T>
1830constexpr void weak_ptr<T>::update_barrier() noexcept {
1831 if !consteval { if (auto * h = heap::current()) h->remember(*this); }
1832}
1833template<class T>
1834constexpr weak_ptr<T>::weak_ptr(ptr<T> const & value) noexcept : position(value.get()) {
1835 if (is_young()) update_barrier();
1836}
1837template<class T>
1838weak_ptr<T>::weak_ptr(root<T> const & value) noexcept : weak_ptr(value.get()) {}
1839template<class T>
1840constexpr weak_ptr<T>::weak_ptr(weak_ptr const & other) noexcept : position(other.position) {
1841 if (is_young()) update_barrier();
1842}
1843template<class T>
1844constexpr weak_ptr<T> & weak_ptr<T>::operator=(weak_ptr const & other) noexcept {
1845 auto const changed = position ^ other.position;
1846 position = other.position;
1847 if (changed & 0x80000000u) update_barrier();
1848 return *this;
1849}
1850template<class T>
1851constexpr weak_ptr<T>::weak_ptr(weak_ptr && other) noexcept : position(std::exchange(other.position, 0)) {
1852 if (is_young()) { update_barrier(); other.update_barrier(); }
1853}
1854template<class T>
1855constexpr weak_ptr<T> & weak_ptr<T>::operator=(weak_ptr && other) noexcept {
1856 if (this == &other) return *this;
1857 *this = static_cast<weak_ptr const &>(other);
1858 auto const previous = std::exchange(other.position, 0);
1859 if (previous & 0x80000000u) other.update_barrier();
1860 return *this;
1861}
1862template<class T>
1863constexpr weak_ptr<T>::~weak_ptr() noexcept {
1864 if !consteval { if (auto * h = heap::current()) h->forget(this); }
1865}
1866template<class T>
1867constexpr void weak_ptr<T>::swap(weak_ptr & other) noexcept {
1868 auto const changed = position ^ other.position;
1869 std::swap(position, other.position);
1870 if (changed & 0x80000000u) { update_barrier(); other.update_barrier(); }
1871}
1872template<class T>
1873root<T> weak_ptr<T>::lock() const noexcept requires traceable<T> {
1874 if (!position) return {};
1875 return root<T>{ptr<T>{position}};
1876}
1877
1878template<class T>
1879constexpr void ptr<T>::update_barrier() noexcept {
1880 if !consteval { if (auto * h = heap::current()) {
1881 if (is_young()) h->remember(*this); else h->forget(this);
1882 } }
1883}
1884template<class T>
1885constexpr ptr<T>::ptr(offset at) noexcept : position(at) {
1886 if (is_young()) update_barrier();
1887}
1888template<class T>
1889constexpr ptr<T>::ptr(ptr const & other) noexcept : ptr(other.position) {}
1890template<class T>
1891template<class U> requires (!std::same_as<T, U>) && std::derived_from<U, T>
1892 && detail::allocation_trace<T> && requires(T * p) { static_cast<U *>(p); }
1893constexpr ptr<T>::ptr(ptr<U> const & other) noexcept : ptr(other.get()) {
1894 if !consteval {
1895 assert(!other || !heap::current() || static_cast<void const *>(static_cast<T const *>(other.operator->()))
1896 == static_cast<void const *>(other.operator->()));
1897 }
1898}
1899template<class T>
1900constexpr ptr<T> & ptr<T>::operator=(ptr const & other) noexcept {
1901 auto const changed = position ^ other.position;
1902 position = other.position;
1903 // Remembered entries name a slot and T, not its current young target.
1904 if (changed & heap::young_bit) update_barrier();
1905 return *this;
1906}
1907template<class T>
1908constexpr ptr<T>::ptr(ptr && other) noexcept : position(std::exchange(other.position, 0)) {
1909 if (is_young()) { update_barrier(); other.update_barrier(); }
1910}
1911template<class T>
1912constexpr ptr<T> & ptr<T>::operator=(ptr && other) noexcept {
1913 if (this == &other) return *this;
1914 *this = static_cast<ptr const &>(other);
1915 auto const previous = std::exchange(other.position, 0);
1916 if (previous & heap::young_bit) other.update_barrier();
1917 return *this;
1918}
1919template<class T>
1920constexpr void ptr<T>::swap(ptr & other) noexcept {
1921 auto const changed = position ^ other.position;
1922 std::swap(position, other.position);
1923 if (changed & heap::young_bit) { update_barrier(); other.update_barrier(); }
1924}
1925template<class T>
1926constexpr ptr<T>::~ptr() noexcept {
1927 if !consteval { if (auto * h = heap::current()) h->forget(this); }
1928}
1929template<class T>
1930T * ptr<T>::operator->() const noexcept {
1931 return heap::current()->address(*this);
1932}
1933template<class T>
1934T & ptr<T>::operator*() const noexcept { return *operator->(); }
1935
1936template<class T>
1937hint_inline void ptr<T>::prefetch_marks() const noexcept {
1938 if (!position) return;
1939 auto const * arena = heap::current();
1940 assert(arena && local_offset() < arena->containing(position).used());
1941 __builtin_prefetch(&arena->containing(position).blocks()[local_offset() >> heap::block_shift].live, 0, 3);
1942}
1943template<class T>
1944hint_inline void ptr<T>::prefetch() const noexcept {
1945 if (!position) return;
1946 auto const * arena = heap::current();
1947 assert(arena && local_offset() < arena->containing(position).used());
1948 __builtin_prefetch(arena->decode(position), 0, 3);
1949}
1950}
1951
1952namespace jam {
1953heap::generation::settings heap::generation::configure(generation_options config) {
1954 if (config.maximum > units::bytes{maximum_bytes} || config.capacity > units::bytes{maximum_bytes} || config.reserve > units::bytes{maximum_bytes})
1955 throw std::length_error("jam generation exceeds 16 GiB");
1956 constexpr auto page = static_cast<std::size_t>(units::pages::ratio::num);
1957 if (detail::heap_mapping::page_size() != page)
1958 detail::heap_failure("platform page size differs from build invariant");
1959 if (!valid_options(config) || page < 512 || page > maximum_bytes || !std::has_single_bit(page))
1960 detail::heap_failure("invalid byte sizes, page size or worker count");
1961 if (config.reserve > config.capacity / 2)
1962 detail::heap_failure("capacity must hold twice the reserve");
1963 auto const capacity = units::bytes{config.capacity}.count();
1964 auto const reserve = units::bytes{config.reserve}.count();
1965 return {page / 8, reserve / 8, 2 * reserve / 8, capacity, config};
1966}
1967
1968heap::generation::generation(settings s, detail::compactor const & c, work::pool & w, std::byte * address) noexcept
1969 : policy(s.policy), compactor(c), workers(w),
1970 page_word_count(s.page_words), reserve_word_count(s.reserved),
1971 minimum_capacity(s.minimum), storage(s.bytes, address, units::bytes{s.policy.maximum}.count()),
1972 view_base(reinterpret_cast<word *>(storage.data())), metadata(s.bytes / (8 * block_words)) {
1973 alignment.resize(((metadata.size() + 7) / 8) * 4);
1974}
1975
1976void heap::generation::resize(std::size_t words) noexcept {
1977 assert(words % page_word_count == 0 && words >= minimum_capacity && words <= maximum_bytes / 8);
1978 assert(cursor <= words - reserve_word_count);
1979 std::vector<block> next_metadata(words / block_words);
1980 std::copy_n(metadata.begin(), (cursor + block_words - 1) / block_words, next_metadata.begin());
1981 auto const next_origin = words - reserve_word_count;
1982 auto next = storage.resized(origin * 8, cursor * 8, words * 8, next_origin * 8);
1983 alignment.resize(((next_metadata.size() + 7) / 8) * 4);
1984 storage.replace(next); metadata.swap(next_metadata);
1985 origin = next_origin;
1986 view_base = reinterpret_cast<word *>(storage.data()) + origin;
1987}
1988
1989heap::generation::generation(generation_options config, detail::compactor const & c, work::pool & w, std::byte * address)
1990 : generation(configure(config), c, w, address) {}
1991
1993 for (auto & item : metadata) {
1994 item.live = 0;
1995 item.destination = 0;
1996 }
1997 std::fill(alignment.begin(), alignment.end(), 0);
1998 has_alignment = false;
1999}
2000
2001void heap::generation::compact(std::span<offset> roots) noexcept {
2002 require_mutator();
2003 std::atomic_signal_fence(std::memory_order_seq_cst);
2004 collecting = true;
2005 compact_impl(roots);
2006 collecting = false;
2007 std::atomic_signal_fence(std::memory_order_seq_cst);
2008}
2009
2010std::size_t heap::generation::prepare(std::size_t start, bool keep_null) noexcept {
2011 // Keep the null cell in the packed prefix, including aligned collections.
2012 // It is padding, never a record or a source of outgoing pointers.
2013 data()[0] = 0;
2014 if (keep_null) metadata[0].live |= bitmap{1};
2015 else metadata[0].live &= ~bitmap{1};
2016 metadata[0].pointers &= ~word{(1u << fields_per_word) - 1};
2017 auto const old_blocks = (cursor + block_words - 1) / block_words;
2018 // A parallel prefix scan could compose joined groups' layout functions:
2019 // F(x) = align_up(x, 1 << k) + retained_cells_after_dilation. Resolve group
2020 // boundaries/k first; composing (max k, summed counts) loses padding.
2021 // Eight input-residue displacements suffice (k <= 3), with associative
2022 // composition c[r] = a[r] + b[(r + a[r]) & 7]. All destinations must be
2023 // ready before workers forward arbitrary pointers into distant blocks.
2024 // This whole pass measured only 0.5-1.7% of GC on eight-byte-aligned trees
2025 // and chains with 1/4 workers, so scan overhead could erase the benefit.
2026 // Sparse retention and higher alignments were not covered; reprofile those
2027 // workloads before adding a parallel scan.
2028 has_alignment = false;
2029 std::size_t live_words = start;
2030 for (std::size_t begin = 0; begin < old_blocks;) {
2031 auto end = begin + 1;
2032 unsigned k = std::popcount(flags(begin) & 7u);
2033 while ((flags(end - 1) & 8u) && end < old_blocks) {
2034 k = std::max(k, static_cast<unsigned>(std::popcount(flags(end) & 7u))); ++end;
2035 }
2036 live_words = (live_words + (std::size_t{1} << k) - 1) & ~((std::size_t{1} << k) - 1);
2037 for (auto i = begin; i != end; ++i) {
2038 auto & item = metadata[i];
2039 item.pointers &= pointer_cells(item.live);
2040 // Publish the joined group's effective k in the existing nibbles.
2041 // live remains the exact claims; dilation is only a register value.
2042 auto const shift = (i & 1) * 4;
2043 alignment[i >> 1] = static_cast<std::uint8_t>((alignment[i >> 1] & ~(7u << shift))
2044 | (((1u << k) - 1) << shift));
2045 has_alignment |= k != 0;
2046 item.destination = static_cast<offset>(live_words);
2047 live_words += std::popcount(detail::retained(item.live, k));
2048 }
2049 begin = end;
2050 }
2051 return live_words;
2052}
2053
2054void heap::generation::move_to(word * target, detail::forwarding_tables tables) noexcept {
2055 auto const old_blocks = (cursor + block_words - 1) / block_words;
2056 auto const source = data();
2057 auto const source_pages = (cursor + page_word_count - 1) / page_word_count;
2058 auto const wave_pages = reserve_word_count / page_word_count;
2059 auto move_page = [&](std::size_t page) noexcept {
2060 auto const begin = page * (page_word_count / block_words);
2061 auto const end = std::min(old_blocks, begin + page_word_count / block_words);
2062 compactor.move(source, target, metadata.data(), begin, end, tables, alignment_table());
2063 };
2064 if (workers.available_workers() > 1 && source_pages > 1) {
2065 auto done = std::make_unique<std::atomic<bool>[]>(source_pages);
2066 std::atomic<std::size_t> next{0}, front{0};
2067 auto task = [&](std::size_t) noexcept {
2068 for (;;) {
2069 auto const page = next.fetch_add(1, std::memory_order_relaxed);
2070 if (page >= source_pages) return;
2071 auto floor = front.load(std::memory_order_acquire);
2072 while (page - floor >= wave_pages) {
2073 front.wait(floor, std::memory_order_relaxed);
2074 floor = front.load(std::memory_order_acquire);
2075 }
2076 move_page(page);
2077 done[page].store(true, std::memory_order_release);
2078 // Every completion publishes through this RMW chain, even when an
2079 // older page still blocks the prefix. The last publisher therefore
2080 // sees all earlier done flags; a store-buffering cycle cannot stall.
2081 floor = front.fetch_add(0, std::memory_order_acq_rel);
2082 for (;;) {
2083 auto end = floor;
2084 while (end != source_pages && done[end].load(std::memory_order_acquire)) ++end;
2085 if (end == floor) break;
2086 if (front.compare_exchange_strong(floor, end, std::memory_order_acq_rel)) {
2087 front.notify_all(); break;
2088 }
2089 floor = front.load(std::memory_order_acquire);
2090 }
2091 }
2092 };
2093 auto group = workers.gig<std::size_t>(task);
2094 for (std::size_t i = 0; i != std::min(workers.available_workers(), wave_pages); ++i) group.push(i);
2095 group.close();
2096 group.join();
2097 } else for (std::size_t page = 0; page < source_pages; ++page) move_page(page);
2098}
2099
2100void heap::generation::zero_gaps(word * target, std::size_t previous_end) const noexcept {
2101 auto const old_blocks = (cursor + block_words - 1) / block_words;
2102 for (std::size_t i = 0; i != old_blocks; ++i) {
2103 auto const next = std::size_t(metadata[i].destination & offset_mask);
2104 std::fill(target + previous_end, target + next, word{0});
2105 previous_end = next + std::popcount(detail::retained(metadata[i], alignment_table(), i));
2106 }
2107}
2108
2109void heap::generation::pack_into(std::vector<block> & output) const noexcept {
2110 auto const old_blocks = (cursor + block_words - 1) / block_words;
2111 compactor.pack(metadata.data(), output.data(), old_blocks, alignment_table());
2112}
2113
2114void heap::generation::ensure(std::size_t words) noexcept {
2115 auto const maximum = units::bytes{policy.maximum}.count() / sizeof(word);
2116 if (words > maximum - reserve_word_count) detail::heap_failure("generation capacity overflow");
2117 while (words > capacity() - reserve_word_count) resize(std::min(2 * capacity(), maximum));
2118}
2119
2120void heap::generation::adopt(std::size_t next_origin, std::size_t words) noexcept {
2121 auto const old_blocks = (cursor + block_words - 1) / block_words;
2122 cursor = words; origin = next_origin; view_base = at_origin(origin);
2123 auto const blocks = (cursor + block_words - 1) / block_words;
2124 for (std::size_t i = 0; i != blocks; ++i) {
2125 auto const count = std::min(block_words, cursor - i * block_words);
2126 metadata[i].live = ~bitmap{0} >> (block_words - count);
2127 metadata[i].destination = 0;
2128 }
2129 for (auto i = blocks; i < old_blocks; ++i) metadata[i] = {};
2130 std::fill(alignment.begin(), alignment.end(), 0);
2131 has_alignment = false;
2132 auto const smaller = std::max(minimum_capacity, (capacity() / page_word_count / 2) * page_word_count);
2133 if (policy.shrink_shift && smaller < capacity()
2134 && cursor < (capacity() >> policy.shrink_shift)
2135 && cursor <= smaller - reserve_word_count) resize(smaller);
2136}
2137
2138template<bool tracks_starts>
2139void heap::generation::reset(bitmap * starts) noexcept {
2140 for (std::size_t i = 0; i != metadata.size(); ++i) {
2141 metadata[i] = {};
2142 if constexpr (tracks_starts) starts[i] = 0;
2143 }
2144 std::fill(alignment.begin(), alignment.end(), 0);
2145 has_alignment = false;
2146 cursor = 1; data()[0] = 0;
2147}
2148
2149void heap::generation::compact_impl(std::span<offset> roots) noexcept {
2150 auto const live_words = prepare(0, true);
2151 auto const next_origin = rotated_origin();
2152 auto * target = at_origin(next_origin);
2153 move_to(target, {metadata.data(), nullptr, alignment_table(), nullptr});
2154 for (auto & root : roots) root = forward(root);
2155 zero_gaps(target, 0);
2156 pack_into(metadata);
2157 adopt(next_origin, live_words);
2158}
2159}
2160
2161namespace jam {
2162heap_options heap::configure(heap_options config) {
2163 static_cast<void>(generation::configure(config.old));
2164 static_cast<void>(generation::configure(config.young));
2165 if (!config.workers) detail::heap_failure("worker count must be positive");
2166 return config;
2167}
2168
2169heap::heap(configured, heap_options config) noexcept
2170 : workers(config.workers),
2171 reservation(units::bytes{config.old.maximum}.count(), units::bytes{config.young.maximum}.count()),
2172 arena(config.old, compactor, workers, reservation.data()),
2173 nursery(config.young, compactor, workers, reservation.data() + 2 * units::bytes{config.old.maximum}.count()),
2174 policy(config), minors_left(config.minor_collections) {}
2175
2176void heap::compact_impl(std::span<offset> roots, bool minor, bool promote) noexcept {
2177 auto const old_end = minor ? arena.cursor : arena.prepare(0, true);
2178 auto const young_start = minor && !promote ? std::size_t(young_bit) : old_end;
2179 auto const end = nursery.prepare(young_start, minor && !promote);
2180 auto & destination = minor && !promote ? nursery : arena;
2181 auto const live_words = end - (minor && !promote ? std::size_t(young_bit) : 0);
2182 destination.ensure(live_words);
2183 // Growth may rebase metadata, so form the shared forwarding tables afterward.
2184 detail::forwarding_tables tables{minor ? nullptr : arena.metadata.data(), nursery.metadata.data(),
2185 minor ? nullptr : arena.alignment_table(), nursery.alignment_table()};
2186 auto const next_origin = minor && promote ? destination.origin : destination.rotated_origin();
2187 auto * target = destination.at_origin(next_origin);
2188 if (!minor) {
2189 arena.move_to(target, tables);
2190 arena.zero_gaps(target, 0);
2191 }
2192 nursery.move_to(target, tables);
2193 nursery.zero_gaps(target, minor && !promote ? 0 : old_end);
2194 for (auto & root : roots) root = forward(root, minor);
2195 for (auto slot = roots_head; slot; slot = root_slots[slot - 1].next) {
2196 auto & entry = root_slots[slot - 1];
2197 entry.position = forward(entry.position, minor);
2198 }
2199 if (minor) for (auto entry = remembered.begin(); entry != remembered.end();) {
2200 auto const slot = entry->first;
2201 auto * address = reinterpret_cast<std::byte *>(arena.data()) + std::size_t(slot) * sizeof(offset);
2202 offset value;
2203 std::memcpy(&value, address, sizeof(value));
2204 value = forward(value, true);
2205 std::memcpy(address, &value, sizeof(value)); // Collector writes bypass barriers.
2206 if (value) ++entry; else entry = remembered.erase(entry);
2207 }
2208 auto forward_entry = [&](weak_entry & entry) noexcept {
2209 entry.key.at = forward(entry.key.at, minor);
2210 entry.value.at = entry.active ? forward(entry.value.at, minor) : null;
2211 entry.finalizer.at = forward(entry.finalizer.at, minor);
2212 };
2213 for (auto const & entry : weak_entries) forward_entry(*entry);
2214 for (auto const & entry : pending_finalizers) forward_entry(*entry);
2215 for (auto * entry = running_finalizer; entry; entry = entry->previous_running) forward_entry(*entry);
2216 // Both generations and every external/remembered root have consumed the
2217 // forwarding tables. Packing may now overwrite their pointer masks.
2218 if (!minor) arena.pack_into(arena.metadata);
2219 nursery.pack_into(destination.metadata);
2220 destination.adopt(next_origin, live_words);
2221 if (!minor || promote) { nursery.reset(); remembered.clear(); }
2222}
2223
2224heap::heap(heap_options config)
2225 : heap(configured{}, configure(config)) {}
2226
2227heap::~heap() noexcept {
2228 if (roots_head || running_finalizer) detail::heap_failure("heap destroyed with attached roots or callbacks");
2229 for (auto const & entry : weak_entries) entry->active = false;
2230}
2231
2232void heap::collect() noexcept {
2233 collect([](visitor &, offset) noexcept { detail::heap_failure("untyped target in typed collection"); });
2234}
2235
2236void heap::collect_major() noexcept {
2237 collect_major([](visitor &, offset) noexcept { detail::heap_failure("untyped target in typed collection"); });
2238}
2239
2240void heap::collect_minor(bool promote) noexcept {
2241 collect_minor([](visitor &, offset) noexcept { detail::heap_failure("untyped target in typed collection"); }, promote);
2242}
2243
2244void heap::compact(std::span<offset> roots) noexcept {
2245 require_mutator();
2246 if (!weak_entries.empty() || !pending_finalizers.empty() || running_finalizer)
2247 detail::heap_failure("raw compact requires no weak registrations or pending finalizers");
2248 std::atomic_signal_fence(std::memory_order_seq_cst);
2249 collecting = true; compact_impl(roots); collecting = false;
2250 std::atomic_signal_fence(std::memory_order_seq_cst);
2251}
2252}
2253
2254namespace jam {
2255std::uint32_t heap::allocate_root(offset at, trace_function trace) noexcept {
2256 auto slot = free_root;
2257 if (slot) free_root = root_slots[slot - 1].next;
2258 else {
2259 if (root_slots.size() == std::numeric_limits<std::uint32_t>::max())
2260 detail::heap_failure("root slot capacity overflow");
2261 root_slots.push_back({});
2262 slot = static_cast<std::uint32_t>(root_slots.size());
2263 }
2264 root_slots[slot - 1] = {at, 1, 0, roots_head, trace};
2265 if (roots_head) root_slots[roots_head - 1].previous = slot;
2266 roots_head = slot;
2267 return slot;
2268}
2269
2270void heap::recycle_root(std::uint32_t slot) noexcept {
2271 auto & entry = root_slots[slot - 1];
2272 if (entry.previous) root_slots[entry.previous - 1].next = entry.next;
2273 else roots_head = entry.next;
2274 if (entry.next) root_slots[entry.next - 1].previous = entry.previous;
2275 entry = {0, 0, 0, free_root, nullptr};
2276 free_root = slot;
2277}
2278
2279hint_noinline void heap::forget_slot(std::uint32_t slot) noexcept {
2280 remembered.erase(slot);
2281}
2282
2283hint_noinline void heap::remember_slot(std::uint32_t slot, trace_function trace) noexcept {
2284 require_mutator();
2285 remembered.insert_or_assign(slot, trace);
2286}
2287}
2288
2289namespace jam {
2290void heap::run_finalizer(std::shared_ptr<weak_entry> const & entry) noexcept {
2291 entry->previous_running = running_finalizer;
2292 running_finalizer = entry.get();
2293 {
2294 heap_scope binding{*this};
2295 entry->invoke(*this, *entry);
2296 }
2297 running_finalizer = entry->previous_running;
2298}
2299
2300void heap::drain_finalizers() noexcept {
2301 if (running_finalizer) return;
2302 while (!pending_finalizers.empty()) {
2303 auto entry = std::move(pending_finalizers.front());
2304 pending_finalizers.pop_front();
2305 run_finalizer(entry);
2306 }
2307}
2308
2309void heap::finalize(std::shared_ptr<weak_entry> const & entry) noexcept {
2310 require_mutator();
2311 if (!entry->active) return;
2312 entry->active = false;
2313 std::erase(weak_entries, entry);
2314 run_finalizer(entry);
2315 drain_finalizers();
2316}
2317}
2318
2319namespace jam {
2320heap::host::host(heap & storage, std::size_t prefix) noexcept : owner(storage), prefix(prefix) {
2321 owner.require_mutator();
2322 for (auto * g : {&owner.arena, &owner.nursery}) {
2323 if (g->used() != 1 || g->policy.capacity != g->policy.maximum || g->policy.shrink_shift ||
2324 !prefix || prefix % g->page_words() || prefix >= g->capacity() - g->reserved())
2325 detail::heap_failure("host requires fresh fixed generations and a whole-page guard");
2326 }
2327 static_cast<void>(owner.arena.allocate(prefix - 1));
2328 static_cast<void>(owner.nursery.allocate(prefix - 1));
2329}
2330
2332 if (state != phase::idle) detail::heap_failure("unfinished host collection");
2333 if (!pins_.empty()) detail::heap_failure("host destroyed with open pins");
2334#if defined(_WIN32)
2335 if (!publications.empty()) detail::heap_failure("host destroyed with published Windows views");
2336#endif
2337}
2338
2339void heap::host::publish(generation which, void * target, std::size_t skip, std::size_t count) const noexcept {
2340 if (state != phase::idle) detail::heap_failure("publish during host collection");
2341 auto const & g = which == generation::young ? owner.nursery : owner.arena;
2342 auto const & config = which == generation::young ? owner.policy.young : owner.policy.old;
2343 if (config.capacity != config.maximum || config.shrink_shift ||
2344 skip > g.capacity() || count > g.capacity() - skip)
2345 detail::heap_failure("published heap requires a fixed generation");
2346#if defined(_WIN32)
2347 auto const address = reinterpret_cast<std::uintptr_t>(target);
2348 auto const bytes = count * 8;
2349 if (address % detail::heap_mapping::page_size() || skip % g.page_words() ||
2350 count % g.page_words() || bytes > std::numeric_limits<std::uintptr_t>::max() - address)
2351 detail::heap_failure("invalid published heap window");
2352 if (!bytes) return;
2353 for (auto const * space : {&owner.arena, &owner.nursery}) {
2354 auto const begin = reinterpret_cast<std::uintptr_t>(space->storage.data());
2355 if (address < begin + space->storage.bytes() * 2 && begin < address + bytes)
2356 detail::heap_failure("published heap window overlaps a private view");
2357 }
2358 bool found = false;
2359 for (auto const & window : publications) {
2360 auto const begin = reinterpret_cast<std::uintptr_t>(window.target);
2361 if (address < begin + window.bytes && begin < address + bytes) {
2362 if (window.target != target || window.bytes != bytes || window.source != &g.storage)
2363 detail::heap_failure("published heap windows must be disjoint or identical");
2364 detail::heap_mapping::unpublish(window.target, window.bytes);
2365 found = true;
2366 break;
2367 }
2368 }
2369 if (!found) publications.push_back({&g.storage, static_cast<std::byte *>(target), bytes});
2370#endif
2371 g.storage.publish(((g.origin + skip) % g.capacity()) * 8,
2372 static_cast<std::byte *>(target), count * 8);
2373}
2374
2375void heap::host::unpublish(void * target, std::size_t count) const noexcept {
2376 if (state != phase::idle) detail::heap_failure("unpublish during host collection");
2377 if (count > std::numeric_limits<std::size_t>::max() / 8)
2378 detail::heap_failure("unpublished heap window is too large");
2379#if defined(_WIN32)
2380 auto const where = std::find_if(publications.begin(), publications.end(), [&](auto const & window) noexcept {
2381 return window.target == target && window.bytes == count * 8;
2382 });
2383 if (where == publications.end()) detail::heap_failure("unpublish requires an exact published window");
2384 detail::heap_mapping::unpublish(where->target, where->bytes);
2385 publications.erase(where);
2386#else
2387 detail::heap_mapping::unpublish(static_cast<std::byte *>(target), count * 8);
2388#endif
2389}
2390
2391
2392heap::host::pin * heap::host::pin_object(offset at, std::size_t words) noexcept {
2393 owner.require_mutator();
2394 if (state != phase::idle || !at || !words) detail::heap_failure("invalid host pin");
2395 auto & g = owner.containing(at);
2396 auto const local = std::size_t(at & offset_mask);
2397 if (local < prefix || local >= g.cursor || words > g.cursor - local)
2398 detail::heap_failure("pin outside allocated storage");
2399 if (auto found = pins_.find(at); found != pins_.end()) {
2400 if (found->second->words_ != words) detail::heap_failure("conflicting pin extents");
2401 ++found->second->references_;
2402 return found->second.get();
2403 }
2404 auto const page = g.page_word_count;
2405 auto const first = local / page * page;
2406 auto const end = (local + words + page - 1) / page * page;
2407 auto alias = g.storage.alias_run(((g.origin + first) % g.capacity()) * 8, (end - first) * 8);
2408 auto value = std::unique_ptr<pin>(new pin{at, words, local - first, std::move(alias)});
2409 auto * result = value.get();
2410 pins_.emplace(at, std::move(value));
2411 return result;
2412}
2413
2414void heap::host::unpin(pin * value) noexcept {
2415 owner.require_mutator();
2416 if (state != phase::idle || !value) detail::heap_failure("invalid host unpin");
2417 auto found = pins_.find(value->at_);
2418 if (found == pins_.end() || found->second.get() != value) detail::heap_failure("foreign host pin");
2419 if (!--value->references_) pins_.erase(found);
2420}
2421
2422void heap::host::prepare_pin_marks() noexcept {
2423 // Snapshot exact claims before padding can make dead targets appear occupied.
2424 for (unsigned which = owner.minor_collection ? 1 : 0; which != 2; ++which) {
2425 auto & g = which ? owner.nursery : owner.arena;
2426 auto const blocks = (g.cursor + block_words - 1) / block_words;
2427 auto & live = traced[which];
2428 live.resize(blocks);
2429 for (std::size_t i = 0; i != blocks; ++i) {
2430 auto & item = g.metadata[i];
2431 live[i] = item.live;
2432 item.pointers &= heap::generation::pointer_cells(item.live);
2433 }
2434 }
2435 for (auto const & [at, value] : pins_) {
2436 if (!owner.marked(at)) detail::heap_failure("open pin was not traced");
2437 auto const which = unsigned(at >> 31);
2438 if (!which && owner.minor_collection) continue;
2439 auto & g = owner.containing(at);
2440 auto & runs = pin_runs[which];
2441 auto const first = std::size_t(at & offset_mask), end = first + value->words_;
2442 auto const page = g.page_word_count;
2443 if (!runs.empty() && first / page < (runs.back().end + page - 1) / page) {
2444 runs.back().end = std::max(runs.back().end, end);
2445 } else runs.push_back({first, end, 0, 0});
2446 }
2447 for (unsigned which = 0; which != 2; ++which) {
2448 auto & g = which ? owner.nursery : owner.arena;
2449 auto & runs = pin_runs[which];
2450 // A placement gap must never split another live record across mini-pages.
2451 std::vector<pin_run> joined;
2452 for (auto run : runs) {
2453 run.block_begin = run.first / block_words;
2454 run.block_end = (run.end + block_words - 1) / block_words;
2455 while (run.block_begin && (g.flags(run.block_begin - 1) & 8u)) --run.block_begin;
2456 while (run.block_end * block_words < g.cursor && (g.flags(run.block_end - 1) & 8u)) ++run.block_end;
2457 if (!joined.empty() && run.block_begin < joined.back().block_end) {
2458 joined.back().end = run.end;
2459 joined.back().block_end = std::max(joined.back().block_end, run.block_end);
2460 } else joined.push_back(run);
2461 }
2462 runs = std::move(joined);
2463 for (auto const & run : runs) {
2464 for (auto cell = run.block_begin * block_words; cell < run.end; ++cell) {
2465 auto & item = g.metadata[cell / block_words];
2466 auto const bit = bitmap{1} << (cell % block_words);
2467 if (!(item.live & bit)) {
2468 auto const at = static_cast<offset>(cell) | (which ? young_bit : 0);
2469 if (!source_gaps.empty() && source_gaps.back().at + source_gaps.back().words == at)
2470 ++source_gaps.back().words;
2471 else source_gaps.push_back({at, 1});
2472 item.live |= bit;
2473 }
2474 }
2475 }
2476 }
2477}
2478
2479std::size_t heap::host::prepare_pinned(heap::generation & g, unsigned which,
2480 std::size_t start, bool keep_null) noexcept {
2481 static_cast<void>(g.prepare(start, keep_null));
2482 auto const blocks = (g.cursor + block_words - 1) / block_words;
2483 auto const page = g.page_word_count;
2484 auto const & runs = pin_runs[which];
2485 std::size_t cursor = start, next_run = 0;
2486 // Promotion cannot replace the partial page containing stationary old objects.
2487 std::size_t pinned_page_end = promoting && which ? (start + page - 1) / page * page : 0;
2488 for (std::size_t begin = 0; begin < blocks;) {
2489 auto end = begin + 1;
2490 while (end < blocks && (g.flags(end - 1) & 8u)) ++end;
2491 bool const constrained = next_run < runs.size() && runs[next_run].block_begin == begin;
2492 if (constrained) end = runs[next_run].block_end;
2493 unsigned k = 0;
2494 for (auto i = begin; i < end; ++i) k = std::max(k, static_cast<unsigned>(std::popcount(g.flags(i) & 7u)));
2495 auto const previous = cursor;
2496 cursor = (cursor + (std::size_t{1} << k) - 1) & ~((std::size_t{1} << k) - 1);
2497 if (constrained) {
2498 auto const & run = runs[next_run++];
2499 cursor += (begin * block_words - cursor) & (page - 1);
2500 auto mapped_page = (cursor + run.first - begin * block_words) / page * page;
2501 if (mapped_page < pinned_page_end) cursor += pinned_page_end - mapped_page;
2502 pinned_page_end = (cursor + run.end - begin * block_words + page - 1) / page * page;
2503 }
2504 if (cursor > previous) pin_gaps.push_back({static_cast<offset>(previous), cursor - previous});
2505 for (auto i = begin; i != end; ++i) {
2506 g.metadata[i].destination = static_cast<offset>(cursor);
2507 cursor += std::popcount(detail::retained(g.metadata[i], g.alignment_table(), i));
2508 }
2509 begin = end;
2510 }
2511 return cursor;
2512}
2513
2514template<bool tracks_starts>
2515void heap::host::finish_pinned() noexcept {
2516 std::array<std::optional<detail::heap_mapping>, 2> output;
2517 std::array<std::vector<block>, 2> metadata;
2518 std::array<std::vector<bitmap>, 2> next_starts;
2519 auto const minor = owner.minor_collection;
2520 for (unsigned which = 0; which != 2; ++which) {
2521 auto & g = which ? owner.nursery : owner.arena;
2522 if (!which && minor && !promoting) continue;
2523 if (!which && minor) {
2524 output[which].emplace(g.storage.alias_run(g.origin * 8, g.capacity() * 8));
2525 metadata[which] = g.metadata;
2526 } else {
2527 output[which].emplace(g.capacity() * 8);
2528 metadata[which].resize(g.metadata.size());
2529 if constexpr (tracks_starts) next_starts[which].resize(g.metadata.size());
2530 }
2531 }
2532 std::vector<std::pair<offset, offset>> relocated;
2533 for (auto const & [at, value] : pins_) relocated.emplace_back(at, owner.forward(at, minor));
2534 for (auto const & hole : source_gaps) pin_gaps.push_back({owner.forward(hole.at, minor), hole.words});
2535
2536 // Read all movable payload before replacing any source pages shared by pins.
2537 for (unsigned which = minor ? 1 : 0; which != 2; ++which) {
2538 auto & g = which ? owner.nursery : owner.arena;
2539 unsigned const target_gen = which && !promoting ? 1 : 0;
2540 auto * target = reinterpret_cast<word *>(output[target_gen]->data());
2541 auto & target_meta = metadata[target_gen];
2542 auto pinned = pins_.lower_bound(which ? young_bit : 0);
2543 auto const blocks = (g.cursor + block_words - 1) / block_words;
2544 for (std::size_t i = 0; i < blocks; ++i) {
2545 auto const & item = g.metadata[i];
2546 auto retained = detail::retained(item, g.alignment_table(), i);
2547 auto destination = std::size_t(item.destination & offset_mask);
2548 while (retained) {
2549 auto const bit = std::countr_zero(retained);
2550 auto const cell = i * block_words + bit;
2551 auto const at = static_cast<offset>(cell) | (which ? young_bit : 0);
2552 while (pinned != pins_.end() && std::uint64_t(pinned->first) + pinned->second->words_ <= at) ++pinned;
2553 bool const fixed = pinned != pins_.end() && at >= pinned->first &&
2554 std::uint64_t(at) < std::uint64_t(pinned->first) + pinned->second->words_;
2555 auto const pointers = (item.pointers >> (bit * 2)) & 3u;
2556 if (!fixed) target[destination] = g.data()[cell];
2557 for (unsigned slot = 0; slot != 2; ++slot) if (pointers & (1u << slot)) {
2558 auto * from = reinterpret_cast<std::byte *>(g.data() + cell) + slot * sizeof(offset);
2559 offset before;
2560 std::memcpy(&before, from, sizeof(before));
2561 auto const after = forward(before);
2562 auto * to = fixed ? from : reinterpret_cast<std::byte *>(target + destination) + slot * sizeof(offset);
2563 std::memcpy(to, &after, sizeof(after));
2564 }
2565 auto & packed = target_meta[destination / block_words];
2566 if constexpr (tracks_starts)
2567 if (starts_[which][i] & (bitmap{1} << bit))
2568 (minor && target_gen == 0 ? starts_[0] : next_starts[target_gen])[destination / block_words]
2569 |= bitmap{1} << (destination % block_words);
2570 packed.live |= bitmap{1} << (destination % block_words);
2571 packed.pointers |= word{pointers} << ((destination % block_words) * 2);
2572 ++destination;
2573 retained &= retained - 1;
2574 }
2575 }
2576 }
2577 for (auto const & hole : pin_gaps) {
2578 auto const which = unsigned(hole.at >> 31);
2579 auto * target = reinterpret_cast<word *>(output[which]->data());
2580 std::fill_n(target + (hole.at & offset_mask), hole.words, word{0});
2581 }
2582 for (unsigned which = minor ? 1 : 0; which != 2; ++which) {
2583 auto & g = which ? owner.nursery : owner.arena;
2584 auto const page = g.page_word_count;
2585 unsigned const target_gen = which && !promoting ? 1 : 0;
2586 for (auto const & run : pin_runs[which]) {
2587 auto const first = run.first / page * page, end = (run.end + page - 1) / page * page;
2588 auto const destination = (owner.forward(static_cast<offset>(run.first) | (which ? young_bit : 0), minor) & offset_mask) / page * page;
2589 auto const * staged = reinterpret_cast<word const *>(output[target_gen]->data());
2590 auto pin_at = pins_.lower_bound(static_cast<offset>(first) | (which ? young_bit : 0));
2591 for (auto cell = first; cell != end; ++cell) {
2592 auto const at = static_cast<offset>(cell) | (which ? young_bit : 0);
2593 while (pin_at != pins_.end() && std::uint64_t(pin_at->first) + pin_at->second->words_ <= at) ++pin_at;
2594 if (pin_at != pins_.end() && at >= pin_at->first && std::uint64_t(at) < std::uint64_t(pin_at->first) + pin_at->second->words_) continue;
2595 g.data()[cell] = staged[destination + cell - first];
2596 }
2597 output[target_gen]->replace_pages(g.storage, ((g.origin + first) % g.capacity()) * 8,
2598 destination * 8, (end - first) * 8);
2599 }
2600 }
2601 for (unsigned which = 0; which != 2; ++which) if (output[which]) {
2602 auto & g = which ? owner.nursery : owner.arena;
2603 g.storage.replace(*output[which]);
2604 g.metadata = std::move(metadata[which]);
2605 if constexpr (tracks_starts)
2606 if (!minor || which) starts_[which].swap(next_starts[which]);
2607 g.adopt(0, which ? young_words : old_words);
2608 }
2609 std::map<offset, std::unique_ptr<pin>> next;
2610 for (auto [before, after] : relocated) {
2611 auto node = pins_.extract(before);
2612 node.key() = after;
2613 node.mapped()->at_ = after;
2614 next.insert(std::move(node));
2615 }
2616 pins_.swap(next);
2617 owner.collecting = false;
2618 owner.minor_collection = false;
2619 state = phase::idle;
2620 std::atomic_signal_fence(std::memory_order_seq_cst);
2621}
2622
2623void heap::host::begin(bool minor) noexcept {
2624 owner.require_mutator();
2625 if (state != phase::idle) detail::heap_failure("host begin outside idle phase");
2626 if (owner.roots_head || !owner.weak_entries.empty() || !owner.pending_finalizers.empty() ||
2627 owner.running_finalizer || !owner.remembered.empty())
2628 detail::heap_failure("host collection requires exclusively VM-owned roots");
2629 std::atomic_signal_fence(std::memory_order_seq_cst);
2630 owner.collecting = true;
2631 owner.minor_collection = minor;
2632 state = phase::marking;
2633 moving_pins = !pins_.empty() && (!minor || (pins_.rbegin()->first & young_bit));
2634 pin_gaps.clear(); source_gaps.clear();
2635 for (auto & runs : pin_runs) runs.clear();
2636 for (auto & live : traced) live.clear();
2637 auto reset = [&]<bool tracks_starts>(heap::generation & g, unsigned which) noexcept {
2638 g.clear_marks();
2639 for (std::size_t i = 0; i != g.metadata.size(); ++i) {
2640 g.metadata[i].pointers = 0;
2641 if constexpr (tracks_starts) starts_[which][i] = 0;
2642 }
2643 };
2644 if (tracks_starts()) {
2645 reset.template operator()<true>(owner.nursery, 1);
2646 if (!minor) reset.template operator()<true>(owner.arena, 0);
2647 } else {
2648 reset.template operator()<false>(owner.nursery, 1);
2649 if (!minor) reset.template operator()<false>(owner.arena, 0);
2650 }
2651}
2652
2653[[nodiscard]] bool heap::host::prepare(bool promote) noexcept {
2654 if (state != phase::marking && state != phase::retry)
2655 detail::heap_failure("host prepare outside marking phase");
2656 pin_gaps.clear();
2657 if (state == phase::marking && moving_pins) prepare_pin_marks();
2658 promoting = owner.minor_collection && promote;
2659 if (!owner.minor_collection) {
2660 if (prefix > 1) owner.arena.mark(1, prefix - 1);
2661 old_words = !moving_pins ? owner.arena.prepare(0, true) : prepare_pinned(owner.arena, 0, 0, true);
2662 } else old_words = owner.arena.cursor;
2663 if (promoting) {
2664 old_words = !moving_pins ? owner.nursery.prepare(owner.arena.cursor, false) : prepare_pinned(owner.nursery, 1, owner.arena.cursor, false);
2665 if (old_words > owner.arena.capacity() - owner.arena.reserved()) {
2666 state = phase::retry;
2667 return false;
2668 }
2669 young_words = prefix;
2670 } else {
2671 if (prefix > 1) owner.nursery.mark(1, prefix - 1);
2672 young_words = (!moving_pins ? owner.nursery.prepare(young_bit, true) : prepare_pinned(owner.nursery, 1, young_bit, true)) - young_bit;
2673 }
2674 state = phase::prepared;
2675 return true;
2676}
2677
2678void heap::host::finish() noexcept {
2679 if (tracks_starts()) finish_impl<true>();
2680 else finish_impl<false>();
2681}
2682
2683template<bool tracks_starts>
2684void heap::host::finish_impl() noexcept {
2685 if (state != phase::prepared)
2686 detail::heap_failure("host finish outside prepared phase");
2687 if (moving_pins) { finish_pinned<tracks_starts>(); return; }
2688 detail::forwarding_tables tables{owner.minor_collection ? nullptr : owner.arena.metadata.data(), owner.nursery.metadata.data(),
2689 owner.minor_collection ? nullptr : owner.arena.alignment_table(), owner.nursery.alignment_table()};
2690 auto const old_origin = owner.minor_collection ? owner.arena.origin : owner.arena.rotated_origin();
2691 auto const young_origin = owner.nursery.rotated_origin();
2692 if (!owner.minor_collection) {
2693 auto * target = owner.arena.at_origin(old_origin);
2694 owner.arena.move_to(target, tables);
2695 owner.arena.zero_gaps(target, 0);
2696 }
2697 auto * target = promoting ? owner.arena.data() : owner.nursery.at_origin(young_origin);
2698 owner.nursery.move_to(target, tables);
2699 owner.nursery.zero_gaps(target, promoting ? owner.arena.cursor : 0);
2700 // Both moves consumed the original tables. Pack starts in the same metadata pass.
2701 auto pack = [&](heap::generation & g, unsigned source, unsigned destination) noexcept {
2702 auto & out = destination ? owner.nursery : owner.arena;
2703 if constexpr (tracks_starts)
2704 g.compactor.pack(g.metadata.data(), out.metadata.data(), (g.cursor + block_words - 1) / block_words,
2705 g.alignment_table(), starts_[source].data(), starts_[destination].data());
2706 else g.pack_into(out.metadata);
2707 };
2708 if (!owner.minor_collection) pack(owner.arena, 0, 0);
2709 pack(owner.nursery, 1, promoting ? 0 : 1);
2710 if (!owner.minor_collection || promoting) owner.arena.adopt(old_origin, old_words);
2711 if (promoting) {
2712 if constexpr (tracks_starts) owner.nursery.reset<true>(starts_[1].data());
2713 else owner.nursery.reset<false>();
2714 } else owner.nursery.adopt(young_origin, young_words);
2715 owner.collecting = false;
2716 owner.minor_collection = false;
2717 state = phase::idle;
2718 if (promoting && young_words > 1)
2719 static_cast<void>(owner.nursery.allocate(young_words - 1));
2720 std::atomic_signal_fence(std::memory_order_seq_cst);
2721}
2722}
Stable alias registration; release through its owning host.
Definition heap.ccm:1227
Borrow a heap whose roots, barriers and reference policy belong to a host runtime.
Definition heap.ccm:1224
bool marked(offset at) const noexcept
Exact collected-generation liveness; old objects are live during minors.
Definition heap.ccm:1366
void unpublish(void *target, std::size_t count) const noexcept
Remove a canonical alias without releasing the host's reservation.
Definition heap.ccm:2375
offset allocate(generation which, std::size_t words) noexcept
Allocate raw cells in either generation, preserving the tag bit. A host may subdivide the extent; sca...
Definition heap.ccm:1303
void unpin(pin *value) noexcept
Release one registration; the last release invalidates its native address.
Definition heap.ccm:2414
generation
Select the arena for raw allocation or publication.
Definition heap.ccm:1278
void trace(std::span< offset const > roots, Trace &&trace, std::size_t marker_limit=1, bool old_owners=false) noexcept
Drain roots using jam's ordinary frontier and persistent worker pool.
Definition heap.ccm:1353
pin * pin_object(offset at, std::size_t words) noexcept
Alias a complete allocated object without collecting or changing its offset.
Definition heap.ccm:2392
void record_start(offset at) noexcept
Declare an actual object start after claiming or formatting the object.
Definition heap.ccm:1332
host(heap &storage, std::size_t prefix) noexcept
Reserve an identical guard in both fresh, fixed-size generations.
Definition heap.ccm:2320
void visit_pins(F &&visit) const noexcept
Enumerate open pins as strong roots before reference policy is resolved.
Definition heap.ccm:1313
~host() noexcept
Release the capability after finishing its last collection.
Definition heap.ccm:2331
void begin(bool minor) noexcept
Start a VM-owned marking epoch; the VM supplies barriers and weak policy.
Definition heap.ccm:2623
void finish() noexcept
Move survivors, preserving side aliases, then pack the consumed metadata.
Definition heap.ccm:2678
bool prepare(bool promote=false) noexcept
Freeze both forwarding tables after resolving all reference policies.
Definition heap.ccm:2653
std::span< bitmap const > starts(generation which) const noexcept
Borrow the bitmap in canonical cell coordinates, one word per mini-page.
Definition heap.ccm:1342
bool tracks_starts() const noexcept
Whether the host opted into object-start transport.
Definition heap.ccm:1329
void track_starts()
Lazily allocate VM-defined object-start bits; enable before a major epoch. Existing objects are disco...
Definition heap.ccm:1320
std::span< gap const > gaps() const noexcept
Placement padding to format before a VM walks the collected object stream.
Definition heap.ccm:1317
offset forward(offset at) const noexcept
Repair a root while original objects and both forwarding tables remain intact.
Definition heap.ccm:1377
void publish(generation which, void *target, std::size_t skip, std::size_t count) const noexcept
Publish one generation at a stable VM-owned address.
Definition heap.ccm:2339
A four-byte handle to a collector-updated external root slot.Copies share a registration; moves leave...
Definition heap.ccm:560
root_handle(root_handle &&other) noexcept
Transfer a registration, leaving the source detached.
Definition heap.ccm:577
offset get() const noexcept
Resolve the slot through the current heap; returned offsets expire on collection.
Definition heap.ccm:591
root_handle & operator=(root_handle &&other) noexcept
Transfer a registration in the same heap.
Definition heap.ccm:584
~root_handle() noexcept
Release this reference; the last release recycles the slot.
Definition heap.ccm:589
root_handle & operator=(root_handle const &other) noexcept
Replace this handle with a shared registration in the same heap.
Definition heap.ccm:579
root_handle() noexcept=default
Construct a detached null handle.
offset operator*() const noexcept
Read the current target offset.
Definition heap.ccm:595
void pointer(weak_ptr< T > const &value) noexcept
Declare a weak slot without following or claiming its target.
Definition heap.ccm:747
void pointer(ptr< T > const &value) noexcept
Declare one pointer slot without following or claiming its target.
Definition heap.ccm:739
void target(offset at) noexcept
Enqueue an external/wide target without declaring a narrow source slot.
Definition heap.ccm:789
offset field(offset cell, unsigned slot=0) noexcept
Declare a managed field and enqueue its nonnull target for tracing.
Definition heap.ccm:781
T const * claim_target(T const *value) noexcept
Claim the complete object from its allocation-level hook.
Definition heap.ccm:719
T const * claim_target(ptr< T > const &value) noexcept
Claim a typed target without declaring the pointer's source slot.
Definition heap.ccm:705
void operator()(Ts const &... values) noexcept
Visit parts in order, preserving their addresses; an empty pack does nothing.
Definition heap.ccm:817
void pointers(word bits, std::size_t first_slot=0) noexcept
OR a pattern of pointer slots into the current record's metadata. Bit zero names the 32-bit slot at f...
Definition heap.ccm:754
void operator()(T const &value) noexcept
Walk an embedded value without claiming cells again. Parts share the current allocation's pointer mas...
Definition heap.ccm:796
T const * claim(ptr< T > const &value) noexcept
Declare a pointer slot, then claim its target as with claim_target(). Null and already-claimed target...
Definition heap.ccm:773
void operator()(weak_ptr< T > const &value) noexcept
Declare a weak field for forwarding; never enqueue its target.
Definition heap.ccm:814
ptr< T > operator()(ptr< T > const &value) noexcept
Declare a typed field and enqueue its nonnull target.
Definition heap.ccm:805
void poll() noexcept
Service overdue stochastic donations without leaving this walker. Long cooperative hooks should poll ...
Definition heap.ccm:823
heap heap_type
Heap accepted by this visitor.
Definition heap.ccm:690
bool claim(offset start, std::size_t words=1, std::size_t alignment_bytes=8) noexcept
Claim a complete record; exactly one marker wins traversal.
Definition heap.ccm:695
Bind an existing heap, restoring the previous binding on scope exit.The heap must outlive the scope....
Definition heap.ccm:307
~heap_scope() noexcept
Restore the binding saved at construction.
Definition heap.ccm:313
heap_scope(heap &arena) noexcept
Use the supplied heap for implicit operations on this thread.
Definition heap.ccm:1707
A circular, double-mapped arena with bounded parallel compaction.Compressed four-byte offsets address...
Definition heap.ccm:502
void remember(std::span< weak_ptr< T > > values) noexcept
Register weak slots after bulk unsafe assignment, dropping stale entries.
Definition heap.ccm:1415
void remember(ptr< T > const &value) noexcept
Explicitly register a pointer after a caller-managed unsafe write.
Definition heap.ccm:1392
generation const & young() const noexcept
Inspect generation one's arena.
Definition heap.ccm:1435
char const * compactor_name() const noexcept
Runtime-selected compaction implementation, including SIMD ISA admission.
Definition heap.ccm:1388
void remember(weak_ptr< T > const &value) noexcept
Register a weak old-to-young slot for rewriting, never for marking.
Definition heap.ccm:1409
void remember(std::span< ptr< T > > values) noexcept
Register a contiguous group after bulk unsafe assignment.
Definition heap.ccm:1399
jam::weak< V > mk_weak(ptr< K > const &key, ptr< V > const &value, ptr< F > const &finalizer, std::type_identity_t< void(*)(F *) noexcept > runner) noexcept
Associate a weak key and value with a managed finalizer and stateless runner.
Definition heap.ccm:1812
std::size_t remembered_size() const noexcept
Number of distinct old source slots retained in the current GC epoch.
Definition heap.ccm:1390
static heap * current() noexcept
Read the current thread's dynamically bound heap. Implicit operations require an active heap_scope....
Definition heap.ccm:512
jam::weak_ptr< T > weak_ptr
The weak field type for this heap.
Definition heap.ccm:532
generation const & old() const noexcept
Inspect generation zero's arena.
Definition heap.ccm:1433
root_handle root(offset at) noexcept
Register a record or null in the current heap.
Definition heap.ccm:1444
~heap() noexcept
Release the arena; every attached root must already be destroyed.
Definition heap.ccm:2227
A typed heap offset, with no root registration or ownership.
Definition heap.ccm:329
constexpr ptr & unsafe_assign(offset bits) noexcept
Install encoded bits without registration; the caller owns the barrier.
Definition heap.ccm:369
void prefetch() const noexcept
Prefetch the cache line containing the target's first byte for reading. Null does nothing,...
Definition heap.ccm:1944
constexpr void swap(ptr &other) noexcept
Exchange targets and update the remembered entries for both slots.
Definition heap.ccm:1920
constexpr ~ptr() noexcept
Remove a dying old pointer slot from the remembered set.
Definition heap.ccm:1926
T & operator*() const noexcept
Borrow the target in the current heap.
Definition heap.ccm:1934
T element_type
Target record type.
Definition heap.ccm:332
constexpr offset local_offset() const noexcept
Cell index within the target generation.
Definition heap.ccm:373
constexpr ptr() noexcept=default
Construct a null reference.
friend constexpr void swap(ptr &left, ptr &right) noexcept
Exchange pointers through ADL, preserving each slot's write barrier.
Definition heap.ccm:363
constexpr offset get() const noexcept
Read the cell offset; unregistered copies expire on collection.
Definition heap.ccm:376
std::uint32_t offset
Eight-byte cell index, stored in exactly four bytes.
Definition heap.ccm:334
void prefetch_marks() const noexcept
Prefetch the target's mark metadata without claiming or reading it. Null does nothing,...
Definition heap.ccm:1937
T * operator->() const noexcept
Borrow the target in the current heap; expires on growth or collection.
Definition heap.ccm:1930
constexpr bool is_young() const noexcept
Whether the target belongs to generation one.
Definition heap.ccm:371
constexpr ptr & unsafe_assign(ptr const &other) noexcept
Assign without a write barrier; the caller must register old-to-young edges.
Definition heap.ccm:367
A copyable external root, updated during collection.Four-byte slot index; no heap or registration add...
Definition heap.ccm:1716
root() noexcept=default
Construct a detached null root.
root(ptr< U > const &value) noexcept
Register a derived pointer through its base allocation-tracing hook.
Definition heap.ccm:1728
ptr< T > get() const noexcept
Obtain a pointer valid until the next collection.
Definition heap.ccm:1731
T * operator->() const noexcept
Borrow the target in its current heap scope.
Definition heap.ccm:1735
T & operator*() const noexcept
Borrow the target in its current heap scope.
Definition heap.ccm:1737
constexpr rep count() const noexcept
Retrieve the count in this unit explicitly.
Definition units.ccm:104
A four-byte weak heap field; tracing updates its slot without retaining its target....
Definition heap.ccm:408
constexpr bool expired() const noexcept
Whether null or cleared by collection; this does not initiate collection.
Definition heap.ccm:451
T element_type
Target record type; may be incomplete.
Definition heap.ccm:411
constexpr bool is_young() const noexcept
Whether this field targets the young generation.
Definition heap.ccm:449
constexpr void swap(weak_ptr &other) noexcept
Exchange targets while preserving each slot's weak barrier.
Definition heap.ccm:1867
constexpr ~weak_ptr() noexcept
Remove a dying old slot from the remembered set.
Definition heap.ccm:1863
constexpr weak_ptr & unsafe_assign(weak_ptr const &other) noexcept
Assign without registration; the caller must remember old-to-young slots.
Definition heap.ccm:445
root< T > lock() const noexcept
Retain the current target as a strong root, or return an empty root.
Definition heap.ccm:1873
constexpr weak_ptr & unsafe_assign(offset bits) noexcept
Assign encoded bits without registration; the caller owns the barrier.
Definition heap.ccm:443
std::uint32_t offset
The same generation-tagged cell index used by ptr.
Definition heap.ccm:413
constexpr weak_ptr() noexcept=default
Construct an empty weak pointer.
constexpr offset get() const noexcept
Read the encoded offset; an external copy expires on collection.
Definition heap.ccm:447
constexpr weak_ptr(ptr< U > const &value) noexcept
Observe a derived pointer through its supported base conversion.
Definition heap.ccm:428
An external weak slot, updated or cleared by collection without retaining its target....
Definition heap.ccm:1749
void swap(weak_root &other) noexcept
Exchange slots in the same heap without allocating or retaining either target.
Definition heap.ccm:1776
root< T > lock() const noexcept
Retain the current target, or return an empty root if expired. Requires the owning heap current; the ...
Definition heap.ccm:1769
void reset() noexcept
Unregister the slot and leave it detached and expired.
Definition heap.ccm:1774
weak_root(root< T > const &value) noexcept
Observe a strong root in the current heap without retaining its target.
Definition heap.ccm:1760
weak_root() noexcept=default
Construct a detached, expired weak root.
friend void swap(weak_root &a, weak_root &b) noexcept
Exchange two external weak roots.
Definition heap.ccm:1780
bool expired() const noexcept
Whether this slot is null; does not initiate collection.
Definition heap.ccm:1766
weak_root(ptr< U > const &value) noexcept
Register a derived pointer through its base allocation-tracing hook.
Definition heap.ccm:1764
An external conditional weak-value handle; registration survives dropped handles.Keep this handle out...
Definition heap.ccm:1788
bool expired() const noexcept
Whether the registration has retired or its heap has been destroyed.
Definition heap.ccm:1795
root< V > lock() const noexcept
Retain the current value, or return an empty root for a retired registration. Locking and using the r...
Definition heap.ccm:1798
void finalize() const noexcept
Retire the registration and run its callback now, at most once. Requires the owning heap current....
Definition heap.ccm:1804
T supports tracing after it is complete.Ordinary trace return types are unrestricted; collection uses...
Definition heap.ccm:182
A visitor for jam's compressed, alignment-preserving heap.
Definition heap.ccm:58
void collect_major() noexcept
Trace both generations and compact survivors into old; reset the countdown.
Definition heap.ccm:2236
jam::ptr< T > ptr
The compact pointer type for this heap.
Definition heap.ccm:530
jam::weak_root< T > weak_root(ptr< T > const &at) noexcept
Register an external weak slot, forwarded but never used to seed marking.
Definition heap.ccm:1461
void collect_minor(bool promote=false) noexcept
Collect young without walking old; optionally promote survivors; preserve the countdown.
Definition heap.ccm:2240
offset field(offset cell, unsigned slot=0) const noexcept
Read one managed reference field by value.
Definition heap.ccm:996
std::size_t page_words() const noexcept
Cells per native OS page (distinct from a rank block).
Definition heap.ccm:977
T load(ptr< T > const &at) const noexcept
Read a typed value snapshot; any pointers in it expire on collection.
Definition heap.ccm:1653
std::size_t capacity() const noexcept
Capacity in eight-byte cells, including the reserve.
Definition heap.ccm:969
T * address(ptr< T > const &at) noexcept
Borrow a typed target; the address expires on growth or collection.
Definition heap.ccm:1644
detail::heap_block block
Live bitmap, forwarding base and pointer-field bitmap.
Definition heap.ccm:527
ptr< T > mk(Args &&... args) noexcept
Allocate and copy a typed record, returning an unrooted reference.Construct T from the arguments....
Definition heap.ccm:1626
offset bitmap
Allocation/live bitmap.
Definition heap.ccm:519
static constexpr std::size_t block_words
Eight-byte cells in one rank block: 32.
Definition heap.ccm:523
auto data(this Self &self) noexcept -> std::conditional_t< std::is_const_v< Self >, word const, word > *
Borrow cells; dereference an offset as data()[offset].
Definition heap.ccm:981
consteval auto make_manifest(Members T::*... members)
Describe the pointer-bearing members of T, including embedded values.T may still be incomplete....
Definition heap.ccm:114
offset allocate(std::size_t words, std::size_t alignment_bytes=8) noexcept
Allocate a positive complete record measured in eight-byte cells.
Definition heap.ccm:1028
bool claim(offset first, std::size_t words=1, std::size_t alignment_bytes=8) noexcept
Claim traversal by atomically marking the record's first cell.
Definition heap.ccm:1065
std::size_t reserved() const noexcept
Reserved cells for bounded parallel compaction.
Definition heap.ccm:971
static constexpr unsigned fields_per_word
Four-byte pointer fields per allocation cell.
Definition heap.ccm:525
void clear_marks() noexcept
Clear marks and alignment requirements; pointer declarations survive.
Definition heap.ccm:1992
void pointer(offset where, unsigned slot=0) noexcept
Declare a managed reference field; may overlap frozen-heap markers.
Definition heap.ccm:1083
std::span< block const > blocks() const noexcept
Borrow rank descriptors while markers and compaction are quiescent.
Definition heap.ccm:1018
void collect_minor(Trace &&trace, bool promote=false) noexcept
Minor collection with a fallback tracer and optional promotion; preserve the countdown....
Definition heap.ccm:1521
static constexpr offset null
Unreachable reference preserved by forwarding.
Definition heap.ccm:521
void collect_major(Trace &&trace) noexcept
Major collection with a fallback tracer; reset the countdown.Uses the same tracing and synchronizatio...
Definition heap.ccm:1513
void mark(offset first, std::size_t words=1, std::size_t alignment_bytes=8) noexcept
Mark a complete reachable record; concurrent markers are permitted.
Definition heap.ccm:1054
std::uint32_t offset
Stored reference, in eight-byte units from data().
Definition heap.ccm:517
void store(ptr< T > const &at, T const &value) noexcept
Replace a typed record's bytes without changing its extent or type.
Definition heap.ccm:1663
void set_field(offset cell, offset value, unsigned slot=0) noexcept
Write a managed reference field's bytes.
Definition heap.ccm:1011
void collect() noexcept
Collect typed roots, running minor_collections minors between majors. The first minor_collections cal...
Definition heap.ccm:2232
heap_options configuration() const noexcept
Read the immutable construction policy with typed page counts.
Definition heap.ccm:1437
std::size_t start() const noexcept
Current view's offset in the circular backing, in cells.
Definition heap.ccm:975
std::size_t used() const noexcept
Allocated prefix in eight-byte cells, including the reserved null cell.
Definition heap.ccm:973
jam::root< T > root(ptr< T > const &at) noexcept
Register a typed external root with its type-specific tracing callback.
Definition heap.ccm:1452
std::uint64_t word
Eight-byte allocation cell.
Definition heap.ccm:515
void compact(std::span< offset > roots={}) noexcept
Pack marked records, forwarding managed fields and external roots.
Definition heap.ccm:2001
void collect_major() noexcept
Collect both generations of the current heap; reset its collection countdown.
Definition jam.ccm:61
void collect() noexcept
Collect the current heap; only registered roots remain meaningful outside it.
Definition jam.ccm:59
weak< V > mk_weak(ptr< K > const &key, ptr< V > const &value, ptr< F > const &finalizer, std::type_identity_t< void(*)(F *) noexcept > runner) noexcept
Register a weak key/value pair and managed finalizer in the current heap. The captureless runner rece...
Definition jam.ccm:21
void collect_minor(bool promote=false) noexcept
Collect the current heap's young generation; optionally promote survivors.
Definition jam.ccm:63
space< std::size_t, mebi > mebibytes
Groups of 1048576 bytes.
Definition units.ccm:243
constexpr To ceil(space< R, P > value) noexcept
Least whole destination count not less than the source.
Definition units.ccm:217
constexpr To floor(space< R, P > value) noexcept
Greatest whole destination count not exceeding the source.
Definition units.ccm:210
space< std::size_t, std::ratio< JAM_PAGE_BYTES > > pages
Platform pages, fixed at build time.
Definition units.ccm:245
space< std::size_t, gibi > gibibytes
Groups of 1073741824 bytes.
Definition units.ccm:244
space< std::size_t, kibi > kibibytes
Groups of 1024 bytes.
Definition units.ccm:242
space< std::size_t > bytes
Whole bytes.
Definition units.ccm:238
Sizing policy for one generation. Sizes are platform pages.
Definition heap.ccm:465
units::pages maximum
Maximum ring size; reserves virtual addresses without committing backing.
Definition heap.ccm:471
units::pages reserve
Gap reserved for bounded parallel compaction.
Definition heap.ccm:469
units::pages capacity
Initial ring capacity, including the compaction reserve.
Definition heap.ccm:467
unsigned shrink_shift
Shrink below 1/2^shift occupancy; zero disables shrinking.
Definition heap.ccm:473
One generation's ordered double-mapped arena and collection metadata.
Definition heap.ccm:873
Padding retained by pin placement, in destination cells.
Definition heap.ccm:1239
Two generations and one shared worker pool.
Definition heap.ccm:477
generation_options young
Generation one; ordinary typed allocation starts here.
Definition heap.ccm:481
std::size_t workers
Workers shared by marking and compaction, including the caller.
Definition heap.ccm:483
generation_options old
Generation zero, below young in virtual memory.
Definition heap.ccm:479
std::size_t minor_collections
Minor collections between scheduled majors; zero means always major.
Definition heap.ccm:485
Opt out of value traversal when specializing tracer<T>.Derive tracer<T>, not the heap object,...
Definition heap.ccm:126
static constexpr void trace(Visitor &, T const &) noexcept
Visit no fields; allocation tracing still marks the complete extent.
Definition heap.ccm:129
static constexpr auto trace(Visitor &visit, T const &value) noexcept(noexcept(value.trace(visit))) -> decltype(value.trace(visit))
Enumerate a value's parts and forward its member hook's result.
Definition heap.ccm:151
static constexpr decltype(auto) trace(Visitor &visit, ptr< T > const &at) noexcept
Forward an unclaimed target to its cooperative static hook.
Definition heap.ccm:157
static void trace(Visitor &visit, ptr< T > const &at) noexcept accepts< Visitor >
Claim records in a loop, queueing branches and walking one same-type edge locally.
Definition heap.ccm:282
static constexpr void trace(Visitor &visit, ptr< T > const &value) noexcept(noexcept(visit(value)))
Preserve the field address and dispatch to the matching heap visitor.
Definition heap.ccm:201
static constexpr void trace(Visitor &visit, std::array< T, N > const &value)
Visit elements in order, preserving their original addresses.
Definition heap.ccm:248
static constexpr void trace(Visitor &visit, std::tuple< Ts... > const &value)
Tuple views retain their elements' original addresses.
Definition heap.ccm:234
static constexpr void trace(Visitor &visit, std::variant< Ts... > const &value)
A valueless variant has no outgoing managed fields.
Definition heap.ccm:260
static constexpr void trace(Visitor &visit, weak_ptr< T > const &value) noexcept(noexcept(visit(value)))
Preserve the original field address for pointer-mask declaration.
Definition heap.ccm:213
Per-value tracing customization; values without a hook or manifest are leaves.An allocation-only clai...
Definition heap.ccm:140