Skip to content

Commit 2936a2c

Browse files
[CAS] Add OnDiskTrieRawHashMap (llvm#114100)
Add OnDiskTrieRawHashMap. This is a on-disk persistent hash map that uses a Trie data structure that is similar to TrieRawHashMap. OnDiskTrieRawHashMap is thread safe and process safe. It is mostly lock free, except it internally coordinates cross process creation and closing using file lock.
1 parent 38a4c9c commit 2936a2c

File tree

8 files changed

+1952
-4
lines changed

8 files changed

+1952
-4
lines changed

llvm/include/llvm/CAS/FileOffset.h

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
//
9+
/// \file
10+
/// This file declares interface for FileOffset that represent stored data at an
11+
/// offset from the beginning of a file.
12+
///
13+
//===----------------------------------------------------------------------===//
14+
15+
#ifndef LLVM_CAS_FILEOFFSET_H
16+
#define LLVM_CAS_FILEOFFSET_H
17+
18+
#include <cstdlib>
19+
20+
namespace llvm::cas {
21+
22+
/// FileOffset is a wrapper around `uint64_t` to represent the offset of data
23+
/// from the beginning of the file.
24+
class FileOffset {
25+
public:
26+
uint64_t get() const { return Offset; }
27+
28+
explicit operator bool() const { return Offset; }
29+
30+
FileOffset() = default;
31+
explicit FileOffset(uint64_t Offset) : Offset(Offset) {}
32+
33+
private:
34+
uint64_t Offset = 0;
35+
};
36+
37+
} // namespace llvm::cas
38+
39+
#endif // LLVM_CAS_FILEOFFSET_H
Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
//
9+
/// \file
10+
/// This file declares interface for OnDiskTrieRawHashMap, a thread-safe and
11+
/// (mostly) lock-free hash map stored as trie and backed by persistent files on
12+
/// disk.
13+
///
14+
//===----------------------------------------------------------------------===//
15+
16+
#ifndef LLVM_CAS_ONDISKTRIERAWHASHMAP_H
17+
#define LLVM_CAS_ONDISKTRIERAWHASHMAP_H
18+
19+
#include "llvm/ADT/ArrayRef.h"
20+
#include "llvm/ADT/STLExtras.h"
21+
#include "llvm/ADT/STLFunctionalExtras.h"
22+
#include "llvm/ADT/StringRef.h"
23+
#include "llvm/CAS/FileOffset.h"
24+
#include "llvm/Support/Error.h"
25+
#include <optional>
26+
27+
namespace llvm {
28+
29+
class raw_ostream;
30+
31+
namespace cas {
32+
33+
/// OnDiskTrieRawHashMap is a persistent trie data structure used as hash maps.
34+
/// The keys are fixed length, and are expected to be binary hashes with a
35+
/// normal distribution.
36+
///
37+
/// - Thread-safety is achieved through the use of atomics within a shared
38+
/// memory mapping. Atomic access does not work on networked filesystems.
39+
/// - Filesystem locks are used, but only sparingly:
40+
/// - during initialization, for creating / opening an existing store;
41+
/// - for the lifetime of the instance, a shared/reader lock is held
42+
/// - during destruction, if there are no concurrent readers, to shrink the
43+
/// files to their minimum size.
44+
/// - Path is used as a directory:
45+
/// - "index" stores the root trie and subtries.
46+
/// - "data" stores (most of) the entries, like a bump-ptr-allocator.
47+
/// - Large entries are stored externally in a file named by the key.
48+
/// - Code is system-dependent and binary format itself is not portable. These
49+
/// are not artifacts that can/should be moved between different systems; they
50+
/// are only appropriate for local storage.
51+
class OnDiskTrieRawHashMap {
52+
public:
53+
LLVM_DUMP_METHOD void dump() const;
54+
void
55+
print(raw_ostream &OS,
56+
function_ref<void(ArrayRef<char>)> PrintRecordData = nullptr) const;
57+
58+
public:
59+
/// Const value proxy to access the records stored in TrieRawHashMap.
60+
struct ConstValueProxy {
61+
ConstValueProxy() = default;
62+
ConstValueProxy(ArrayRef<uint8_t> Hash, ArrayRef<char> Data)
63+
: Hash(Hash), Data(Data) {}
64+
ConstValueProxy(ArrayRef<uint8_t> Hash, StringRef Data)
65+
: Hash(Hash), Data(Data.begin(), Data.size()) {}
66+
67+
ArrayRef<uint8_t> Hash;
68+
ArrayRef<char> Data;
69+
};
70+
71+
/// Value proxy to access the records stored in TrieRawHashMap.
72+
struct ValueProxy {
73+
operator ConstValueProxy() const { return ConstValueProxy(Hash, Data); }
74+
75+
ValueProxy() = default;
76+
ValueProxy(ArrayRef<uint8_t> Hash, MutableArrayRef<char> Data)
77+
: Hash(Hash), Data(Data) {}
78+
79+
ArrayRef<uint8_t> Hash;
80+
MutableArrayRef<char> Data;
81+
};
82+
83+
/// Validate the trie data structure.
84+
///
85+
/// Callback receives the file offset to the data entry and the data stored.
86+
Error validate(
87+
function_ref<Error(FileOffset, ConstValueProxy)> RecordVerifier) const;
88+
89+
/// Check the valid range of file offset for OnDiskTrieRawHashMap.
90+
static bool validOffset(FileOffset Offset) {
91+
return Offset.get() < (1LL << 48);
92+
}
93+
94+
public:
95+
/// Template class to implement a `pointer` type into the trie data structure.
96+
///
97+
/// It provides pointer-like operation, e.g., dereference to get underlying
98+
/// data. It also reserves the top 16 bits of the pointer value, which can be
99+
/// used to pack additional information if needed.
100+
template <class ProxyT> class PointerImpl {
101+
public:
102+
FileOffset getOffset() const {
103+
return FileOffset(OffsetLow32 | (uint64_t)OffsetHigh16 << 32);
104+
}
105+
106+
explicit operator bool() const { return IsValue; }
107+
108+
const ProxyT &operator*() const {
109+
assert(IsValue);
110+
return Value;
111+
}
112+
const ProxyT *operator->() const {
113+
assert(IsValue);
114+
return &Value;
115+
}
116+
117+
PointerImpl() = default;
118+
119+
protected:
120+
PointerImpl(ProxyT Value, FileOffset Offset, bool IsValue = true)
121+
: Value(Value), OffsetLow32((uint64_t)Offset.get()),
122+
OffsetHigh16((uint64_t)Offset.get() >> 32), IsValue(IsValue) {
123+
if (IsValue)
124+
assert(validOffset(Offset));
125+
}
126+
127+
ProxyT Value;
128+
uint32_t OffsetLow32 = 0;
129+
uint16_t OffsetHigh16 = 0;
130+
131+
// True if points to a value (not a "nullptr"). Use an extra field because
132+
// 0 can be a valid offset.
133+
bool IsValue = false;
134+
};
135+
136+
class pointer;
137+
class const_pointer : public PointerImpl<ConstValueProxy> {
138+
public:
139+
const_pointer() = default;
140+
141+
private:
142+
friend class pointer;
143+
friend class OnDiskTrieRawHashMap;
144+
using const_pointer::PointerImpl::PointerImpl;
145+
};
146+
147+
class pointer : public PointerImpl<ValueProxy> {
148+
public:
149+
operator const_pointer() const {
150+
return const_pointer(Value, getOffset(), IsValue);
151+
}
152+
153+
pointer() = default;
154+
155+
private:
156+
friend class OnDiskTrieRawHashMap;
157+
using pointer::PointerImpl::PointerImpl;
158+
};
159+
160+
/// Find the value from hash.
161+
///
162+
/// \returns pointer to the value if exists, otherwise returns a non-value
163+
/// pointer that evaluates to `false` when convert to boolean.
164+
const_pointer find(ArrayRef<uint8_t> Hash) const;
165+
166+
/// Helper function to recover a pointer into the trie from file offset.
167+
Expected<const_pointer> recoverFromFileOffset(FileOffset Offset) const;
168+
169+
using LazyInsertOnConstructCB =
170+
function_ref<void(FileOffset TentativeOffset, ValueProxy TentativeValue)>;
171+
using LazyInsertOnLeakCB =
172+
function_ref<void(FileOffset TentativeOffset, ValueProxy TentativeValue,
173+
FileOffset FinalOffset, ValueProxy FinalValue)>;
174+
175+
/// Insert lazily.
176+
///
177+
/// \p OnConstruct is called when ready to insert a value, after allocating
178+
/// space for the data. It is called at most once.
179+
///
180+
/// \p OnLeak is called only if \p OnConstruct has been called and a race
181+
/// occurred before insertion, causing the tentative offset and data to be
182+
/// abandoned. This allows clients to clean up other results or update any
183+
/// references.
184+
///
185+
/// NOTE: Does *not* guarantee that \p OnConstruct is only called on success.
186+
/// The in-memory \a TrieRawHashMap uses LazyAtomicPointer to synchronize
187+
/// simultaneous writes, but that seems dangerous to use in a memory-mapped
188+
/// file in case a process crashes in the busy state.
189+
Expected<pointer> insertLazy(ArrayRef<uint8_t> Hash,
190+
LazyInsertOnConstructCB OnConstruct = nullptr,
191+
LazyInsertOnLeakCB OnLeak = nullptr);
192+
193+
Expected<pointer> insert(const ConstValueProxy &Value) {
194+
return insertLazy(Value.Hash, [&](FileOffset, ValueProxy Allocated) {
195+
assert(Allocated.Hash == Value.Hash);
196+
assert(Allocated.Data.size() == Value.Data.size());
197+
llvm::copy(Value.Data, Allocated.Data.begin());
198+
});
199+
}
200+
201+
size_t size() const;
202+
size_t capacity() const;
203+
204+
/// Gets or creates a file at \p Path with a hash-mapped trie named \p
205+
/// TrieName. The hash size is \p NumHashBits (in bits) and the records store
206+
/// data of size \p DataSize (in bytes).
207+
///
208+
/// \p MaxFileSize controls the maximum file size to support, limiting the
209+
/// size of the \a mapped_file_region. \p NewFileInitialSize is the starting
210+
/// size if a new file is created.
211+
///
212+
/// \p NewTableNumRootBits and \p NewTableNumSubtrieBits are hints to
213+
/// configure the trie, if it doesn't already exist.
214+
///
215+
/// \pre NumHashBits is a multiple of 8 (byte-aligned).
216+
static Expected<OnDiskTrieRawHashMap>
217+
create(const Twine &Path, const Twine &TrieName, size_t NumHashBits,
218+
uint64_t DataSize, uint64_t MaxFileSize,
219+
std::optional<uint64_t> NewFileInitialSize,
220+
std::optional<size_t> NewTableNumRootBits = std::nullopt,
221+
std::optional<size_t> NewTableNumSubtrieBits = std::nullopt);
222+
223+
OnDiskTrieRawHashMap(OnDiskTrieRawHashMap &&RHS);
224+
OnDiskTrieRawHashMap &operator=(OnDiskTrieRawHashMap &&RHS);
225+
~OnDiskTrieRawHashMap();
226+
227+
private:
228+
struct ImplType;
229+
explicit OnDiskTrieRawHashMap(std::unique_ptr<ImplType> Impl);
230+
std::unique_ptr<ImplType> Impl;
231+
};
232+
233+
} // namespace cas
234+
} // namespace llvm
235+
236+
#endif // LLVM_CAS_ONDISKTRIERAWHASHMAP_H

llvm/lib/CAS/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ add_llvm_component_library(LLVMCAS
22
ActionCache.cpp
33
ActionCaches.cpp
44
BuiltinCAS.cpp
5+
DatabaseFile.cpp
56
InMemoryCAS.cpp
67
MappedFileRegionArena.cpp
78
ObjectStore.cpp
89
OnDiskCommon.cpp
10+
OnDiskTrieRawHashMap.cpp
911

1012
ADDITIONAL_HEADER_DIRS
1113
${LLVM_MAIN_INCLUDE_DIR}/llvm/CAS

0 commit comments

Comments
 (0)