1 // <memory_resource> -*- C++ -*-
3 // Copyright (C) 2018-2024 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file include/memory_resource
26 * This is a Standard C++ Library header.
28 * This header declares the @ref pmr (std::pmr) memory resources.
32 #ifndef _GLIBCXX_MEMORY_RESOURCE
33 #define _GLIBCXX_MEMORY_RESOURCE 1
35 #pragma GCC system_header
37 #include <bits/requires_hosted.h> // polymorphic allocation
39 #define __glibcxx_want_polymorphic_allocator
40 #define __glibcxx_want_memory_resource
41 #include <bits/version.h>
43 #if __cplusplus >= 201703L
46 * @defgroup pmr Polymorphic memory resources
52 * Memory resources are classes that implement the `std::pmr::memory_resource`
53 * interface for allocating and deallocating memory. Unlike traditional C++
54 * allocators, memory resources are not value types and are used via pointers
55 * to the abstract base class. They are only responsible for allocating and
56 * deallocating, not for construction and destruction of objects. As a result,
57 * memory resources just allocate raw memory as type `void*` and are not
58 * templates that allocate/deallocate and construct/destroy a specific type.
60 * The class template `std::pmr::polymorphic_allocator` is an allocator that
61 * uses a memory resource for its allocations.
64 #include <bits/memory_resource.h>
65 #include <vector> // vector
66 #include <shared_mutex> // shared_mutex
67 #include <bits/align.h> // align
68 #include <debug/assertions.h>
70 namespace std _GLIBCXX_VISIBILITY(default)
72 _GLIBCXX_BEGIN_NAMESPACE_VERSION
76 #ifdef __cpp_lib_polymorphic_allocator // C++ >= 20 && HOSTED
77 template<typename _Tp = std::byte>
78 class polymorphic_allocator;
81 // Global memory resources
83 /// A pmr::memory_resource that uses `new` to allocate memory
86 * @headerfile memory_resource
89 [[nodiscard, __gnu__::__returns_nonnull__, __gnu__::__const__]]
91 new_delete_resource() noexcept;
93 /// A pmr::memory_resource that always throws `bad_alloc`
94 [[nodiscard, __gnu__::__returns_nonnull__, __gnu__::__const__]]
96 null_memory_resource() noexcept;
98 /// Replace the default memory resource pointer
99 [[__gnu__::__returns_nonnull__]]
101 set_default_resource(memory_resource* __r) noexcept;
103 /// Get the current default memory resource pointer
104 [[__gnu__::__returns_nonnull__]]
106 get_default_resource() noexcept;
108 // Pool resource classes
110 #if __cpp_lib_memory_resource >= 201603L // C++ >= 17 && hosted && gthread
111 class synchronized_pool_resource;
113 class unsynchronized_pool_resource;
114 class monotonic_buffer_resource;
116 /// Parameters for tuning a pool resource's behaviour.
119 * @headerfile memory_resource
124 /** @brief Upper limit on number of blocks in a chunk.
126 * A lower value prevents allocating huge chunks that could remain mostly
127 * unused, but means pools will need to replenished more frequently.
129 size_t max_blocks_per_chunk = 0;
131 /* @brief Largest block size (in bytes) that should be served from pools.
133 * Larger allocations will be served directly by the upstream resource,
134 * not from one of the pools managed by the pool resource.
136 size_t largest_required_pool_block = 0;
139 // Common implementation details for un-/synchronized pool resources.
140 class __pool_resource
142 friend class synchronized_pool_resource;
143 friend class unsynchronized_pool_resource;
145 __pool_resource(const pool_options& __opts, memory_resource* __upstream);
149 __pool_resource(const __pool_resource&) = delete;
150 __pool_resource& operator=(const __pool_resource&) = delete;
152 // Allocate a large unpooled block.
154 allocate(size_t __bytes, size_t __alignment);
156 // Deallocate a large unpooled block.
158 deallocate(void* __p, size_t __bytes, size_t __alignment);
161 // Deallocate unpooled memory.
162 void release() noexcept;
164 memory_resource* resource() const noexcept
165 { return _M_unpooled.get_allocator().resource(); }
169 _Pool* _M_alloc_pools();
171 const pool_options _M_opts;
174 // Collection of blocks too big for any pool, sorted by address.
175 // This also stores the only copy of the upstream memory resource pointer.
176 _GLIBCXX_STD_C::pmr::vector<_BigBlock> _M_unpooled;
181 #if __cpp_lib_memory_resource >= 201603L // C++ >= 17 && hosted && gthread
182 /// A thread-safe memory resource that manages pools of fixed-size blocks.
185 * @headerfile memory_resource
188 class synchronized_pool_resource : public memory_resource
191 synchronized_pool_resource(const pool_options& __opts,
192 memory_resource* __upstream)
193 __attribute__((__nonnull__));
195 synchronized_pool_resource()
196 : synchronized_pool_resource(pool_options(), get_default_resource())
200 synchronized_pool_resource(memory_resource* __upstream)
201 __attribute__((__nonnull__))
202 : synchronized_pool_resource(pool_options(), __upstream)
206 synchronized_pool_resource(const pool_options& __opts)
207 : synchronized_pool_resource(__opts, get_default_resource()) { }
209 synchronized_pool_resource(const synchronized_pool_resource&) = delete;
211 virtual ~synchronized_pool_resource();
213 synchronized_pool_resource&
214 operator=(const synchronized_pool_resource&) = delete;
219 upstream_resource() const noexcept
220 __attribute__((__returns_nonnull__))
221 { return _M_impl.resource(); }
223 pool_options options() const noexcept { return _M_impl._M_opts; }
227 do_allocate(size_t __bytes, size_t __alignment) override;
230 do_deallocate(void* __p, size_t __bytes, size_t __alignment) override;
233 do_is_equal(const memory_resource& __other) const noexcept override
234 { return this == &__other; }
237 // Thread-specific pools (only public for access by implementation details)
241 _TPools* _M_alloc_tpools(lock_guard<shared_mutex>&);
242 _TPools* _M_alloc_shared_tpools(lock_guard<shared_mutex>&);
243 auto _M_thread_specific_pools() noexcept;
245 __pool_resource _M_impl;
246 __gthread_key_t _M_key;
247 // Linked list of thread-specific pools. All threads share _M_tpools[0].
248 _TPools* _M_tpools = nullptr;
249 mutable shared_mutex _M_mx;
251 #endif // __cpp_lib_memory_resource >= 201603L
253 /// A non-thread-safe memory resource that manages pools of fixed-size blocks.
256 * @headerfile memory_resource
259 class unsynchronized_pool_resource : public memory_resource
262 [[__gnu__::__nonnull__]]
263 unsynchronized_pool_resource(const pool_options& __opts,
264 memory_resource* __upstream);
266 unsynchronized_pool_resource()
267 : unsynchronized_pool_resource(pool_options(), get_default_resource())
270 [[__gnu__::__nonnull__]]
272 unsynchronized_pool_resource(memory_resource* __upstream)
273 : unsynchronized_pool_resource(pool_options(), __upstream)
277 unsynchronized_pool_resource(const pool_options& __opts)
278 : unsynchronized_pool_resource(__opts, get_default_resource()) { }
280 unsynchronized_pool_resource(const unsynchronized_pool_resource&) = delete;
282 virtual ~unsynchronized_pool_resource();
284 unsynchronized_pool_resource&
285 operator=(const unsynchronized_pool_resource&) = delete;
289 [[__gnu__::__returns_nonnull__]]
291 upstream_resource() const noexcept
292 { return _M_impl.resource(); }
294 pool_options options() const noexcept { return _M_impl._M_opts; }
298 do_allocate(size_t __bytes, size_t __alignment) override;
301 do_deallocate(void* __p, size_t __bytes, size_t __alignment) override;
304 do_is_equal(const memory_resource& __other) const noexcept override
305 { return this == &__other; }
308 using _Pool = __pool_resource::_Pool;
310 auto _M_find_pool(size_t) noexcept;
312 __pool_resource _M_impl;
313 _Pool* _M_pools = nullptr;
316 /// A memory resource that allocates from a fixed-size buffer.
318 * The main feature of a `pmr::monotonic_buffer_resource` is that its
319 * `do_deallocate` does nothing. This makes it very fast because there is no
320 * need to manage a free list, and every allocation simply returns a new
321 * block of memory, rather than searching for a suitably-sized free block.
322 * Because deallocating is a no-op, the amount of memory used by the resource
323 * only grows until `release()` (or the destructor) is called to return all
324 * memory to upstream.
326 * A `monotonic_buffer_resource` can be initialized with a buffer that
327 * will be used to satisfy all allocation requests, until the buffer is full.
328 * After that a new buffer will be allocated from the upstream resource.
329 * By using a stack buffer and `pmr::null_memory_resource()` as the upstream
330 * you can get a memory resource that only uses the stack and never
331 * dynamically allocates.
334 * @headerfile memory_resource
337 class monotonic_buffer_resource : public memory_resource
341 monotonic_buffer_resource(memory_resource* __upstream) noexcept
342 __attribute__((__nonnull__))
343 : _M_upstream(__upstream)
344 { _GLIBCXX_DEBUG_ASSERT(__upstream != nullptr); }
346 monotonic_buffer_resource(size_t __initial_size,
347 memory_resource* __upstream) noexcept
348 __attribute__((__nonnull__))
349 : _M_next_bufsiz(__initial_size),
350 _M_upstream(__upstream)
352 _GLIBCXX_DEBUG_ASSERT(__upstream != nullptr);
353 _GLIBCXX_DEBUG_ASSERT(__initial_size > 0);
356 monotonic_buffer_resource(void* __buffer, size_t __buffer_size,
357 memory_resource* __upstream) noexcept
358 __attribute__((__nonnull__(4)))
359 : _M_current_buf(__buffer), _M_avail(__buffer_size),
360 _M_next_bufsiz(_S_next_bufsize(__buffer_size)),
361 _M_upstream(__upstream),
362 _M_orig_buf(__buffer), _M_orig_size(__buffer_size)
364 _GLIBCXX_DEBUG_ASSERT(__upstream != nullptr);
365 _GLIBCXX_DEBUG_ASSERT(__buffer != nullptr || __buffer_size == 0);
368 monotonic_buffer_resource() noexcept
369 : monotonic_buffer_resource(get_default_resource())
373 monotonic_buffer_resource(size_t __initial_size) noexcept
374 : monotonic_buffer_resource(__initial_size, get_default_resource())
377 monotonic_buffer_resource(void* __buffer, size_t __buffer_size) noexcept
378 : monotonic_buffer_resource(__buffer, __buffer_size, get_default_resource())
381 monotonic_buffer_resource(const monotonic_buffer_resource&) = delete;
383 virtual ~monotonic_buffer_resource(); // key function
385 monotonic_buffer_resource&
386 operator=(const monotonic_buffer_resource&) = delete;
392 _M_release_buffers();
394 // reset to initial state at contruction:
395 if ((_M_current_buf = _M_orig_buf))
397 _M_avail = _M_orig_size;
398 _M_next_bufsiz = _S_next_bufsize(_M_orig_size);
403 _M_next_bufsiz = _M_orig_size;
408 upstream_resource() const noexcept
409 __attribute__((__returns_nonnull__))
410 { return _M_upstream; }
414 do_allocate(size_t __bytes, size_t __alignment) override
416 if (__builtin_expect(__bytes == 0, false))
417 __bytes = 1; // Ensures we don't return the same pointer twice.
419 void* __p = std::align(__alignment, __bytes, _M_current_buf, _M_avail);
420 if (__builtin_expect(__p == nullptr, false))
422 _M_new_buffer(__bytes, __alignment);
423 __p = _M_current_buf;
425 _M_current_buf = (char*)_M_current_buf + __bytes;
431 do_deallocate(void*, size_t, size_t) override
435 do_is_equal(const memory_resource& __other) const noexcept override
436 { return this == &__other; }
439 // Update _M_current_buf and _M_avail to refer to a new buffer with
440 // at least the specified size and alignment, allocated from upstream.
442 _M_new_buffer(size_t __bytes, size_t __alignment);
444 // Deallocate all buffers obtained from upstream.
446 _M_release_buffers() noexcept;
449 _S_next_bufsize(size_t __buffer_size) noexcept
451 if (__builtin_expect(__buffer_size == 0, false))
453 return __buffer_size * _S_growth_factor;
456 static constexpr size_t _S_init_bufsize = 128 * sizeof(void*);
457 static constexpr float _S_growth_factor = 1.5;
459 void* _M_current_buf = nullptr;
461 size_t _M_next_bufsiz = _S_init_bufsize;
463 // Initial values set at construction and reused by release():
464 memory_resource* const _M_upstream;
465 void* const _M_orig_buf = nullptr;
466 size_t const _M_orig_size = _M_next_bufsiz;
469 _Chunk* _M_head = nullptr;
473 _GLIBCXX_END_NAMESPACE_VERSION
477 #endif // _GLIBCXX_MEMORY_RESOURCE