LLVM 17.0.0git
StringMap.h
Go to the documentation of this file.
1//===- StringMap.h - String Hash table map interface ------------*- C++ -*-===//
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 defines the StringMap class.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_STRINGMAP_H
15#define LLVM_ADT_STRINGMAP_H
16
18#include "llvm/ADT/iterator.h"
21#include <initializer_list>
22#include <iterator>
23
24namespace llvm {
25
26template <typename ValueTy> class StringMapConstIterator;
27template <typename ValueTy> class StringMapIterator;
28template <typename ValueTy> class StringMapKeyIterator;
29
30/// StringMapImpl - This is the base class of StringMap that is shared among
31/// all of its instantiations.
33protected:
34 // Array of NumBuckets pointers to entries, null pointers are holes.
35 // TheTable[NumBuckets] contains a sentinel value for easy iteration. Followed
36 // by an array of the actual hash values as unsigned integers.
38 unsigned NumBuckets = 0;
39 unsigned NumItems = 0;
40 unsigned NumTombstones = 0;
41 unsigned ItemSize;
42
43protected:
44 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {}
49 RHS.TheTable = nullptr;
50 RHS.NumBuckets = 0;
51 RHS.NumItems = 0;
52 RHS.NumTombstones = 0;
53 }
54
55 StringMapImpl(unsigned InitSize, unsigned ItemSize);
56 unsigned RehashTable(unsigned BucketNo = 0);
57
58 /// LookupBucketFor - Look up the bucket that the specified string should end
59 /// up in. If it already exists as a key in the map, the Item pointer for the
60 /// specified bucket will be non-null. Otherwise, it will be null. In either
61 /// case, the FullHashValue field of the bucket will be set to the hash value
62 /// of the string.
63 unsigned LookupBucketFor(StringRef Key);
64
65 /// FindKey - Look up the bucket that contains the specified key. If it exists
66 /// in the map, return the bucket number of the key. Otherwise return -1.
67 /// This does not modify the map.
68 int FindKey(StringRef Key) const;
69
70 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
71 /// delete it. This aborts if the value isn't in the table.
73
74 /// RemoveKey - Remove the StringMapEntry for the specified key from the
75 /// table, returning it. If the key is not in the table, this returns null.
77
78 /// Allocate the table with the specified number of buckets and otherwise
79 /// setup the map as empty.
80 void init(unsigned Size);
81
82public:
83 static constexpr uintptr_t TombstoneIntVal =
84 static_cast<uintptr_t>(-1)
86
88 return reinterpret_cast<StringMapEntryBase *>(TombstoneIntVal);
89 }
90
91 unsigned getNumBuckets() const { return NumBuckets; }
92 unsigned getNumItems() const { return NumItems; }
93
94 bool empty() const { return NumItems == 0; }
95 unsigned size() const { return NumItems; }
96
98 std::swap(TheTable, Other.TheTable);
99 std::swap(NumBuckets, Other.NumBuckets);
100 std::swap(NumItems, Other.NumItems);
101 std::swap(NumTombstones, Other.NumTombstones);
102 }
103};
104
105/// StringMap - This is an unconventional map that is specialized for handling
106/// keys that are "strings", which are basically ranges of bytes. This does some
107/// funky memory allocation and hashing things to make it extremely efficient,
108/// storing the string data *after* the value in the map.
109template <typename ValueTy, typename AllocatorTy = MallocAllocator>
111 private detail::AllocatorHolder<AllocatorTy> {
113
114public:
116
117 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
118
119 explicit StringMap(unsigned InitialSize)
120 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
121
122 explicit StringMap(AllocatorTy A)
123 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), AllocTy(A) {}
124
125 StringMap(unsigned InitialSize, AllocatorTy A)
126 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))),
127 AllocTy(A) {}
128
129 StringMap(std::initializer_list<std::pair<StringRef, ValueTy>> List)
130 : StringMapImpl(List.size(), static_cast<unsigned>(sizeof(MapEntryTy))) {
131 insert(List);
132 }
133
136
138 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))),
140 if (RHS.empty())
141 return;
142
143 // Allocate TheTable of the same size as RHS's TheTable, and set the
144 // sentinel appropriately (and NumBuckets).
145 init(RHS.NumBuckets);
146 unsigned *HashTable = (unsigned *)(TheTable + NumBuckets + 1),
147 *RHSHashTable = (unsigned *)(RHS.TheTable + NumBuckets + 1);
148
149 NumItems = RHS.NumItems;
150 NumTombstones = RHS.NumTombstones;
151 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
152 StringMapEntryBase *Bucket = RHS.TheTable[I];
153 if (!Bucket || Bucket == getTombstoneVal()) {
154 TheTable[I] = Bucket;
155 continue;
156 }
157
159 static_cast<MapEntryTy *>(Bucket)->getKey(), getAllocator(),
160 static_cast<MapEntryTy *>(Bucket)->getValue());
161 HashTable[I] = RHSHashTable[I];
162 }
163
164 // Note that here we've copied everything from the RHS into this object,
165 // tombstones included. We could, instead, have re-probed for each key to
166 // instantiate this new object without any tombstone buckets. The
167 // assumption here is that items are rarely deleted from most StringMaps,
168 // and so tombstones are rare, so the cost of re-probing for all inputs is
169 // not worthwhile.
170 }
171
174 std::swap(getAllocator(), RHS.getAllocator());
175 return *this;
176 }
177
179 // Delete all the elements in the map, but don't reset the elements
180 // to default values. This is a copy of clear(), but avoids unnecessary
181 // work not required in the destructor.
182 if (!empty()) {
183 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
184 StringMapEntryBase *Bucket = TheTable[I];
185 if (Bucket && Bucket != getTombstoneVal()) {
186 static_cast<MapEntryTy *>(Bucket)->Destroy(getAllocator());
187 }
188 }
189 }
190 free(TheTable);
191 }
192
194
195 using key_type = const char *;
196 using mapped_type = ValueTy;
198 using size_type = size_t;
199
202
204 iterator end() { return iterator(TheTable + NumBuckets, true); }
206 return const_iterator(TheTable, NumBuckets == 0);
207 }
209 return const_iterator(TheTable + NumBuckets, true);
210 }
211
215 }
216
218 int Bucket = FindKey(Key);
219 if (Bucket == -1)
220 return end();
221 return iterator(TheTable + Bucket, true);
222 }
223
225 int Bucket = FindKey(Key);
226 if (Bucket == -1)
227 return end();
228 return const_iterator(TheTable + Bucket, true);
229 }
230
231 /// lookup - Return the entry for the specified key, or a default
232 /// constructed value if no such entry exists.
233 ValueTy lookup(StringRef Key) const {
234 const_iterator Iter = find(Key);
235 if (Iter != end())
236 return Iter->second;
237 return ValueTy();
238 }
239
240 /// at - Return the entry for the specified key, or abort if no such
241 /// entry exists.
242 const ValueTy &at(StringRef Val) const {
243 auto Iter = this->find(std::move(Val));
244 assert(Iter != this->end() && "StringMap::at failed due to a missing key");
245 return Iter->second;
246 }
247
248 /// Lookup the ValueTy for the \p Key, or create a default constructed value
249 /// if the key is not in the map.
250 ValueTy &operator[](StringRef Key) { return try_emplace(Key).first->second; }
251
252 /// contains - Return true if the element is in the map, false otherwise.
253 bool contains(StringRef Key) const { return find(Key) != end(); }
254
255 /// count - Return 1 if the element is in the map, 0 otherwise.
256 size_type count(StringRef Key) const { return contains(Key) ? 1 : 0; }
257
258 template <typename InputTy>
259 size_type count(const StringMapEntry<InputTy> &MapEntry) const {
260 return count(MapEntry.getKey());
261 }
262
263 /// equal - check whether both of the containers are equal.
264 bool operator==(const StringMap &RHS) const {
265 if (size() != RHS.size())
266 return false;
267
268 for (const auto &KeyValue : *this) {
269 auto FindInRHS = RHS.find(KeyValue.getKey());
270
271 if (FindInRHS == RHS.end())
272 return false;
273
274 if (!(KeyValue.getValue() == FindInRHS->getValue()))
275 return false;
276 }
277
278 return true;
279 }
280
281 bool operator!=(const StringMap &RHS) const { return !(*this == RHS); }
282
283 /// insert - Insert the specified key/value pair into the map. If the key
284 /// already exists in the map, return false and ignore the request, otherwise
285 /// insert it and return true.
286 bool insert(MapEntryTy *KeyValue) {
287 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
288 StringMapEntryBase *&Bucket = TheTable[BucketNo];
289 if (Bucket && Bucket != getTombstoneVal())
290 return false; // Already exists in map.
291
292 if (Bucket == getTombstoneVal())
294 Bucket = KeyValue;
295 ++NumItems;
297
298 RehashTable();
299 return true;
300 }
301
302 /// insert - Inserts the specified key/value pair into the map if the key
303 /// isn't already in the map. The bool component of the returned pair is true
304 /// if and only if the insertion takes place, and the iterator component of
305 /// the pair points to the element with key equivalent to the key of the pair.
306 std::pair<iterator, bool> insert(std::pair<StringRef, ValueTy> KV) {
307 return try_emplace(KV.first, std::move(KV.second));
308 }
309
310 /// Inserts elements from range [first, last). If multiple elements in the
311 /// range have keys that compare equivalent, it is unspecified which element
312 /// is inserted .
313 template <typename InputIt> void insert(InputIt First, InputIt Last) {
314 for (InputIt It = First; It != Last; ++It)
315 insert(*It);
316 }
317
318 /// Inserts elements from initializer list ilist. If multiple elements in
319 /// the range have keys that compare equivalent, it is unspecified which
320 /// element is inserted
321 void insert(std::initializer_list<std::pair<StringRef, ValueTy>> List) {
322 insert(List.begin(), List.end());
323 }
324
325 /// Inserts an element or assigns to the current element if the key already
326 /// exists. The return type is the same as try_emplace.
327 template <typename V>
328 std::pair<iterator, bool> insert_or_assign(StringRef Key, V &&Val) {
329 auto Ret = try_emplace(Key, std::forward<V>(Val));
330 if (!Ret.second)
331 Ret.first->second = std::forward<V>(Val);
332 return Ret;
333 }
334
335 /// Emplace a new element for the specified key into the map if the key isn't
336 /// already in the map. The bool component of the returned pair is true
337 /// if and only if the insertion takes place, and the iterator component of
338 /// the pair points to the element with key equivalent to the key of the pair.
339 template <typename... ArgsTy>
340 std::pair<iterator, bool> try_emplace(StringRef Key, ArgsTy &&...Args) {
341 unsigned BucketNo = LookupBucketFor(Key);
342 StringMapEntryBase *&Bucket = TheTable[BucketNo];
343 if (Bucket && Bucket != getTombstoneVal())
344 return std::make_pair(iterator(TheTable + BucketNo, false),
345 false); // Already exists in map.
346
347 if (Bucket == getTombstoneVal())
349 Bucket =
350 MapEntryTy::create(Key, getAllocator(), std::forward<ArgsTy>(Args)...);
351 ++NumItems;
353
354 BucketNo = RehashTable(BucketNo);
355 return std::make_pair(iterator(TheTable + BucketNo, false), true);
356 }
357
358 // clear - Empties out the StringMap
359 void clear() {
360 if (empty())
361 return;
362
363 // Zap all values, resetting the keys back to non-present (not tombstone),
364 // which is safe because we're removing all elements.
365 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
366 StringMapEntryBase *&Bucket = TheTable[I];
367 if (Bucket && Bucket != getTombstoneVal()) {
368 static_cast<MapEntryTy *>(Bucket)->Destroy(getAllocator());
369 }
370 Bucket = nullptr;
371 }
372
373 NumItems = 0;
374 NumTombstones = 0;
375 }
376
377 /// remove - Remove the specified key/value pair from the map, but do not
378 /// erase it. This aborts if the key is not in the map.
379 void remove(MapEntryTy *KeyValue) { RemoveKey(KeyValue); }
380
382 MapEntryTy &V = *I;
383 remove(&V);
384 V.Destroy(getAllocator());
385 }
386
387 bool erase(StringRef Key) {
388 iterator I = find(Key);
389 if (I == end())
390 return false;
391 erase(I);
392 return true;
393 }
394};
395
396template <typename DerivedTy, typename ValueTy>
398 : public iterator_facade_base<DerivedTy, std::forward_iterator_tag,
399 ValueTy> {
400protected:
402
403public:
404 StringMapIterBase() = default;
405
407 bool NoAdvance = false)
408 : Ptr(Bucket) {
409 if (!NoAdvance)
410 AdvancePastEmptyBuckets();
411 }
412
413 DerivedTy &operator=(const DerivedTy &Other) {
414 Ptr = Other.Ptr;
415 return static_cast<DerivedTy &>(*this);
416 }
417
418 friend bool operator==(const DerivedTy &LHS, const DerivedTy &RHS) {
419 return LHS.Ptr == RHS.Ptr;
420 }
421
422 DerivedTy &operator++() { // Preincrement
423 ++Ptr;
424 AdvancePastEmptyBuckets();
425 return static_cast<DerivedTy &>(*this);
426 }
427
428 DerivedTy operator++(int) { // Post-increment
429 DerivedTy Tmp(Ptr);
430 ++*this;
431 return Tmp;
432 }
433
434private:
435 void AdvancePastEmptyBuckets() {
436 while (*Ptr == nullptr || *Ptr == StringMapImpl::getTombstoneVal())
437 ++Ptr;
438 }
439};
440
441template <typename ValueTy>
443 : public StringMapIterBase<StringMapConstIterator<ValueTy>,
444 const StringMapEntry<ValueTy>> {
447
448public:
451 bool NoAdvance = false)
452 : base(Bucket, NoAdvance) {}
453
455 return *static_cast<const StringMapEntry<ValueTy> *>(*this->Ptr);
456 }
457};
458
459template <typename ValueTy>
460class StringMapIterator : public StringMapIterBase<StringMapIterator<ValueTy>,
461 StringMapEntry<ValueTy>> {
462 using base =
464
465public:
466 StringMapIterator() = default;
468 bool NoAdvance = false)
469 : base(Bucket, NoAdvance) {}
470
472 return *static_cast<StringMapEntry<ValueTy> *>(*this->Ptr);
473 }
474
476 return StringMapConstIterator<ValueTy>(this->Ptr, true);
477 }
478};
479
480template <typename ValueTy>
482 : public iterator_adaptor_base<StringMapKeyIterator<ValueTy>,
483 StringMapConstIterator<ValueTy>,
484 std::forward_iterator_tag, StringRef> {
487 std::forward_iterator_tag, StringRef>;
488
489public:
492 : base(std::move(Iter)) {}
493
494 StringRef operator*() const { return this->wrapped()->getKey(); }
495};
496
497} // end namespace llvm
498
499#endif // LLVM_ADT_STRINGMAP_H
This file defines the StringMapEntry class - it is intended to be a low dependency implementation det...
This file defines MallocAllocator.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
uint64_t Size
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value * RHS
Value * LHS
StringMapConstIterator(StringMapEntryBase **Bucket, bool NoAdvance=false)
Definition: StringMap.h:450
const StringMapEntry< ValueTy > & operator*() const
Definition: StringMap.h:454
StringMapEntryBase - Shared base class of StringMapEntry instances.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
static StringMapEntry * create(StringRef key, AllocatorTy &allocator, InitTy &&...initVals)
Create a StringMapEntry for the specified key construct the value using InitiVals.
StringRef getKey() const
StringMapImpl - This is the base class of StringMap that is shared among all of its instantiations.
Definition: StringMap.h:32
void swap(StringMapImpl &Other)
Definition: StringMap.h:97
static StringMapEntryBase * getTombstoneVal()
Definition: StringMap.h:87
unsigned ItemSize
Definition: StringMap.h:41
int FindKey(StringRef Key) const
FindKey - Look up the bucket that contains the specified key.
Definition: StringMap.cpp:139
unsigned RehashTable(unsigned BucketNo=0)
RehashTable - Grow the table, redistributing values into the buckets with the appropriate mod-of-hash...
Definition: StringMap.cpp:206
unsigned NumItems
Definition: StringMap.h:39
unsigned LookupBucketFor(StringRef Key)
LookupBucketFor - Look up the bucket that the specified string should end up in.
Definition: StringMap.cpp:83
void RemoveKey(StringMapEntryBase *V)
RemoveKey - Remove the specified StringMapEntry from the table, but do not delete it.
Definition: StringMap.cpp:181
StringMapEntryBase ** TheTable
Definition: StringMap.h:37
unsigned getNumBuckets() const
Definition: StringMap.h:91
unsigned size() const
Definition: StringMap.h:95
StringMapImpl(unsigned itemSize)
Definition: StringMap.h:44
void init(unsigned Size)
Allocate the table with the specified number of buckets and otherwise setup the map as empty.
Definition: StringMap.cpp:64
unsigned getNumItems() const
Definition: StringMap.h:92
unsigned NumBuckets
Definition: StringMap.h:38
static constexpr uintptr_t TombstoneIntVal
Definition: StringMap.h:83
unsigned NumTombstones
Definition: StringMap.h:40
bool empty() const
Definition: StringMap.h:94
StringMapImpl(StringMapImpl &&RHS)
Definition: StringMap.h:45
DerivedTy & operator++()
Definition: StringMap.h:422
StringMapEntryBase ** Ptr
Definition: StringMap.h:401
DerivedTy operator++(int)
Definition: StringMap.h:428
DerivedTy & operator=(const DerivedTy &Other)
Definition: StringMap.h:413
StringMapIterBase(StringMapEntryBase **Bucket, bool NoAdvance=false)
Definition: StringMap.h:406
friend bool operator==(const DerivedTy &LHS, const DerivedTy &RHS)
Definition: StringMap.h:418
StringMapIterator(StringMapEntryBase **Bucket, bool NoAdvance=false)
Definition: StringMap.h:467
StringMapEntry< ValueTy > & operator*() const
Definition: StringMap.h:471
StringRef operator*() const
Definition: StringMap.h:494
StringMapKeyIterator(StringMapConstIterator< ValueTy > Iter)
Definition: StringMap.h:491
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:111
size_type count(const StringMapEntry< InputTy > &MapEntry) const
Definition: StringMap.h:259
StringMapConstIterator< ValueTy > const_iterator
Definition: StringMap.h:200
StringMap(StringMap &&RHS)
Definition: StringMap.h:134
bool erase(StringRef Key)
Definition: StringMap.h:387
iterator end()
Definition: StringMap.h:204
StringMap(std::initializer_list< std::pair< StringRef, ValueTy > > List)
Definition: StringMap.h:129
bool operator!=(const StringMap &RHS) const
Definition: StringMap.h:281
iterator begin()
Definition: StringMap.h:203
void remove(MapEntryTy *KeyValue)
remove - Remove the specified key/value pair from the map, but do not erase it.
Definition: StringMap.h:379
std::pair< iterator, bool > insert_or_assign(StringRef Key, V &&Val)
Inserts an element or assigns to the current element if the key already exists.
Definition: StringMap.h:328
iterator find(StringRef Key)
Definition: StringMap.h:217
const_iterator end() const
Definition: StringMap.h:208
StringMap(const StringMap &RHS)
Definition: StringMap.h:137
const ValueTy & at(StringRef Val) const
at - Return the entry for the specified key, or abort if no such entry exists.
Definition: StringMap.h:242
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition: StringMap.h:253
size_t size_type
Definition: StringMap.h:198
ValueTy mapped_type
Definition: StringMap.h:196
StringMapIterator< ValueTy > iterator
Definition: StringMap.h:201
std::pair< iterator, bool > insert(std::pair< StringRef, ValueTy > KV)
insert - Inserts the specified key/value pair into the map if the key isn't already in the map.
Definition: StringMap.h:306
iterator_range< StringMapKeyIterator< ValueTy > > keys() const
Definition: StringMap.h:212
const_iterator find(StringRef Key) const
Definition: StringMap.h:224
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:256
StringMap(AllocatorTy A)
Definition: StringMap.h:122
StringMap & operator=(StringMap RHS)
Definition: StringMap.h:172
void insert(InputIt First, InputIt Last)
Inserts elements from range [first, last).
Definition: StringMap.h:313
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: StringMap.h:233
const_iterator begin() const
Definition: StringMap.h:205
void erase(iterator I)
Definition: StringMap.h:381
StringMap(unsigned InitialSize)
Definition: StringMap.h:119
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition: StringMap.h:340
StringMap(unsigned InitialSize, AllocatorTy A)
Definition: StringMap.h:125
ValueTy & operator[](StringRef Key)
Lookup the ValueTy for the Key, or create a default constructed value if the key is not in the map.
Definition: StringMap.h:250
bool operator==(const StringMap &RHS) const
equal - check whether both of the containers are equal.
Definition: StringMap.h:264
void insert(std::initializer_list< std::pair< StringRef, ValueTy > > List)
Inserts elements from initializer list ilist.
Definition: StringMap.h:321
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:286
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
CRTP base class for adapting an iterator to a different type.
Definition: iterator.h:237
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:80
A range adaptor for a pair of iterators.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1946
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...