container_memory.h 17 KB

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