xref: /aosp_15_r20/external/abseil-cpp/absl/container/internal/container_memory.h (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
16 #define ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
17 
18 #include <cassert>
19 #include <cstddef>
20 #include <cstring>
21 #include <memory>
22 #include <new>
23 #include <tuple>
24 #include <type_traits>
25 #include <utility>
26 
27 #include "absl/base/config.h"
28 #include "absl/memory/memory.h"
29 #include "absl/meta/type_traits.h"
30 #include "absl/utility/utility.h"
31 
32 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
33 #include <sanitizer/asan_interface.h>
34 #endif
35 
36 #ifdef ABSL_HAVE_MEMORY_SANITIZER
37 #include <sanitizer/msan_interface.h>
38 #endif
39 
40 namespace absl {
41 ABSL_NAMESPACE_BEGIN
42 namespace container_internal {
43 
44 template <size_t Alignment>
45 struct alignas(Alignment) AlignedType {};
46 
47 // Allocates at least n bytes aligned to the specified alignment.
48 // Alignment must be a power of 2. It must be positive.
49 //
50 // Note that many allocators don't honor alignment requirements above certain
51 // threshold (usually either alignof(std::max_align_t) or alignof(void*)).
52 // Allocate() doesn't apply alignment corrections. If the underlying allocator
53 // returns insufficiently alignment pointer, that's what you are going to get.
54 template <size_t Alignment, class Alloc>
Allocate(Alloc * alloc,size_t n)55 void* Allocate(Alloc* alloc, size_t n) {
56   static_assert(Alignment > 0, "");
57   assert(n && "n must be positive");
58   using M = AlignedType<Alignment>;
59   using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
60   using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
61   // On macOS, "mem_alloc" is a #define with one argument defined in
62   // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
63   // with the "foo(bar)" syntax.
64   A my_mem_alloc(*alloc);
65   void* p = AT::allocate(my_mem_alloc, (n + sizeof(M) - 1) / sizeof(M));
66   assert(reinterpret_cast<uintptr_t>(p) % Alignment == 0 &&
67          "allocator does not respect alignment");
68   return p;
69 }
70 
71 // Returns true if the destruction of the value with given Allocator will be
72 // trivial.
73 template <class Allocator, class ValueType>
IsDestructionTrivial()74 constexpr auto IsDestructionTrivial() {
75   constexpr bool result =
76       std::is_trivially_destructible<ValueType>::value &&
77       std::is_same<typename absl::allocator_traits<
78                        Allocator>::template rebind_alloc<char>,
79                    std::allocator<char>>::value;
80   return std::integral_constant<bool, result>();
81 }
82 
83 // The pointer must have been previously obtained by calling
84 // Allocate<Alignment>(alloc, n).
85 template <size_t Alignment, class Alloc>
Deallocate(Alloc * alloc,void * p,size_t n)86 void Deallocate(Alloc* alloc, void* p, size_t n) {
87   static_assert(Alignment > 0, "");
88   assert(n && "n must be positive");
89   using M = AlignedType<Alignment>;
90   using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
91   using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
92   // On macOS, "mem_alloc" is a #define with one argument defined in
93   // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
94   // with the "foo(bar)" syntax.
95   A my_mem_alloc(*alloc);
96   AT::deallocate(my_mem_alloc, static_cast<M*>(p),
97                  (n + sizeof(M) - 1) / sizeof(M));
98 }
99 
100 namespace memory_internal {
101 
102 // Constructs T into uninitialized storage pointed by `ptr` using the args
103 // specified in the tuple.
104 template <class Alloc, class T, class Tuple, size_t... I>
ConstructFromTupleImpl(Alloc * alloc,T * ptr,Tuple && t,absl::index_sequence<I...>)105 void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t,
106                             absl::index_sequence<I...>) {
107   absl::allocator_traits<Alloc>::construct(
108       *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...);
109 }
110 
111 template <class T, class F>
112 struct WithConstructedImplF {
113   template <class... Args>
decltypeWithConstructedImplF114   decltype(std::declval<F>()(std::declval<T>())) operator()(
115       Args&&... args) const {
116     return std::forward<F>(f)(T(std::forward<Args>(args)...));
117   }
118   F&& f;
119 };
120 
121 template <class T, class Tuple, size_t... Is, class F>
decltype(std::declval<F> ()(std::declval<T> ()))122 decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl(
123     Tuple&& t, absl::index_sequence<Is...>, F&& f) {
124   return WithConstructedImplF<T, F>{std::forward<F>(f)}(
125       std::get<Is>(std::forward<Tuple>(t))...);
126 }
127 
128 template <class T, size_t... Is>
129 auto TupleRefImpl(T&& t, absl::index_sequence<Is...>)
130     -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) {
131   return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...);
132 }
133 
134 // Returns a tuple of references to the elements of the input tuple. T must be a
135 // tuple.
136 template <class T>
137 auto TupleRef(T&& t) -> decltype(TupleRefImpl(
138     std::forward<T>(t),
139     absl::make_index_sequence<
140         std::tuple_size<typename std::decay<T>::type>::value>())) {
141   return TupleRefImpl(
142       std::forward<T>(t),
143       absl::make_index_sequence<
144           std::tuple_size<typename std::decay<T>::type>::value>());
145 }
146 
147 template <class F, class K, class V>
decltype(std::declval<F> ()(std::declval<const K &> (),std::piecewise_construct,std::declval<std::tuple<K>> (),std::declval<V> ()))148 decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct,
149                            std::declval<std::tuple<K>>(), std::declval<V>()))
150 DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
151   const auto& key = std::get<0>(p.first);
152   return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
153                             std::move(p.second));
154 }
155 
156 }  // namespace memory_internal
157 
158 // Constructs T into uninitialized storage pointed by `ptr` using the args
159 // specified in the tuple.
160 template <class Alloc, class T, class Tuple>
ConstructFromTuple(Alloc * alloc,T * ptr,Tuple && t)161 void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
162   memory_internal::ConstructFromTupleImpl(
163       alloc, ptr, std::forward<Tuple>(t),
164       absl::make_index_sequence<
165           std::tuple_size<typename std::decay<Tuple>::type>::value>());
166 }
167 
168 // Constructs T using the args specified in the tuple and calls F with the
169 // constructed value.
170 template <class T, class Tuple, class F>
decltype(std::declval<F> ()(std::declval<T> ()))171 decltype(std::declval<F>()(std::declval<T>())) WithConstructed(Tuple&& t,
172                                                                F&& f) {
173   return memory_internal::WithConstructedImpl<T>(
174       std::forward<Tuple>(t),
175       absl::make_index_sequence<
176           std::tuple_size<typename std::decay<Tuple>::type>::value>(),
177       std::forward<F>(f));
178 }
179 
180 // Given arguments of an std::pair's constructor, PairArgs() returns a pair of
181 // tuples with references to the passed arguments. The tuples contain
182 // constructor arguments for the first and the second elements of the pair.
183 //
184 // The following two snippets are equivalent.
185 //
186 // 1. std::pair<F, S> p(args...);
187 //
188 // 2. auto a = PairArgs(args...);
189 //    std::pair<F, S> p(std::piecewise_construct,
190 //                      std::move(a.first), std::move(a.second));
PairArgs()191 inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
192 template <class F, class S>
PairArgs(F && f,S && s)193 std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
194   return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
195           std::forward_as_tuple(std::forward<S>(s))};
196 }
197 template <class F, class S>
PairArgs(const std::pair<F,S> & p)198 std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
199     const std::pair<F, S>& p) {
200   return PairArgs(p.first, p.second);
201 }
202 template <class F, class S>
PairArgs(std::pair<F,S> && p)203 std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
204   return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
205 }
206 template <class F, class S>
207 auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
208     -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
209                                memory_internal::TupleRef(std::forward<S>(s)))) {
210   return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
211                         memory_internal::TupleRef(std::forward<S>(s)));
212 }
213 
214 // A helper function for implementing apply() in map policies.
215 template <class F, class... Args>
216 auto DecomposePair(F&& f, Args&&... args)
217     -> decltype(memory_internal::DecomposePairImpl(
218         std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
219   return memory_internal::DecomposePairImpl(
220       std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
221 }
222 
223 // A helper function for implementing apply() in set policies.
224 template <class F, class Arg>
decltype(std::declval<F> ()(std::declval<const Arg &> (),std::declval<Arg> ()))225 decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
226 DecomposeValue(F&& f, Arg&& arg) {
227   const auto& key = arg;
228   return std::forward<F>(f)(key, std::forward<Arg>(arg));
229 }
230 
231 // Helper functions for asan and msan.
SanitizerPoisonMemoryRegion(const void * m,size_t s)232 inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) {
233 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
234   ASAN_POISON_MEMORY_REGION(m, s);
235 #endif
236 #ifdef ABSL_HAVE_MEMORY_SANITIZER
237   __msan_poison(m, s);
238 #endif
239   (void)m;
240   (void)s;
241 }
242 
SanitizerUnpoisonMemoryRegion(const void * m,size_t s)243 inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) {
244 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
245   ASAN_UNPOISON_MEMORY_REGION(m, s);
246 #endif
247 #ifdef ABSL_HAVE_MEMORY_SANITIZER
248   __msan_unpoison(m, s);
249 #endif
250   (void)m;
251   (void)s;
252 }
253 
254 template <typename T>
SanitizerPoisonObject(const T * object)255 inline void SanitizerPoisonObject(const T* object) {
256   SanitizerPoisonMemoryRegion(object, sizeof(T));
257 }
258 
259 template <typename T>
SanitizerUnpoisonObject(const T * object)260 inline void SanitizerUnpoisonObject(const T* object) {
261   SanitizerUnpoisonMemoryRegion(object, sizeof(T));
262 }
263 
264 namespace memory_internal {
265 
266 // If Pair is a standard-layout type, OffsetOf<Pair>::kFirst and
267 // OffsetOf<Pair>::kSecond are equivalent to offsetof(Pair, first) and
268 // offsetof(Pair, second) respectively. Otherwise they are -1.
269 //
270 // The purpose of OffsetOf is to avoid calling offsetof() on non-standard-layout
271 // type, which is non-portable.
272 template <class Pair, class = std::true_type>
273 struct OffsetOf {
274   static constexpr size_t kFirst = static_cast<size_t>(-1);
275   static constexpr size_t kSecond = static_cast<size_t>(-1);
276 };
277 
278 template <class Pair>
279 struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> {
280   static constexpr size_t kFirst = offsetof(Pair, first);
281   static constexpr size_t kSecond = offsetof(Pair, second);
282 };
283 
284 template <class K, class V>
285 struct IsLayoutCompatible {
286  private:
287   struct Pair {
288     K first;
289     V second;
290   };
291 
292   // Is P layout-compatible with Pair?
293   template <class P>
294   static constexpr bool LayoutCompatible() {
295     return std::is_standard_layout<P>() && sizeof(P) == sizeof(Pair) &&
296            alignof(P) == alignof(Pair) &&
297            memory_internal::OffsetOf<P>::kFirst ==
298                memory_internal::OffsetOf<Pair>::kFirst &&
299            memory_internal::OffsetOf<P>::kSecond ==
300                memory_internal::OffsetOf<Pair>::kSecond;
301   }
302 
303  public:
304   // Whether pair<const K, V> and pair<K, V> are layout-compatible. If they are,
305   // then it is safe to store them in a union and read from either.
306   static constexpr bool value = std::is_standard_layout<K>() &&
307                                 std::is_standard_layout<Pair>() &&
308                                 memory_internal::OffsetOf<Pair>::kFirst == 0 &&
309                                 LayoutCompatible<std::pair<K, V>>() &&
310                                 LayoutCompatible<std::pair<const K, V>>();
311 };
312 
313 }  // namespace memory_internal
314 
315 // The internal storage type for key-value containers like flat_hash_map.
316 //
317 // It is convenient for the value_type of a flat_hash_map<K, V> to be
318 // pair<const K, V>; the "const K" prevents accidental modification of the key
319 // when dealing with the reference returned from find() and similar methods.
320 // However, this creates other problems; we want to be able to emplace(K, V)
321 // efficiently with move operations, and similarly be able to move a
322 // pair<K, V> in insert().
323 //
324 // The solution is this union, which aliases the const and non-const versions
325 // of the pair. This also allows flat_hash_map<const K, V> to work, even though
326 // that has the same efficiency issues with move in emplace() and insert() -
327 // but people do it anyway.
328 //
329 // If kMutableKeys is false, only the value member can be accessed.
330 //
331 // If kMutableKeys is true, key can be accessed through all slots while value
332 // and mutable_value must be accessed only via INITIALIZED slots. Slots are
333 // created and destroyed via mutable_value so that the key can be moved later.
334 //
335 // Accessing one of the union fields while the other is active is safe as
336 // long as they are layout-compatible, which is guaranteed by the definition of
337 // kMutableKeys. For C++11, the relevant section of the standard is
338 // https://timsong-cpp.github.io/cppwp/n3337/class.mem#19 (9.2.19)
339 template <class K, class V>
340 union map_slot_type {
341   map_slot_type() {}
342   ~map_slot_type() = delete;
343   using value_type = std::pair<const K, V>;
344   using mutable_value_type =
345       std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
346 
347   value_type value;
348   mutable_value_type mutable_value;
349   absl::remove_const_t<K> key;
350 };
351 
352 template <class K, class V>
353 struct map_slot_policy {
354   using slot_type = map_slot_type<K, V>;
355   using value_type = std::pair<const K, V>;
356   using mutable_value_type =
357       std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
358 
359  private:
360   static void emplace(slot_type* slot) {
361     // The construction of union doesn't do anything at runtime but it allows us
362     // to access its members without violating aliasing rules.
363     new (slot) slot_type;
364   }
365   // If pair<const K, V> and pair<K, V> are layout-compatible, we can accept one
366   // or the other via slot_type. We are also free to access the key via
367   // slot_type::key in this case.
368   using kMutableKeys = memory_internal::IsLayoutCompatible<K, V>;
369 
370  public:
371   static value_type& element(slot_type* slot) { return slot->value; }
372   static const value_type& element(const slot_type* slot) {
373     return slot->value;
374   }
375 
376   // When C++17 is available, we can use std::launder to provide mutable
377   // access to the key for use in node handle.
378 #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
379   static K& mutable_key(slot_type* slot) {
380     // Still check for kMutableKeys so that we can avoid calling std::launder
381     // unless necessary because it can interfere with optimizations.
382     return kMutableKeys::value ? slot->key
383                                : *std::launder(const_cast<K*>(
384                                      std::addressof(slot->value.first)));
385   }
386 #else  // !(defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606)
387   static const K& mutable_key(slot_type* slot) { return key(slot); }
388 #endif
389 
390   static const K& key(const slot_type* slot) {
391     return kMutableKeys::value ? slot->key : slot->value.first;
392   }
393 
394   template <class Allocator, class... Args>
395   static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
396     emplace(slot);
397     if (kMutableKeys::value) {
398       absl::allocator_traits<Allocator>::construct(*alloc, &slot->mutable_value,
399                                                    std::forward<Args>(args)...);
400     } else {
401       absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
402                                                    std::forward<Args>(args)...);
403     }
404   }
405 
406   // Construct this slot by moving from another slot.
407   template <class Allocator>
408   static void construct(Allocator* alloc, slot_type* slot, slot_type* other) {
409     emplace(slot);
410     if (kMutableKeys::value) {
411       absl::allocator_traits<Allocator>::construct(
412           *alloc, &slot->mutable_value, std::move(other->mutable_value));
413     } else {
414       absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
415                                                    std::move(other->value));
416     }
417   }
418 
419   // Construct this slot by copying from another slot.
420   template <class Allocator>
421   static void construct(Allocator* alloc, slot_type* slot,
422                         const slot_type* other) {
423     emplace(slot);
424     absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
425                                                  other->value);
426   }
427 
428   template <class Allocator>
429   static auto destroy(Allocator* alloc, slot_type* slot) {
430     if (kMutableKeys::value) {
431       absl::allocator_traits<Allocator>::destroy(*alloc, &slot->mutable_value);
432     } else {
433       absl::allocator_traits<Allocator>::destroy(*alloc, &slot->value);
434     }
435     return IsDestructionTrivial<Allocator, value_type>();
436   }
437 
438   template <class Allocator>
439   static auto transfer(Allocator* alloc, slot_type* new_slot,
440                        slot_type* old_slot) {
441     auto is_relocatable =
442         typename absl::is_trivially_relocatable<value_type>::type();
443 
444     emplace(new_slot);
445 #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
446     if (is_relocatable) {
447       // TODO(b/247130232,b/251814870): remove casts after fixing warnings.
448       std::memcpy(static_cast<void*>(std::launder(&new_slot->value)),
449                   static_cast<const void*>(&old_slot->value),
450                   sizeof(value_type));
451       return is_relocatable;
452     }
453 #endif
454 
455     if (kMutableKeys::value) {
456       absl::allocator_traits<Allocator>::construct(
457           *alloc, &new_slot->mutable_value, std::move(old_slot->mutable_value));
458     } else {
459       absl::allocator_traits<Allocator>::construct(*alloc, &new_slot->value,
460                                                    std::move(old_slot->value));
461     }
462     destroy(alloc, old_slot);
463     return is_relocatable;
464   }
465 };
466 
467 // Type erased function for computing hash of the slot.
468 using HashSlotFn = size_t (*)(const void* hash_fn, void* slot);
469 
470 // Type erased function to apply `Fn` to data inside of the `slot`.
471 // The data is expected to have type `T`.
472 template <class Fn, class T>
473 size_t TypeErasedApplyToSlotFn(const void* fn, void* slot) {
474   const auto* f = static_cast<const Fn*>(fn);
475   return (*f)(*static_cast<const T*>(slot));
476 }
477 
478 // Type erased function to apply `Fn` to data inside of the `*slot_ptr`.
479 // The data is expected to have type `T`.
480 template <class Fn, class T>
481 size_t TypeErasedDerefAndApplyToSlotFn(const void* fn, void* slot_ptr) {
482   const auto* f = static_cast<const Fn*>(fn);
483   const T* slot = *static_cast<const T**>(slot_ptr);
484   return (*f)(*slot);
485 }
486 
487 }  // namespace container_internal
488 ABSL_NAMESPACE_END
489 }  // namespace absl
490 
491 #endif  // ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
492