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 #include "absl/container/internal/raw_hash_set.h"
16
17 #include <atomic>
18 #include <cassert>
19 #include <cstddef>
20 #include <cstring>
21
22 #include "absl/base/attributes.h"
23 #include "absl/base/config.h"
24 #include "absl/base/dynamic_annotations.h"
25 #include "absl/hash/hash.h"
26
27 namespace absl {
28 ABSL_NAMESPACE_BEGIN
29 namespace container_internal {
30
31 // We have space for `growth_left` before a single block of control bytes. A
32 // single block of empty control bytes for tables without any slots allocated.
33 // This enables removing a branch in the hot path of find(). In order to ensure
34 // that the control bytes are aligned to 16, we have 16 bytes before the control
35 // bytes even though growth_left only needs 8.
ZeroCtrlT()36 constexpr ctrl_t ZeroCtrlT() { return static_cast<ctrl_t>(0); }
37 alignas(16) ABSL_CONST_INIT ABSL_DLL const ctrl_t kEmptyGroup[32] = {
38 ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(),
39 ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(),
40 ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(),
41 ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(),
42 ctrl_t::kSentinel, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
43 ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
44 ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
45 ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty};
46
47 #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
48 constexpr size_t Group::kWidth;
49 #endif
50
51 namespace {
52
53 // Returns "random" seed.
RandomSeed()54 inline size_t RandomSeed() {
55 #ifdef ABSL_HAVE_THREAD_LOCAL
56 static thread_local size_t counter = 0;
57 // On Linux kernels >= 5.4 the MSAN runtime has a false-positive when
58 // accessing thread local storage data from loaded libraries
59 // (https://github.com/google/sanitizers/issues/1265), for this reason counter
60 // needs to be annotated as initialized.
61 ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(&counter, sizeof(size_t));
62 size_t value = ++counter;
63 #else // ABSL_HAVE_THREAD_LOCAL
64 static std::atomic<size_t> counter(0);
65 size_t value = counter.fetch_add(1, std::memory_order_relaxed);
66 #endif // ABSL_HAVE_THREAD_LOCAL
67 return value ^ static_cast<size_t>(reinterpret_cast<uintptr_t>(&counter));
68 }
69
70 } // namespace
71
EmptyGeneration()72 GenerationType* EmptyGeneration() {
73 if (SwisstableGenerationsEnabled()) {
74 constexpr size_t kNumEmptyGenerations = 1024;
75 static constexpr GenerationType kEmptyGenerations[kNumEmptyGenerations]{};
76 return const_cast<GenerationType*>(
77 &kEmptyGenerations[RandomSeed() % kNumEmptyGenerations]);
78 }
79 return nullptr;
80 }
81
82 bool CommonFieldsGenerationInfoEnabled::
should_rehash_for_bug_detection_on_insert(const ctrl_t * ctrl,size_t capacity) const83 should_rehash_for_bug_detection_on_insert(const ctrl_t* ctrl,
84 size_t capacity) const {
85 if (reserved_growth_ == kReservedGrowthJustRanOut) return true;
86 if (reserved_growth_ > 0) return false;
87 // Note: we can't use the abseil-random library because abseil-random
88 // depends on swisstable. We want to return true with probability
89 // `min(1, RehashProbabilityConstant() / capacity())`. In order to do this,
90 // we probe based on a random hash and see if the offset is less than
91 // RehashProbabilityConstant().
92 return probe(ctrl, capacity, absl::HashOf(RandomSeed())).offset() <
93 RehashProbabilityConstant();
94 }
95
ShouldInsertBackwards(size_t hash,const ctrl_t * ctrl)96 bool ShouldInsertBackwards(size_t hash, const ctrl_t* ctrl) {
97 // To avoid problems with weak hashes and single bit tests, we use % 13.
98 // TODO(kfm,sbenza): revisit after we do unconditional mixing
99 return (H1(hash, ctrl) ^ RandomSeed()) % 13 > 6;
100 }
101
ConvertDeletedToEmptyAndFullToDeleted(ctrl_t * ctrl,size_t capacity)102 void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity) {
103 assert(ctrl[capacity] == ctrl_t::kSentinel);
104 assert(IsValidCapacity(capacity));
105 for (ctrl_t* pos = ctrl; pos < ctrl + capacity; pos += Group::kWidth) {
106 Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos);
107 }
108 // Copy the cloned ctrl bytes.
109 std::memcpy(ctrl + capacity + 1, ctrl, NumClonedBytes());
110 ctrl[capacity] = ctrl_t::kSentinel;
111 }
112 // Extern template instantiation for inline function.
113 template FindInfo find_first_non_full(const CommonFields&, size_t);
114
find_first_non_full_outofline(const CommonFields & common,size_t hash)115 FindInfo find_first_non_full_outofline(const CommonFields& common,
116 size_t hash) {
117 return find_first_non_full(common, hash);
118 }
119
120 // Returns the address of the ith slot in slots where each slot occupies
121 // slot_size.
SlotAddress(void * slot_array,size_t slot,size_t slot_size)122 static inline void* SlotAddress(void* slot_array, size_t slot,
123 size_t slot_size) {
124 return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(slot_array) +
125 (slot * slot_size));
126 }
127
128 // Returns the address of the slot just after slot assuming each slot has the
129 // specified size.
NextSlot(void * slot,size_t slot_size)130 static inline void* NextSlot(void* slot, size_t slot_size) {
131 return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(slot) + slot_size);
132 }
133
134 // Returns the address of the slot just before slot assuming each slot has the
135 // specified size.
PrevSlot(void * slot,size_t slot_size)136 static inline void* PrevSlot(void* slot, size_t slot_size) {
137 return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(slot) - slot_size);
138 }
139
DropDeletesWithoutResize(CommonFields & common,const PolicyFunctions & policy,void * tmp_space)140 void DropDeletesWithoutResize(CommonFields& common,
141 const PolicyFunctions& policy, void* tmp_space) {
142 void* set = &common;
143 void* slot_array = common.slot_array();
144 const size_t capacity = common.capacity();
145 assert(IsValidCapacity(capacity));
146 assert(!is_small(capacity));
147 // Algorithm:
148 // - mark all DELETED slots as EMPTY
149 // - mark all FULL slots as DELETED
150 // - for each slot marked as DELETED
151 // hash = Hash(element)
152 // target = find_first_non_full(hash)
153 // if target is in the same group
154 // mark slot as FULL
155 // else if target is EMPTY
156 // transfer element to target
157 // mark slot as EMPTY
158 // mark target as FULL
159 // else if target is DELETED
160 // swap current element with target element
161 // mark target as FULL
162 // repeat procedure for current slot with moved from element (target)
163 ctrl_t* ctrl = common.control();
164 ConvertDeletedToEmptyAndFullToDeleted(ctrl, capacity);
165 auto hasher = policy.hash_slot;
166 auto transfer = policy.transfer;
167 const size_t slot_size = policy.slot_size;
168
169 size_t total_probe_length = 0;
170 void* slot_ptr = SlotAddress(slot_array, 0, slot_size);
171 for (size_t i = 0; i != capacity;
172 ++i, slot_ptr = NextSlot(slot_ptr, slot_size)) {
173 assert(slot_ptr == SlotAddress(slot_array, i, slot_size));
174 if (!IsDeleted(ctrl[i])) continue;
175 const size_t hash = (*hasher)(set, slot_ptr);
176 const FindInfo target = find_first_non_full(common, hash);
177 const size_t new_i = target.offset;
178 total_probe_length += target.probe_length;
179
180 // Verify if the old and new i fall within the same group wrt the hash.
181 // If they do, we don't need to move the object as it falls already in the
182 // best probe we can.
183 const size_t probe_offset = probe(common, hash).offset();
184 const auto probe_index = [probe_offset, capacity](size_t pos) {
185 return ((pos - probe_offset) & capacity) / Group::kWidth;
186 };
187
188 // Element doesn't move.
189 if (ABSL_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) {
190 SetCtrl(common, i, H2(hash), slot_size);
191 continue;
192 }
193
194 void* new_slot_ptr = SlotAddress(slot_array, new_i, slot_size);
195 if (IsEmpty(ctrl[new_i])) {
196 // Transfer element to the empty spot.
197 // SetCtrl poisons/unpoisons the slots so we have to call it at the
198 // right time.
199 SetCtrl(common, new_i, H2(hash), slot_size);
200 (*transfer)(set, new_slot_ptr, slot_ptr);
201 SetCtrl(common, i, ctrl_t::kEmpty, slot_size);
202 } else {
203 assert(IsDeleted(ctrl[new_i]));
204 SetCtrl(common, new_i, H2(hash), slot_size);
205 // Until we are done rehashing, DELETED marks previously FULL slots.
206
207 // Swap i and new_i elements.
208 (*transfer)(set, tmp_space, new_slot_ptr);
209 (*transfer)(set, new_slot_ptr, slot_ptr);
210 (*transfer)(set, slot_ptr, tmp_space);
211
212 // repeat the processing of the ith slot
213 --i;
214 slot_ptr = PrevSlot(slot_ptr, slot_size);
215 }
216 }
217 ResetGrowthLeft(common);
218 common.infoz().RecordRehash(total_probe_length);
219 }
220
EraseMetaOnly(CommonFields & c,ctrl_t * it,size_t slot_size)221 void EraseMetaOnly(CommonFields& c, ctrl_t* it, size_t slot_size) {
222 assert(IsFull(*it) && "erasing a dangling iterator");
223 c.set_size(c.size() - 1);
224 const auto index = static_cast<size_t>(it - c.control());
225 const size_t index_before = (index - Group::kWidth) & c.capacity();
226 const auto empty_after = Group(it).MaskEmpty();
227 const auto empty_before = Group(c.control() + index_before).MaskEmpty();
228
229 // We count how many consecutive non empties we have to the right and to the
230 // left of `it`. If the sum is >= kWidth then there is at least one probe
231 // window that might have seen a full group.
232 bool was_never_full = empty_before && empty_after &&
233 static_cast<size_t>(empty_after.TrailingZeros()) +
234 empty_before.LeadingZeros() <
235 Group::kWidth;
236
237 SetCtrl(c, index, was_never_full ? ctrl_t::kEmpty : ctrl_t::kDeleted,
238 slot_size);
239 c.set_growth_left(c.growth_left() + (was_never_full ? 1 : 0));
240 c.infoz().RecordErase();
241 }
242
ClearBackingArray(CommonFields & c,const PolicyFunctions & policy,bool reuse)243 void ClearBackingArray(CommonFields& c, const PolicyFunctions& policy,
244 bool reuse) {
245 c.set_size(0);
246 if (reuse) {
247 ResetCtrl(c, policy.slot_size);
248 c.infoz().RecordStorageChanged(0, c.capacity());
249 } else {
250 (*policy.dealloc)(c, policy);
251 c.set_control(EmptyGroup());
252 c.set_generation_ptr(EmptyGeneration());
253 c.set_slots(nullptr);
254 c.set_capacity(0);
255 c.infoz().RecordClearedReservation();
256 assert(c.size() == 0);
257 c.infoz().RecordStorageChanged(0, 0);
258 }
259 }
260
261 } // namespace container_internal
262 ABSL_NAMESPACE_END
263 } // namespace absl
264