1 //===--- OnDiskHashTable.h - On-Disk Hash Table Implementation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines facilities for reading and writing on-disk hash tables.
13 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_ONDISKHASHTABLE_H
15 #define LLVM_SUPPORT_ONDISKHASHTABLE_H
17 #include "llvm/Support/AlignOf.h"
18 #include "llvm/Support/Allocator.h"
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/Support/EndianStream.h"
21 #include "llvm/Support/Host.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/raw_ostream.h"
29 /// \brief Generates an on disk hash table.
31 /// This needs an \c Info that handles storing values into the hash table's
32 /// payload and computes the hash for a given key. This should provide the
33 /// following interface:
36 /// class ExampleInfo {
38 /// typedef ExampleKey key_type; // Must be copy constructible
39 /// typedef ExampleKey &key_type_ref;
40 /// typedef ExampleData data_type; // Must be copy constructible
41 /// typedef ExampleData &data_type_ref;
42 /// typedef uint32_t hash_value_type; // The type the hash function returns.
43 /// typedef uint32_t offset_type; // The type for offsets into the table.
45 /// /// Calculate the hash for Key
46 /// static hash_value_type ComputeHash(key_type_ref Key);
47 /// /// Return the lengths, in bytes, of the given Key/Data pair.
48 /// static std::pair<offset_type, offset_type>
49 /// EmitKeyDataLength(raw_ostream &Out, key_type_ref Key, data_type_ref Data);
50 /// /// Write Key to Out. KeyLen is the length from EmitKeyDataLength.
51 /// static void EmitKey(raw_ostream &Out, key_type_ref Key,
52 /// offset_type KeyLen);
53 /// /// Write Data to Out. DataLen is the length from EmitKeyDataLength.
54 /// static void EmitData(raw_ostream &Out, key_type_ref Key,
55 /// data_type_ref Data, offset_type DataLen);
56 /// /// Determine if two keys are equal. Optional, only needed by contains.
57 /// static bool EqualKey(key_type_ref Key1, key_type_ref Key2);
60 template <typename Info> class OnDiskChainedHashTableGenerator {
61 /// \brief A single item in the hash table.
64 typename Info::key_type Key;
65 typename Info::data_type Data;
67 const typename Info::hash_value_type Hash;
69 Item(typename Info::key_type_ref Key, typename Info::data_type_ref Data,
71 : Key(Key), Data(Data), Next(nullptr), Hash(InfoObj.ComputeHash(Key)) {}
74 typedef typename Info::offset_type offset_type;
75 offset_type NumBuckets;
76 offset_type NumEntries;
77 llvm::SpecificBumpPtrAllocator<Item> BA;
79 /// \brief A linked list of values in a particular hash bucket.
89 /// \brief Insert an item into the appropriate hash bucket.
90 void insert(Bucket *Buckets, size_t Size, Item *E) {
91 Bucket &B = Buckets[E->Hash & (Size - 1)];
97 /// \brief Resize the hash table, moving the old entries into the new buckets.
98 void resize(size_t NewSize) {
99 Bucket *NewBuckets = (Bucket *)std::calloc(NewSize, sizeof(Bucket));
100 // Populate NewBuckets with the old entries.
101 for (size_t I = 0; I < NumBuckets; ++I)
102 for (Item *E = Buckets[I].Head; E;) {
105 insert(NewBuckets, NewSize, E);
110 NumBuckets = NewSize;
111 Buckets = NewBuckets;
115 /// \brief Insert an entry into the table.
116 void insert(typename Info::key_type_ref Key,
117 typename Info::data_type_ref Data) {
119 insert(Key, Data, InfoObj);
122 /// \brief Insert an entry into the table.
124 /// Uses the provided Info instead of a stack allocated one.
125 void insert(typename Info::key_type_ref Key,
126 typename Info::data_type_ref Data, Info &InfoObj) {
128 if (4 * NumEntries >= 3 * NumBuckets)
129 resize(NumBuckets * 2);
130 insert(Buckets, NumBuckets, new (BA.Allocate()) Item(Key, Data, InfoObj));
133 /// \brief Determine whether an entry has been inserted.
134 bool contains(typename Info::key_type_ref Key, Info &InfoObj) {
135 unsigned Hash = InfoObj.ComputeHash(Key);
136 for (Item *I = Buckets[Hash & (NumBuckets - 1)].Head; I; I = I->Next)
137 if (I->Hash == Hash && InfoObj.EqualKey(I->Key, Key))
142 /// \brief Emit the table to Out, which must not be at offset 0.
143 offset_type Emit(raw_ostream &Out) {
145 return Emit(Out, InfoObj);
148 /// \brief Emit the table to Out, which must not be at offset 0.
150 /// Uses the provided Info instead of a stack allocated one.
151 offset_type Emit(raw_ostream &Out, Info &InfoObj) {
152 using namespace llvm::support;
153 endian::Writer<little> LE(Out);
155 // Emit the payload of the table.
156 for (offset_type I = 0; I < NumBuckets; ++I) {
157 Bucket &B = Buckets[I];
161 // Store the offset for the data of this bucket.
163 assert(B.Off && "Cannot write a bucket at offset 0. Please add padding.");
165 // Write out the number of items in the bucket.
166 LE.write<uint16_t>(B.Length);
167 assert(B.Length != 0 && "Bucket has a head but zero length?");
169 // Write out the entries in the bucket.
170 for (Item *I = B.Head; I; I = I->Next) {
171 LE.write<typename Info::hash_value_type>(I->Hash);
172 const std::pair<offset_type, offset_type> &Len =
173 InfoObj.EmitKeyDataLength(Out, I->Key, I->Data);
174 InfoObj.EmitKey(Out, I->Key, Len.first);
175 InfoObj.EmitData(Out, I->Key, I->Data, Len.second);
179 // Pad with zeros so that we can start the hashtable at an aligned address.
180 offset_type TableOff = Out.tell();
181 uint64_t N = llvm::OffsetToAlignment(TableOff, alignOf<offset_type>());
184 LE.write<uint8_t>(0);
186 // Emit the hashtable itself.
187 LE.write<offset_type>(NumBuckets);
188 LE.write<offset_type>(NumEntries);
189 for (offset_type I = 0; I < NumBuckets; ++I)
190 LE.write<offset_type>(Buckets[I].Off);
195 OnDiskChainedHashTableGenerator() {
198 // Note that we do not need to run the constructors of the individual
199 // Bucket objects since 'calloc' returns bytes that are all 0.
200 Buckets = (Bucket *)std::calloc(NumBuckets, sizeof(Bucket));
203 ~OnDiskChainedHashTableGenerator() { std::free(Buckets); }
206 /// \brief Provides lookup on an on disk hash table.
208 /// This needs an \c Info that handles reading values from the hash table's
209 /// payload and computes the hash for a given key. This should provide the
210 /// following interface:
213 /// class ExampleLookupInfo {
215 /// typedef ExampleData data_type;
216 /// typedef ExampleInternalKey internal_key_type; // The stored key type.
217 /// typedef ExampleKey external_key_type; // The type to pass to find().
218 /// typedef uint32_t hash_value_type; // The type the hash function returns.
219 /// typedef uint32_t offset_type; // The type for offsets into the table.
221 /// /// Compare two keys for equality.
222 /// static bool EqualKey(internal_key_type &Key1, internal_key_type &Key2);
223 /// /// Calculate the hash for the given key.
224 /// static hash_value_type ComputeHash(internal_key_type &IKey);
225 /// /// Translate from the semantic type of a key in the hash table to the
226 /// /// type that is actually stored and used for hashing and comparisons.
227 /// /// The internal and external types are often the same, in which case this
228 /// /// can simply return the passed in value.
229 /// static const internal_key_type &GetInternalKey(external_key_type &EKey);
230 /// /// Read the key and data length from Buffer, leaving it pointing at the
231 /// /// following byte.
232 /// static std::pair<offset_type, offset_type>
233 /// ReadKeyDataLength(const unsigned char *&Buffer);
234 /// /// Read the key from Buffer, given the KeyLen as reported from
235 /// /// ReadKeyDataLength.
236 /// const internal_key_type &ReadKey(const unsigned char *Buffer,
237 /// offset_type KeyLen);
238 /// /// Read the data for Key from Buffer, given the DataLen as reported from
239 /// /// ReadKeyDataLength.
240 /// data_type ReadData(StringRef Key, const unsigned char *Buffer,
241 /// offset_type DataLen);
244 template <typename Info> class OnDiskChainedHashTable {
245 const typename Info::offset_type NumBuckets;
246 const typename Info::offset_type NumEntries;
247 const unsigned char *const Buckets;
248 const unsigned char *const Base;
252 typedef typename Info::internal_key_type internal_key_type;
253 typedef typename Info::external_key_type external_key_type;
254 typedef typename Info::data_type data_type;
255 typedef typename Info::hash_value_type hash_value_type;
256 typedef typename Info::offset_type offset_type;
258 OnDiskChainedHashTable(offset_type NumBuckets, offset_type NumEntries,
259 const unsigned char *Buckets,
260 const unsigned char *Base,
261 const Info &InfoObj = Info())
262 : NumBuckets(NumBuckets), NumEntries(NumEntries), Buckets(Buckets),
263 Base(Base), InfoObj(InfoObj) {
264 assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 &&
265 "'buckets' must have a 4-byte alignment");
268 /// Read the number of buckets and the number of entries from a hash table
269 /// produced by OnDiskHashTableGenerator::Emit, and advance the Buckets
270 /// pointer past them.
271 static std::pair<offset_type, offset_type>
272 readNumBucketsAndEntries(const unsigned char *&Buckets) {
273 assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 &&
274 "buckets should be 4-byte aligned.");
275 using namespace llvm::support;
276 offset_type NumBuckets =
277 endian::readNext<offset_type, little, aligned>(Buckets);
278 offset_type NumEntries =
279 endian::readNext<offset_type, little, aligned>(Buckets);
280 return std::make_pair(NumBuckets, NumEntries);
283 offset_type getNumBuckets() const { return NumBuckets; }
284 offset_type getNumEntries() const { return NumEntries; }
285 const unsigned char *getBase() const { return Base; }
286 const unsigned char *getBuckets() const { return Buckets; }
288 bool isEmpty() const { return NumEntries == 0; }
291 internal_key_type Key;
292 const unsigned char *const Data;
293 const offset_type Len;
297 iterator() : Data(nullptr), Len(0) {}
298 iterator(const internal_key_type K, const unsigned char *D, offset_type L,
300 : Key(K), Data(D), Len(L), InfoObj(InfoObj) {}
302 data_type operator*() const { return InfoObj->ReadData(Key, Data, Len); }
304 const unsigned char *getDataPtr() const { return Data; }
305 offset_type getDataLen() const { return Len; }
307 bool operator==(const iterator &X) const { return X.Data == Data; }
308 bool operator!=(const iterator &X) const { return X.Data != Data; }
311 /// \brief Look up the stored data for a particular key.
312 iterator find(const external_key_type &EKey, Info *InfoPtr = nullptr) {
313 const internal_key_type &IKey = InfoObj.GetInternalKey(EKey);
314 hash_value_type KeyHash = InfoObj.ComputeHash(IKey);
315 return find_hashed(IKey, KeyHash, InfoPtr);
318 /// \brief Look up the stored data for a particular key with a known hash.
319 iterator find_hashed(const internal_key_type &IKey, hash_value_type KeyHash,
320 Info *InfoPtr = nullptr) {
321 using namespace llvm::support;
326 // Each bucket is just an offset into the hash table file.
327 offset_type Idx = KeyHash & (NumBuckets - 1);
328 const unsigned char *Bucket = Buckets + sizeof(offset_type) * Idx;
330 offset_type Offset = endian::readNext<offset_type, little, aligned>(Bucket);
332 return iterator(); // Empty bucket.
333 const unsigned char *Items = Base + Offset;
335 // 'Items' starts with a 16-bit unsigned integer representing the
336 // number of items in this bucket.
337 unsigned Len = endian::readNext<uint16_t, little, unaligned>(Items);
339 for (unsigned i = 0; i < Len; ++i) {
341 hash_value_type ItemHash =
342 endian::readNext<hash_value_type, little, unaligned>(Items);
344 // Determine the length of the key and the data.
345 const std::pair<offset_type, offset_type> &L =
346 Info::ReadKeyDataLength(Items);
347 offset_type ItemLen = L.first + L.second;
349 // Compare the hashes. If they are not the same, skip the entry entirely.
350 if (ItemHash != KeyHash) {
356 const internal_key_type &X =
357 InfoPtr->ReadKey((const unsigned char *const)Items, L.first);
359 // If the key doesn't match just skip reading the value.
360 if (!InfoPtr->EqualKey(X, IKey)) {
366 return iterator(X, Items + L.first, L.second, InfoPtr);
372 iterator end() const { return iterator(); }
374 Info &getInfoObj() { return InfoObj; }
376 /// \brief Create the hash table.
378 /// \param Buckets is the beginning of the hash table itself, which follows
379 /// the payload of entire structure. This is the value returned by
380 /// OnDiskHashTableGenerator::Emit.
382 /// \param Base is the point from which all offsets into the structure are
383 /// based. This is offset 0 in the stream that was used when Emitting the
385 static OnDiskChainedHashTable *Create(const unsigned char *Buckets,
386 const unsigned char *const Base,
387 const Info &InfoObj = Info()) {
388 assert(Buckets > Base);
389 auto NumBucketsAndEntries = readNumBucketsAndEntries(Buckets);
390 return new OnDiskChainedHashTable<Info>(NumBucketsAndEntries.first,
391 NumBucketsAndEntries.second,
392 Buckets, Base, InfoObj);
396 /// \brief Provides lookup and iteration over an on disk hash table.
398 /// \copydetails llvm::OnDiskChainedHashTable
399 template <typename Info>
400 class OnDiskIterableChainedHashTable : public OnDiskChainedHashTable<Info> {
401 const unsigned char *Payload;
404 typedef OnDiskChainedHashTable<Info> base_type;
405 typedef typename base_type::internal_key_type internal_key_type;
406 typedef typename base_type::external_key_type external_key_type;
407 typedef typename base_type::data_type data_type;
408 typedef typename base_type::hash_value_type hash_value_type;
409 typedef typename base_type::offset_type offset_type;
412 /// \brief Iterates over all of the keys in the table.
413 class iterator_base {
414 const unsigned char *Ptr;
415 offset_type NumItemsInBucketLeft;
416 offset_type NumEntriesLeft;
419 typedef external_key_type value_type;
421 iterator_base(const unsigned char *const Ptr, offset_type NumEntries)
422 : Ptr(Ptr), NumItemsInBucketLeft(0), NumEntriesLeft(NumEntries) {}
424 : Ptr(nullptr), NumItemsInBucketLeft(0), NumEntriesLeft(0) {}
426 friend bool operator==(const iterator_base &X, const iterator_base &Y) {
427 return X.NumEntriesLeft == Y.NumEntriesLeft;
429 friend bool operator!=(const iterator_base &X, const iterator_base &Y) {
430 return X.NumEntriesLeft != Y.NumEntriesLeft;
433 /// Move to the next item.
435 using namespace llvm::support;
436 if (!NumItemsInBucketLeft) {
437 // 'Items' starts with a 16-bit unsigned integer representing the
438 // number of items in this bucket.
439 NumItemsInBucketLeft =
440 endian::readNext<uint16_t, little, unaligned>(Ptr);
442 Ptr += sizeof(hash_value_type); // Skip the hash.
443 // Determine the length of the key and the data.
444 const std::pair<offset_type, offset_type> &L =
445 Info::ReadKeyDataLength(Ptr);
446 Ptr += L.first + L.second;
447 assert(NumItemsInBucketLeft);
448 --NumItemsInBucketLeft;
449 assert(NumEntriesLeft);
453 /// Get the start of the item as written by the trait (after the hash and
454 /// immediately before the key and value length).
455 const unsigned char *getItem() const {
456 return Ptr + (NumItemsInBucketLeft ? 0 : 2) + sizeof(hash_value_type);
461 OnDiskIterableChainedHashTable(offset_type NumBuckets, offset_type NumEntries,
462 const unsigned char *Buckets,
463 const unsigned char *Payload,
464 const unsigned char *Base,
465 const Info &InfoObj = Info())
466 : base_type(NumBuckets, NumEntries, Buckets, Base, InfoObj),
469 /// \brief Iterates over all of the keys in the table.
470 class key_iterator : public iterator_base {
474 typedef external_key_type value_type;
476 key_iterator(const unsigned char *const Ptr, offset_type NumEntries,
478 : iterator_base(Ptr, NumEntries), InfoObj(InfoObj) {}
479 key_iterator() : iterator_base(), InfoObj() {}
481 key_iterator &operator++() {
485 key_iterator operator++(int) { // Postincrement
486 key_iterator tmp = *this;
491 internal_key_type getInternalKey() const {
492 auto *LocalPtr = this->getItem();
494 // Determine the length of the key and the data.
495 auto L = Info::ReadKeyDataLength(LocalPtr);
498 return InfoObj->ReadKey(LocalPtr, L.first);
501 value_type operator*() const {
502 return InfoObj->GetExternalKey(getInternalKey());
506 key_iterator key_begin() {
507 return key_iterator(Payload, this->getNumEntries(), &this->getInfoObj());
509 key_iterator key_end() { return key_iterator(); }
511 iterator_range<key_iterator> keys() {
512 return make_range(key_begin(), key_end());
515 /// \brief Iterates over all the entries in the table, returning the data.
516 class data_iterator : public iterator_base {
520 typedef data_type value_type;
522 data_iterator(const unsigned char *const Ptr, offset_type NumEntries,
524 : iterator_base(Ptr, NumEntries), InfoObj(InfoObj) {}
525 data_iterator() : iterator_base(), InfoObj() {}
527 data_iterator &operator++() { // Preincrement
531 data_iterator operator++(int) { // Postincrement
532 data_iterator tmp = *this;
537 value_type operator*() const {
538 auto *LocalPtr = this->getItem();
540 // Determine the length of the key and the data.
541 auto L = Info::ReadKeyDataLength(LocalPtr);
544 const internal_key_type &Key = InfoObj->ReadKey(LocalPtr, L.first);
545 return InfoObj->ReadData(Key, LocalPtr + L.first, L.second);
549 data_iterator data_begin() {
550 return data_iterator(Payload, this->getNumEntries(), &this->getInfoObj());
552 data_iterator data_end() { return data_iterator(); }
554 iterator_range<data_iterator> data() {
555 return make_range(data_begin(), data_end());
558 /// \brief Create the hash table.
560 /// \param Buckets is the beginning of the hash table itself, which follows
561 /// the payload of entire structure. This is the value returned by
562 /// OnDiskHashTableGenerator::Emit.
564 /// \param Payload is the beginning of the data contained in the table. This
565 /// is Base plus any padding or header data that was stored, ie, the offset
566 /// that the stream was at when calling Emit.
568 /// \param Base is the point from which all offsets into the structure are
569 /// based. This is offset 0 in the stream that was used when Emitting the
571 static OnDiskIterableChainedHashTable *
572 Create(const unsigned char *Buckets, const unsigned char *const Payload,
573 const unsigned char *const Base, const Info &InfoObj = Info()) {
574 assert(Buckets > Base);
575 auto NumBucketsAndEntries =
576 OnDiskIterableChainedHashTable<Info>::readNumBucketsAndEntries(Buckets);
577 return new OnDiskIterableChainedHashTable<Info>(
578 NumBucketsAndEntries.first, NumBucketsAndEntries.second,
579 Buckets, Payload, Base, InfoObj);
583 } // end namespace llvm