Path: blob/main/contrib/llvm-project/libc/src/__support/HashTable/table.h
213799 views
//===-- Resizable Monotonic HashTable ---------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLVM_LIBC_SRC___SUPPORT_HASHTABLE_TABLE_H9#define LLVM_LIBC_SRC___SUPPORT_HASHTABLE_TABLE_H1011#include "hdr/types/ENTRY.h"12#include "src/__support/CPP/bit.h" // bit_ceil13#include "src/__support/CPP/new.h"14#include "src/__support/HashTable/bitmask.h"15#include "src/__support/hash.h"16#include "src/__support/macros/attributes.h"17#include "src/__support/macros/config.h"18#include "src/__support/macros/optimization.h"19#include "src/__support/memory_size.h"20#include "src/string/memory_utils/inline_strcmp.h"21#include "src/string/string_utils.h"22#include <stddef.h>23#include <stdint.h>2425namespace LIBC_NAMESPACE_DECL {26namespace internal {2728LIBC_INLINE uint8_t secondary_hash(uint64_t hash) {29// top 7 bits of the hash.30return static_cast<uint8_t>(hash >> 57);31}3233// Probe sequence based on triangular numbers, which is guaranteed (since our34// table size is a power of two) to visit every group of elements exactly once.35//36// A triangular probe has us jump by 1 more group every time. So first we37// jump by 1 group (meaning we just continue our linear scan), then 2 groups38// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on.39//40// If we set sizeof(Group) to be one unit:41// T[k] = sum {1 + 2 + ... + k} = k * (k + 1) / 242// It is provable that T[k] mod 2^m generates a permutation of43// 0, 1, 2, 3, ..., 2^m - 2, 2^m - 144// Detailed proof is available at:45// https://fgiesen.wordpress.com/2015/02/22/triangular-numbers-mod-2n/46struct ProbeSequence {47size_t position;48size_t stride;49size_t entries_mask;5051LIBC_INLINE size_t next() {52position += stride;53position &= entries_mask;54stride += sizeof(Group);55return position;56}57};5859// The number of entries is at least group width: we do not60// need to do the fixup when we set the control bytes.61// The number of entries is at least 8: we don't have to worry62// about special sizes when check the fullness of the table.63LIBC_INLINE size_t capacity_to_entries(size_t cap) {64if (8 >= sizeof(Group) && cap < 8)65return 8;66if (16 >= sizeof(Group) && cap < 15)67return 16;68if (cap < sizeof(Group))69cap = sizeof(Group);70// overflow is always checked in allocate()71return cpp::bit_ceil(cap * 8 / 7);72}7374// The heap memory layout for N buckets HashTable is as follows:75//76// =======================77// | N * Entry |78// ======================= <- align boundary79// | Header |80// ======================= <- align boundary (for fast resize)81// | (N + 1) * Byte |82// =======================83//84// The trailing group part is to make sure we can always load85// a whole group of control bytes.8687struct HashTable {88HashState state;89size_t entries_mask; // number of buckets - 190size_t available_slots; // less than capacity91private:92// How many entries are there in the table.93LIBC_INLINE size_t num_of_entries() const { return entries_mask + 1; }9495// How many entries can we store in the table before resizing.96LIBC_INLINE size_t full_capacity() const { return num_of_entries() / 8 * 7; }9798// The alignment of the whole memory area is the maximum of the alignment99// among the following types:100// - HashTable101// - ENTRY102// - Group103LIBC_INLINE constexpr static size_t table_alignment() {104size_t left_align = alignof(HashTable) > alignof(ENTRY) ? alignof(HashTable)105: alignof(ENTRY);106return left_align > alignof(Group) ? left_align : alignof(Group);107}108109LIBC_INLINE bool is_full() const { return available_slots == 0; }110111LIBC_INLINE size_t offset_from_entries() const {112size_t entries_size = num_of_entries() * sizeof(ENTRY);113return entries_size +114SafeMemSize::offset_to(entries_size, table_alignment());115}116117LIBC_INLINE constexpr static size_t offset_to_groups() {118size_t header_size = sizeof(HashTable);119return header_size + SafeMemSize::offset_to(header_size, table_alignment());120}121122LIBC_INLINE ENTRY &entry(size_t i) {123return reinterpret_cast<ENTRY *>(this)[-i - 1];124}125126LIBC_INLINE const ENTRY &entry(size_t i) const {127return reinterpret_cast<const ENTRY *>(this)[-i - 1];128}129130LIBC_INLINE uint8_t &control(size_t i) {131uint8_t *ptr = reinterpret_cast<uint8_t *>(this) + offset_to_groups();132return ptr[i];133}134135LIBC_INLINE const uint8_t &control(size_t i) const {136const uint8_t *ptr =137reinterpret_cast<const uint8_t *>(this) + offset_to_groups();138return ptr[i];139}140141// We duplicate a group of control bytes to the end. Thus, it is possible that142// we need to set two control bytes at the same time.143LIBC_INLINE void set_ctrl(size_t index, uint8_t value) {144size_t index2 = ((index - sizeof(Group)) & entries_mask) + sizeof(Group);145control(index) = value;146control(index2) = value;147}148149LIBC_INLINE size_t find(const char *key, uint64_t primary) {150uint8_t secondary = secondary_hash(primary);151ProbeSequence sequence{static_cast<size_t>(primary), 0, entries_mask};152while (true) {153size_t pos = sequence.next();154Group ctrls = Group::load(&control(pos));155IteratableBitMask masks = ctrls.match_byte(secondary);156for (size_t i : masks) {157size_t index = (pos + i) & entries_mask;158ENTRY &entry = this->entry(index);159auto comp = [](char l, char r) -> int { return l - r; };160if (LIBC_LIKELY(entry.key != nullptr &&161inline_strcmp(entry.key, key, comp) == 0))162return index;163}164BitMask available = ctrls.mask_available();165// Since there is no deletion, the first time we find an available slot166// it is also ready to be used as an insertion point. Therefore, we also167// return the first available slot we find. If such entry is empty, the168// key will be nullptr.169if (LIBC_LIKELY(available.any_bit_set())) {170size_t index =171(pos + available.lowest_set_bit_nonzero()) & entries_mask;172return index;173}174}175}176177LIBC_INLINE uint64_t oneshot_hash(const char *key) const {178LIBC_NAMESPACE::internal::HashState hasher = state;179hasher.update(key, internal::string_length(key));180return hasher.finish();181}182183// A fast insertion routine without checking if a key already exists.184// Nor does the routine check if the table is full.185// This is only to be used in grow() where we insert all existing entries186// into a new table. Hence, the requirements are naturally satisfied.187LIBC_INLINE ENTRY *unsafe_insert(ENTRY item) {188uint64_t primary = oneshot_hash(item.key);189uint8_t secondary = secondary_hash(primary);190ProbeSequence sequence{static_cast<size_t>(primary), 0, entries_mask};191while (true) {192size_t pos = sequence.next();193Group ctrls = Group::load(&control(pos));194BitMask available = ctrls.mask_available();195if (available.any_bit_set()) {196size_t index =197(pos + available.lowest_set_bit_nonzero()) & entries_mask;198set_ctrl(index, secondary);199entry(index).key = item.key;200entry(index).data = item.data;201available_slots--;202return &entry(index);203}204}205}206207LIBC_INLINE HashTable *grow() const {208size_t hint = full_capacity() + 1;209HashState state = this->state;210// migrate to a new random state211state.update(&hint, sizeof(hint));212HashTable *new_table = allocate(hint, state.finish());213// It is safe to call unsafe_insert() because we know that:214// - the new table has enough capacity to hold all the entries215// - there is no duplicate key in the old table216if (new_table != nullptr)217for (ENTRY e : *this)218new_table->unsafe_insert(e);219return new_table;220}221222LIBC_INLINE static ENTRY *insert(HashTable *&table, ENTRY item,223uint64_t primary) {224auto index = table->find(item.key, primary);225auto slot = &table->entry(index);226// SVr4 and POSIX.1-2001 specify that action is significant only for227// unsuccessful searches, so that an ENTER should not do anything228// for a successful search.229if (slot->key != nullptr)230return slot;231232// if table of full, we try to grow the table233if (table->is_full()) {234HashTable *new_table = table->grow();235// allocation failed, return nullptr to indicate failure236if (new_table == nullptr)237return nullptr;238// resized sccuessfully: clean up the old table and use the new one239deallocate(table);240table = new_table;241// it is still valid to use the fastpath insertion.242return table->unsafe_insert(item);243}244245table->set_ctrl(index, secondary_hash(primary));246slot->key = item.key;247slot->data = item.data;248table->available_slots--;249return slot;250}251252public:253LIBC_INLINE static void deallocate(HashTable *table) {254if (table) {255void *ptr =256reinterpret_cast<uint8_t *>(table) - table->offset_from_entries();257operator delete(ptr, std::align_val_t{table_alignment()});258}259}260261LIBC_INLINE static HashTable *allocate(size_t capacity, uint64_t randomness) {262// check if capacity_to_entries overflows MAX_MEM_SIZE263if (capacity > size_t{1} << (8 * sizeof(size_t) - 1 - 3))264return nullptr;265SafeMemSize entries{capacity_to_entries(capacity)};266SafeMemSize entries_size = entries * SafeMemSize{sizeof(ENTRY)};267SafeMemSize align_boundary = entries_size.align_up(table_alignment());268SafeMemSize ctrl_sizes = entries + SafeMemSize{sizeof(Group)};269SafeMemSize header_size{offset_to_groups()};270SafeMemSize total_size =271(align_boundary + header_size + ctrl_sizes).align_up(table_alignment());272if (!total_size.valid())273return nullptr;274AllocChecker ac;275276void *mem = operator new(total_size, std::align_val_t{table_alignment()},277ac);278279HashTable *table = reinterpret_cast<HashTable *>(280static_cast<uint8_t *>(mem) + align_boundary);281if (ac) {282table->entries_mask = entries - 1u;283table->available_slots = entries / 8 * 7;284table->state = HashState{randomness};285__builtin_memset(&table->control(0), 0x80, ctrl_sizes);286__builtin_memset(mem, 0, table->offset_from_entries());287}288return table;289}290291struct FullTableIterator {292size_t current_offset;293size_t remaining;294IteratableBitMask current_mask;295const HashTable &table;296297// It is fine to use remaining to represent the iterator:298// - this comparison only happens with the same table299// - hashtable will not be mutated during the iteration300LIBC_INLINE bool operator==(const FullTableIterator &other) const {301return remaining == other.remaining;302}303LIBC_INLINE bool operator!=(const FullTableIterator &other) const {304return remaining != other.remaining;305}306307LIBC_INLINE FullTableIterator &operator++() {308this->ensure_valid_group();309current_mask.remove_lowest_bit();310remaining--;311return *this;312}313LIBC_INLINE const ENTRY &operator*() {314this->ensure_valid_group();315return table.entry(316(current_offset + current_mask.lowest_set_bit_nonzero()) &317table.entries_mask);318}319320private:321LIBC_INLINE void ensure_valid_group() {322while (!current_mask.any_bit_set()) {323current_offset += sizeof(Group);324// It is ensured that the load will only happen at aligned boundaries.325current_mask =326Group::load_aligned(&table.control(current_offset)).occupied();327}328}329};330331using value_type = ENTRY;332using iterator = FullTableIterator;333iterator begin() const {334return {0, full_capacity() - available_slots,335Group::load_aligned(&control(0)).occupied(), *this};336}337iterator end() const { return {0, 0, {BitMask{0}}, *this}; }338339LIBC_INLINE ENTRY *find(const char *key) {340uint64_t primary = oneshot_hash(key);341ENTRY &entry = this->entry(find(key, primary));342if (entry.key == nullptr)343return nullptr;344return &entry;345}346347LIBC_INLINE static ENTRY *insert(HashTable *&table, ENTRY item) {348uint64_t primary = table->oneshot_hash(item.key);349return insert(table, item, primary);350}351};352} // namespace internal353} // namespace LIBC_NAMESPACE_DECL354355#endif // LLVM_LIBC_SRC___SUPPORT_HASHTABLE_TABLE_H356357358