Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_dfs_stack.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
44#ifndef TPL_DFS_STACK_H
45#define TPL_DFS_STACK_H
46
47#include <algorithm>
48#include <concepts>
49#include <cstddef>
50#include <memory>
51#include <new>
52#include <optional>
53#include <type_traits>
54#include <utility>
55
56#if defined(__GLIBC__)
57#include <unistd.h>
58#endif
59
79#if defined(ALEPH_NO_FLATTEN) || defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) || \
80 defined(__NO_INLINE__)
81#define ALEPH_FLATTEN
82#elif defined(__has_feature)
83#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer)
84#define ALEPH_FLATTEN
85#else
86#define ALEPH_FLATTEN [[gnu::flatten]]
87#endif
88#else
89#define ALEPH_FLATTEN [[gnu::flatten]]
90#endif
91
92// Under AddressSanitizer with ALEPH_ANNOTATE_CONTAINERS, which every
93// translation unit of the program must agree on, as for MemArray, the part
94// of the room of a stack that holds no frame cannot be reached
95#if defined(ALEPH_ANNOTATE_CONTAINERS)
96#if defined(__SANITIZE_ADDRESS__)
97#define ALEPH_DFS_STACK_POISON 1
98#elif defined(__has_feature)
99#if __has_feature(address_sanitizer)
100#define ALEPH_DFS_STACK_POISON 1
101#endif
102#endif
103#endif
104#ifdef ALEPH_DFS_STACK_POISON
105#include <sanitizer/asan_interface.h>
106#endif
107
108namespace Aleph {
109namespace dfs_stack_detail {
110// The largest room that a thread keeps
111inline constexpr size_t Kept_Bytes = 1024 * 1024;
112
113// Whether the part of a room that holds no frame is poisoned
114#ifdef ALEPH_DFS_STACK_POISON
115inline constexpr bool Poisoned = true;
116#else
117inline constexpr bool Poisoned = false;
118#endif
119
120// Under ALEPH_DFS_STACK_POISON, makes the bytes from p unreachable, so
121// that AddressSanitizer reports the use of a frame that was popped, or
122// of the room of a stack that is gone, which its thread keeps
123inline void poison([[maybe_unused]] const void *p, [[maybe_unused]] size_t bytes) noexcept
124{
125#ifdef ALEPH_DFS_STACK_POISON
126 ASAN_POISON_MEMORY_REGION(p, bytes);
127#endif
128}
129
130// Makes the bytes from p reachable again
131inline void unpoison([[maybe_unused]] const void *p, [[maybe_unused]] size_t bytes) noexcept
132{
133#ifdef ALEPH_DFS_STACK_POISON
134 ASAN_UNPOISON_MEMORY_REGION(p, bytes);
135#endif
136}
137
138// Frees a room, which may be poisoned, of the given bytes, or nothing
139inline void free_room(void *r, [[maybe_unused]] size_t bytes) noexcept
140{
141 if constexpr (Poisoned)
142 if (r != nullptr)
143 unpoison(r, bytes);
144 ::operator delete (r);
145}
146
148struct Room
149{
150 void *base = nullptr;
151 size_t bytes = 0;
152 bool open = false; // from the first stack of the thread to its end
153};
154
155// Trivially destructible, so that a stack destroyed when the thread
156// ends, as a static one is, can still look at it
157inline Room &kept_room() noexcept
158{
159 static thread_local constinit Room room;
160 return room;
161}
162
163// Whether this thread is the one that runs main(): with glibc, the one
164// whose id is that of the process. It is asked, and not taken from a
165// mark before main() starts, which a library that another thread loads
166// with dlopen() would take in that thread, and which costs an
167// initializer in each unit. Elsewhere, no thread is taken for it.
168inline bool in_main_thread() noexcept
169{
170#if defined(__GLIBC__)
171#if __GLIBC_PREREQ(2, 30)
172 return ::gettid() == ::getpid();
173#else
174 return false;
175#endif
176#else
177 return false;
178#endif
179}
180
187{
188 Room_Keeper() noexcept
189 {
190 kept_room().open = true;
191 }
192
194 {
195 Room &room = kept_room();
196 room.open = false;
197 if (in_main_thread())
198 return; // the room stays reachable, so that it is not a leak
199
200 free_room(room.base, room.bytes);
201 room = Room();
202 }
203};
204
205// The room of the thread, which the first stack of the thread opens
206inline Room &open_room() noexcept
207{
208 static thread_local Room_Keeper keeper;
209 return kept_room();
210}
211} // namespace dfs_stack_detail
212
239template <class T>
241{
242 static_assert(alignof(T) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__,
243 "the frames need more alignment than operator new gives");
244
245 // The frames of the first room: as many as fit in 1000 bytes, which
246 // glibc gives without merging its free blocks, or one
247 static constexpr size_t Initial_Capacity = sizeof(T) < 1000 ? 1000 / sizeof(T) : 1;
248
249 // The frames of the second room, at least: a search that outgrows the
250 // first one goes deep, and then grows by four from 256 frames
251 static constexpr size_t Second_Capacity = 256;
252
253 void *room = nullptr; // where the frames are
254 size_t room_bytes = 0;
255 T *base = nullptr; // the first frame
256 T *top_ptr = nullptr; // one past the top frame
257 T *limit = nullptr; // one past the last frame that fits in the room
258
259 void set_room(void *r, size_t bytes) noexcept
260 {
261 room = r;
262 room_bytes = bytes;
263 base = top_ptr = static_cast<T *>(r);
264 limit = base + bytes / sizeof(T);
265 }
266
267 // Gives the room, whose frames are gone, to the thread, which keeps it,
268 // poisoned, in the place of the one that it kept, if it fits in
269 // Kept_Bytes and is larger; else frees it. The room is read after the
270 // room of the thread, which code built for a shared library gets
271 // through a call: else it would be held across that call, in registers
272 // that the loop of the search would then lack.
273 void give_room_back() noexcept
274 {
276 if (kept.open and room_bytes <= dfs_stack_detail::Kept_Bytes and room_bytes > kept.bytes)
277 {
280 kept.base = room;
281 kept.bytes = room_bytes;
282 }
283 else
285 }
286
287 // Gives the stack room for more frames: that which the thread kept, if
288 // the stack has none, or else, through enlarge(), a larger one. Out of
289 // line, so that push() stays small, and apart from enlarge(), so that
290 // the search that takes the room of the thread, as most do, does not
291 // pay the registers that enlarge() saves.
292 [[gnu::noinline]] void grow()
293 {
294 if (room == nullptr)
295 {
297 if (kept.bytes >= sizeof(T))
298 {
299 set_room(kept.base, kept.bytes); // poisoned, as kept
300 kept.base = nullptr;
301 kept.bytes = 0;
302 return;
303 }
304 }
305 enlarge();
306 }
307
308 // Moves the frames to a room four times as large, and of
309 // Second_Capacity frames at least, so that a search that goes deep
310 // moves a third of the frames that doubling would. The room that it
311 // leaves goes to the thread if the thread keeps none, as when the stack
312 // took it from the thread, so that a search that outgrows it does not
313 // leave the thread without room; else it is freed at once, which leaves
314 // no free block in the middle of the heap for the small allocations
315 // that follow to be carved from. A member that told which room was the
316 // thread's would cost up to 12 % with GCC, which would no longer hold
317 // the stack in registers in the loop of a search. If it throws, the new
318 // room goes back and the stack is as it was, unless a frame that cannot
319 // be copied threw while it was moved: those moved before it are left
320 // moved from.
321 [[gnu::noinline]] void enlarge()
322 {
323 const size_t n = size();
324 const size_t frames = n == 0 ? Initial_Capacity : std::max(4 * n, Second_Capacity);
325 const size_t new_bytes = frames * sizeof(T);
326 void *new_room = ::operator new (new_bytes);
327 T *new_base = static_cast<T *>(new_room);
328 dfs_stack_detail::poison(new_base + n, new_bytes - n * sizeof(T));
329 if constexpr (std::is_nothrow_move_constructible_v<T>)
330 std::uninitialized_move(base, top_ptr, new_base);
331 else
332 {
333 try
334 {
335 // from const frames, which a constructor that forwards
336 // what it takes cannot take for itself
337 if constexpr (std::is_copy_constructible_v<T>)
338 std::uninitialized_copy(static_cast<const T *>(base), static_cast<const T *>(top_ptr),
339 new_base);
340 else // the frames that were moved are left moved from
341 std::uninitialized_move(base, top_ptr, new_base);
342 }
343 catch (...)
344 {
345 dfs_stack_detail::free_room(new_room, new_bytes);
346 throw;
347 }
348 }
349 std::destroy(base, top_ptr);
350 if (dfs_stack_detail::kept_room().bytes == 0)
352 else
354 set_room(new_room, new_bytes);
355 top_ptr = new_base + n;
356 }
357
358 // push() under ALEPH_DFS_STACK_POISON, once the stack has room: the
359 // frame becomes reachable, and unreachable again if building it throws
360 template <class... Args>
361 [[gnu::always_inline]] T &push_in_poisoned_room(Args &&...args)
362 {
363 void *place = top_ptr;
364 dfs_stack_detail::unpoison(place, sizeof(T));
365 T *frame;
366 if constexpr (std::is_nothrow_constructible_v<T, Args &&...>)
367 frame = ::new (place) T(std::forward<Args>(args)...);
368 else
369 try
370 {
371 frame = ::new (place) T(std::forward<Args>(args)...);
372 }
373 catch (...)
374 {
375 dfs_stack_detail::poison(place, sizeof(T));
376 throw;
377 }
378 ++top_ptr;
379 return *frame;
380 }
381
382public:
385 Dfs_Stack() noexcept = default;
386
388 Dfs_Stack(Dfs_Stack &&other) noexcept
389 : room(other.room), room_bytes(other.room_bytes), base(other.base), top_ptr(other.top_ptr),
390 limit(other.limit)
391 {
392 other.set_room(nullptr, 0);
393 }
394
397 Dfs_Stack &operator = (Dfs_Stack &&other) noexcept
398 {
399 clear();
400 std::swap(room, other.room);
401 std::swap(room_bytes, other.room_bytes);
402 std::swap(base, other.base);
403 std::swap(top_ptr, other.top_ptr);
404 std::swap(limit, other.limit);
405 return *this;
406 }
407
411 {
412 if (room == nullptr)
413 return;
414
415 clear();
417 }
418
429 template <class... Args>
430 [[gnu::always_inline]] T &push(Args &&...args)
431 {
432 if (top_ptr == limit) [[unlikely]]
433 grow();
434 if constexpr (dfs_stack_detail::Poisoned)
435 return push_in_poisoned_room(std::forward<Args>(args)...);
436 else
437 {
438 T *frame = ::new (static_cast<void *>(top_ptr)) T(std::forward<Args>(args)...);
439 ++top_ptr;
440 return *frame;
441 }
442 }
443
445 void pop() noexcept
446 {
447 --top_ptr;
448 std::destroy_at(top_ptr);
449 if constexpr (dfs_stack_detail::Poisoned)
451 }
452
454 [[nodiscard]] T &top() noexcept
455 {
456 return top_ptr[-1];
457 }
458
460 [[nodiscard]] bool is_empty() const noexcept
461 {
462 return top_ptr == base;
463 }
464
466 [[nodiscard]] size_t size() const noexcept
467 {
468 return size_t(top_ptr - base);
469 }
470
473 [[nodiscard]] size_t capacity() const noexcept
474 {
475 return size_t(limit - base);
476 }
477
479 void clear() noexcept
480 {
481 std::destroy(base, top_ptr);
482 if constexpr (dfs_stack_detail::Poisoned)
483 dfs_stack_detail::poison(base, size() * sizeof(T));
484 top_ptr = base;
485 }
486
494 void release() noexcept
495 {
496 if (room == nullptr)
497 return;
498
499 clear();
501 set_room(nullptr, 0);
502 }
503};
504
516template <class It>
518{
520 using Node = std::remove_pointer_t<decltype(std::declval<It &>().get_tgt_node_ne())>;
521
523
526 template <class... Args>
527 requires std::constructible_from<It, Args &&...>
528 [[gnu::always_inline]] ALEPH_FLATTEN explicit Dfs_Arc_Frame(Args &&...args)
529 : it(std::forward<Args>(args)...)
530 {}
531
533 [[gnu::always_inline]] ALEPH_FLATTEN void next_arc() noexcept(noexcept(it.next_ne()))
534 {
535 it.next_ne();
536 }
537
550 template <int Bit, bool Marked_Too = false>
551 [[gnu::always_inline]] ALEPH_FLATTEN Node *next_target(Node *goal = nullptr) noexcept(
552 noexcept(it.next_ne()))
553 {
554 // the control bits, as the macros of aleph-graph.H give them: this
555 // header does not include it, so that the trees can take the stack
556 for (; it.has_curr(); it.next_ne())
557 {
558 auto arc = it.get_current_arc_ne();
559 if (arc->attrs.control_bits.get_bit(Bit))
560 continue;
561
562 // the target before the mark, which the compiler takes for a
563 // store that could change the iterator
564 auto tgt = it.get_tgt_node_ne();
565 arc->attrs.control_bits.set_bit(Bit, true);
566 if (Marked_Too or tgt == goal or not tgt->attrs.control_bits.get_bit(Bit))
567 return tgt;
568 }
569 return nullptr;
570 }
571};
572
590template <class T>
591using Dfs_Here = std::conditional_t<std::is_move_assignable_v<T>, T, std::optional<T>>;
592
601template <class T, class... Args>
602[[gnu::always_inline]] inline Dfs_Here<T> dfs_here(Args &&...args)
603{
604 if constexpr (std::is_move_assignable_v<T>)
605 return T(std::forward<Args>(args)...);
606 else
607 return Dfs_Here<T>(std::in_place, std::forward<Args>(args)...);
608}
609
616template <class T>
617[[gnu::always_inline]] inline T &dfs_frame(T &here) noexcept
618{
619 return here;
620}
621
629template <class T>
630[[gnu::always_inline]] inline T &dfs_frame(std::optional<T> &here) noexcept
631{
632 return *here;
633}
634
644template <class T, class... Args>
645[[gnu::always_inline]] inline void dfs_replace(T &here, Args &&...args)
646{
647 here = T(std::forward<Args>(args)...);
648}
649
659template <class T, class... Args>
660[[gnu::always_inline]] inline void dfs_replace(std::optional<T> &here, Args &&...args)
661{
662 here.emplace(std::forward<Args>(args)...);
663}
664
675template <class It>
676[[gnu::always_inline]] inline decltype(auto) dfs_curr(const It &it)
677{
678 if constexpr (requires { it.get_curr_ne(); })
679 return it.get_curr_ne();
680 else
681 return it.get_curr();
682}
683} // namespace Aleph
684
685#endif // TPL_DFS_STACK_H
Stack of the frames of a depth-first search that does not recurse.
static constexpr size_t Initial_Capacity
static constexpr size_t Second_Capacity
void clear() noexcept
Destroys all the frames, and keeps the room.
size_t capacity() const noexcept
The number of frames that fit in the room of the stack, 0 while it has none.
T & push(Args &&...args)
Builds a frame on top of the stack.
void give_room_back() noexcept
bool is_empty() const noexcept
Whether the stack has no frames.
~Dfs_Stack()
Destroys the frames; the thread keeps the room, if it fits in 1 MiB and is larger than the one kept.
Dfs_Stack & operator=(Dfs_Stack &&other) noexcept
Takes the frames and the room of other, which is left with the room of this stack and no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void release() noexcept
Destroys all the frames, and gives the room back.
size_t size() const noexcept
The number of frames.
void set_room(void *r, size_t bytes) noexcept
Dfs_Stack() noexcept=default
Builds an empty stack, which takes the room that the thread kept when it first needs room.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
T & push_in_poisoned_room(Args &&...args)
T & get_curr() const
Return the current item.
Definition htlist.H:1679
T & get_curr_ne() const noexcept
Return the current link guaranteeing no exception. Be careful.
Definition htlist.H:1669
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
bool has_curr() const noexcept
Definition htlist.H:969
void dfs_replace(T &here, Args &&...args)
Replaces the frame that a Dfs_Here holds with one built with args, by assignment.
Dfs_Here< T > dfs_here(Args &&...args)
Builds the variable of the frame of a search, with the frame built with args.
decltype(auto) dfs_curr(const It &it)
The current item of an iterator that has one.
T & dfs_frame(T &here) noexcept
The frame that a Dfs_Here holds.
std::conditional_t< std::is_move_assignable_v< T >, T, std::optional< T > > Dfs_Here
The variable that holds the frame of the node that a depth-first search visits.
#define ALEPH_FLATTEN
[[gnu::flatten]], or nothing where it would only make the compilation slower.
constexpr size_t Kept_Bytes
bool in_main_thread() noexcept
Room & open_room() noexcept
void free_room(void *r, size_t bytes) noexcept
Room & kept_room() noexcept
void poison(const void *p, size_t bytes) noexcept
void unpoison(const void *p, size_t bytes) noexcept
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
STL namespace.
The next arc of a node to look at, for a depth-first search that keeps only that in a frame.
Dfs_Arc_Frame(Args &&...args)
Builds the iterator with args, if they build one, so that a frame is copied by the copy constructor; ...
std::remove_pointer_t< decltype(std::declval< It & >().get_tgt_node_ne())> Node
The type of the nodes of the graph.
It it
The arcs of the node, on the next one to look at.
void next_arc() noexcept(noexcept(it.next_ne()))
Moves to the next arc; inlined, with all it calls.
Node * next_target(Node *goal=nullptr) noexcept(noexcept(it.next_ne()))
Moves the iterator to the next arc to follow, and gives its target.
Opens the room of the thread, and frees it when the thread ends, but for the thread of main() with gl...
Room of a destroyed stack, kept for the next stack of the thread.
Filter_Iterator< DynList< int >, DynList< int >::Iterator, Par > It
Definition test_htlist.C:61
Gsl_Compatible_Rng r