Path: blob/main/contrib/llvm-project/clang/lib/Serialization/MultiOnDiskHashTable.h
35233 views
//===- MultiOnDiskHashTable.h - Merged set of hash tables -------*- 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//===----------------------------------------------------------------------===//7//8// This file provides a hash table data structure suitable for incremental and9// distributed storage across a set of files.10//11// Multiple hash tables from different files are implicitly merged to improve12// performance, and on reload the merged table will override those from other13// files.14//15//===----------------------------------------------------------------------===//1617#ifndef LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H18#define LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H1920#include "llvm/ADT/DenseMap.h"21#include "llvm/ADT/DenseSet.h"22#include "llvm/ADT/PointerUnion.h"23#include "llvm/ADT/STLExtras.h"24#include "llvm/ADT/SmallVector.h"25#include "llvm/ADT/TinyPtrVector.h"26#include "llvm/ADT/iterator_range.h"27#include "llvm/Support/Endian.h"28#include "llvm/Support/EndianStream.h"29#include "llvm/Support/OnDiskHashTable.h"30#include "llvm/Support/raw_ostream.h"31#include <algorithm>32#include <cstdint>33#include <vector>3435namespace clang {36namespace serialization {3738/// A collection of on-disk hash tables, merged when relevant for performance.39template<typename Info> class MultiOnDiskHashTable {40public:41/// A handle to a file, used when overriding tables.42using file_type = typename Info::file_type;4344/// A pointer to an on-disk representation of the hash table.45using storage_type = const unsigned char *;4647using external_key_type = typename Info::external_key_type;48using internal_key_type = typename Info::internal_key_type;49using data_type = typename Info::data_type;50using data_type_builder = typename Info::data_type_builder;51using hash_value_type = unsigned;5253private:54/// The generator is permitted to read our merged table.55template<typename ReaderInfo, typename WriterInfo>56friend class MultiOnDiskHashTableGenerator;5758/// A hash table stored on disk.59struct OnDiskTable {60using HashTable = llvm::OnDiskIterableChainedHashTable<Info>;6162file_type File;63HashTable Table;6465OnDiskTable(file_type File, unsigned NumBuckets, unsigned NumEntries,66storage_type Buckets, storage_type Payload, storage_type Base,67const Info &InfoObj)68: File(File),69Table(NumBuckets, NumEntries, Buckets, Payload, Base, InfoObj) {}70};7172struct MergedTable {73std::vector<file_type> Files;74llvm::DenseMap<internal_key_type, data_type> Data;75};7677using Table = llvm::PointerUnion<OnDiskTable *, MergedTable *>;78using TableVector = llvm::TinyPtrVector<void *>;7980/// The current set of on-disk and merged tables.81/// We manually store the opaque value of the Table because TinyPtrVector82/// can't cope with holding a PointerUnion directly.83/// There can be at most one MergedTable in this vector, and if present,84/// it is the first table.85TableVector Tables;8687/// Files corresponding to overridden tables that we've not yet88/// discarded.89llvm::TinyPtrVector<file_type> PendingOverrides;9091struct AsOnDiskTable {92using result_type = OnDiskTable *;9394result_type operator()(void *P) const {95return Table::getFromOpaqueValue(P).template get<OnDiskTable *>();96}97};9899using table_iterator =100llvm::mapped_iterator<TableVector::iterator, AsOnDiskTable>;101using table_range = llvm::iterator_range<table_iterator>;102103/// The current set of on-disk tables.104table_range tables() {105auto Begin = Tables.begin(), End = Tables.end();106if (getMergedTable())107++Begin;108return llvm::make_range(llvm::map_iterator(Begin, AsOnDiskTable()),109llvm::map_iterator(End, AsOnDiskTable()));110}111112MergedTable *getMergedTable() const {113// If we already have a merged table, it's the first one.114return Tables.empty() ? nullptr : Table::getFromOpaqueValue(*Tables.begin())115.template dyn_cast<MergedTable*>();116}117118/// Delete all our current on-disk tables.119void clear() {120for (auto *T : tables())121delete T;122if (auto *M = getMergedTable())123delete M;124Tables.clear();125}126127void removeOverriddenTables() {128llvm::DenseSet<file_type> Files;129Files.insert(PendingOverrides.begin(), PendingOverrides.end());130// Explicitly capture Files to work around an MSVC 2015 rejects-valid bug.131auto ShouldRemove = [&Files](void *T) -> bool {132auto *ODT = Table::getFromOpaqueValue(T).template get<OnDiskTable *>();133bool Remove = Files.count(ODT->File);134if (Remove)135delete ODT;136return Remove;137};138Tables.erase(std::remove_if(tables().begin().getCurrent(), Tables.end(),139ShouldRemove),140Tables.end());141PendingOverrides.clear();142}143144void condense() {145MergedTable *Merged = getMergedTable();146if (!Merged)147Merged = new MergedTable;148149// Read in all the tables and merge them together.150// FIXME: Be smarter about which tables we merge.151for (auto *ODT : tables()) {152auto &HT = ODT->Table;153Info &InfoObj = HT.getInfoObj();154155for (auto I = HT.data_begin(), E = HT.data_end(); I != E; ++I) {156auto *LocalPtr = I.getItem();157158// FIXME: Don't rely on the OnDiskHashTable format here.159auto L = InfoObj.ReadKeyDataLength(LocalPtr);160const internal_key_type &Key = InfoObj.ReadKey(LocalPtr, L.first);161data_type_builder ValueBuilder(Merged->Data[Key]);162InfoObj.ReadDataInto(Key, LocalPtr + L.first, L.second,163ValueBuilder);164}165166Merged->Files.push_back(ODT->File);167delete ODT;168}169170Tables.clear();171Tables.push_back(Table(Merged).getOpaqueValue());172}173174public:175MultiOnDiskHashTable() = default;176177MultiOnDiskHashTable(MultiOnDiskHashTable &&O)178: Tables(std::move(O.Tables)),179PendingOverrides(std::move(O.PendingOverrides)) {180O.Tables.clear();181}182183MultiOnDiskHashTable &operator=(MultiOnDiskHashTable &&O) {184if (&O == this)185return *this;186clear();187Tables = std::move(O.Tables);188O.Tables.clear();189PendingOverrides = std::move(O.PendingOverrides);190return *this;191}192193~MultiOnDiskHashTable() { clear(); }194195/// Add the table \p Data loaded from file \p File.196void add(file_type File, storage_type Data, Info InfoObj = Info()) {197using namespace llvm::support;198199storage_type Ptr = Data;200201uint32_t BucketOffset =202endian::readNext<uint32_t, llvm::endianness::little>(Ptr);203204// Read the list of overridden files.205uint32_t NumFiles =206endian::readNext<uint32_t, llvm::endianness::little>(Ptr);207// FIXME: Add a reserve() to TinyPtrVector so that we don't need to make208// an additional copy.209llvm::SmallVector<file_type, 16> OverriddenFiles;210OverriddenFiles.reserve(NumFiles);211for (/**/; NumFiles != 0; --NumFiles)212OverriddenFiles.push_back(InfoObj.ReadFileRef(Ptr));213PendingOverrides.insert(PendingOverrides.end(), OverriddenFiles.begin(),214OverriddenFiles.end());215216// Read the OnDiskChainedHashTable header.217storage_type Buckets = Data + BucketOffset;218auto NumBucketsAndEntries =219OnDiskTable::HashTable::readNumBucketsAndEntries(Buckets);220221// Register the table.222Table NewTable = new OnDiskTable(File, NumBucketsAndEntries.first,223NumBucketsAndEntries.second,224Buckets, Ptr, Data, std::move(InfoObj));225Tables.push_back(NewTable.getOpaqueValue());226}227228/// Find and read the lookup results for \p EKey.229data_type find(const external_key_type &EKey) {230data_type Result;231232if (!PendingOverrides.empty())233removeOverriddenTables();234235if (Tables.size() > static_cast<unsigned>(Info::MaxTables))236condense();237238internal_key_type Key = Info::GetInternalKey(EKey);239auto KeyHash = Info::ComputeHash(Key);240241if (MergedTable *M = getMergedTable()) {242auto It = M->Data.find(Key);243if (It != M->Data.end())244Result = It->second;245}246247data_type_builder ResultBuilder(Result);248249for (auto *ODT : tables()) {250auto &HT = ODT->Table;251auto It = HT.find_hashed(Key, KeyHash);252if (It != HT.end())253HT.getInfoObj().ReadDataInto(Key, It.getDataPtr(), It.getDataLen(),254ResultBuilder);255}256257return Result;258}259260/// Read all the lookup results into a single value. This only makes261/// sense if merging values across keys is meaningful.262data_type findAll() {263data_type Result;264data_type_builder ResultBuilder(Result);265266if (!PendingOverrides.empty())267removeOverriddenTables();268269if (MergedTable *M = getMergedTable()) {270for (auto &KV : M->Data)271Info::MergeDataInto(KV.second, ResultBuilder);272}273274for (auto *ODT : tables()) {275auto &HT = ODT->Table;276Info &InfoObj = HT.getInfoObj();277for (auto I = HT.data_begin(), E = HT.data_end(); I != E; ++I) {278auto *LocalPtr = I.getItem();279280// FIXME: Don't rely on the OnDiskHashTable format here.281auto L = InfoObj.ReadKeyDataLength(LocalPtr);282const internal_key_type &Key = InfoObj.ReadKey(LocalPtr, L.first);283InfoObj.ReadDataInto(Key, LocalPtr + L.first, L.second, ResultBuilder);284}285}286287return Result;288}289};290291/// Writer for the on-disk hash table.292template<typename ReaderInfo, typename WriterInfo>293class MultiOnDiskHashTableGenerator {294using BaseTable = MultiOnDiskHashTable<ReaderInfo>;295using Generator = llvm::OnDiskChainedHashTableGenerator<WriterInfo>;296297Generator Gen;298299public:300MultiOnDiskHashTableGenerator() : Gen() {}301302void insert(typename WriterInfo::key_type_ref Key,303typename WriterInfo::data_type_ref Data, WriterInfo &Info) {304Gen.insert(Key, Data, Info);305}306307void emit(llvm::SmallVectorImpl<char> &Out, WriterInfo &Info,308const BaseTable *Base) {309using namespace llvm::support;310311llvm::raw_svector_ostream OutStream(Out);312313// Write our header information.314{315endian::Writer Writer(OutStream, llvm::endianness::little);316317// Reserve four bytes for the bucket offset.318Writer.write<uint32_t>(0);319320if (auto *Merged = Base ? Base->getMergedTable() : nullptr) {321// Write list of overridden files.322Writer.write<uint32_t>(Merged->Files.size());323for (const auto &F : Merged->Files)324Info.EmitFileRef(OutStream, F);325326// Add all merged entries from Base to the generator.327for (auto &KV : Merged->Data) {328if (!Gen.contains(KV.first, Info))329Gen.insert(KV.first, Info.ImportData(KV.second), Info);330}331} else {332Writer.write<uint32_t>(0);333}334}335336// Write the table itself.337uint32_t BucketOffset = Gen.Emit(OutStream, Info);338339// Replace the first four bytes with the bucket offset.340endian::write32le(Out.data(), BucketOffset);341}342};343344} // namespace serialization345} // namespace clang346347#endif // LLVM_CLANG_LIB_SERIALIZATION_MULTIONDISKHASHTABLE_H348349350