1 //===--- StringMap.h - String Hash table map interface ----------*- 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 //===----------------------------------------------------------------------===//
10 // This file defines the StringMap class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Allocator.h"
22 template<typename ValueT>
23 class StringMapConstIterator;
24 template<typename ValueT>
25 class StringMapIterator;
26 template<typename ValueTy>
29 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
30 class StringMapEntryBase {
33 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
35 unsigned getKeyLength() const { return StrLen; }
38 /// StringMapImpl - This is the base class of StringMap that is shared among
39 /// all of its instantiations.
42 // Array of NumBuckets pointers to entries, null pointers are holes.
43 // TheTable[NumBuckets] contains a sentinel value for easy iteration. Followed
44 // by an array of the actual hash values as unsigned integers.
45 StringMapEntryBase **TheTable;
48 unsigned NumTombstones;
51 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
52 // Initialize the map with zero buckets to allocation.
58 StringMapImpl(unsigned InitSize, unsigned ItemSize);
61 /// LookupBucketFor - Look up the bucket that the specified string should end
62 /// up in. If it already exists as a key in the map, the Item pointer for the
63 /// specified bucket will be non-null. Otherwise, it will be null. In either
64 /// case, the FullHashValue field of the bucket will be set to the hash value
66 unsigned LookupBucketFor(StringRef Key);
68 /// FindKey - Look up the bucket that contains the specified key. If it exists
69 /// in the map, return the bucket number of the key. Otherwise return -1.
70 /// This does not modify the map.
71 int FindKey(StringRef Key) const;
73 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
74 /// delete it. This aborts if the value isn't in the table.
75 void RemoveKey(StringMapEntryBase *V);
77 /// RemoveKey - Remove the StringMapEntry for the specified key from the
78 /// table, returning it. If the key is not in the table, this returns null.
79 StringMapEntryBase *RemoveKey(StringRef Key);
81 void init(unsigned Size);
83 static StringMapEntryBase *getTombstoneVal() {
84 return (StringMapEntryBase*)-1;
87 unsigned getNumBuckets() const { return NumBuckets; }
88 unsigned getNumItems() const { return NumItems; }
90 bool empty() const { return NumItems == 0; }
91 unsigned size() const { return NumItems; }
93 void swap(StringMapImpl &Other) {
94 std::swap(TheTable, Other.TheTable);
95 std::swap(NumBuckets, Other.NumBuckets);
96 std::swap(NumItems, Other.NumItems);
97 std::swap(NumTombstones, Other.NumTombstones);
101 /// StringMapEntry - This is used to represent one value that is inserted into
102 /// a StringMap. It contains the Value itself and the key: the string length
104 template<typename ValueTy>
105 class StringMapEntry : public StringMapEntryBase {
106 StringMapEntry(StringMapEntry &E) LLVM_DELETED_FUNCTION;
110 explicit StringMapEntry(unsigned strLen)
111 : StringMapEntryBase(strLen), second() {}
112 StringMapEntry(unsigned strLen, ValueTy V)
113 : StringMapEntryBase(strLen), second(std::move(V)) {}
115 StringRef getKey() const {
116 return StringRef(getKeyData(), getKeyLength());
119 const ValueTy &getValue() const { return second; }
120 ValueTy &getValue() { return second; }
122 void setValue(const ValueTy &V) { second = V; }
124 /// getKeyData - Return the start of the string data that is the key for this
125 /// value. The string data is always stored immediately after the
126 /// StringMapEntry object.
127 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
129 StringRef first() const { return StringRef(getKeyData(), getKeyLength()); }
131 /// Create - Create a StringMapEntry for the specified key and default
132 /// construct the value.
133 template<typename AllocatorTy, typename InitType>
134 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
135 AllocatorTy &Allocator,
137 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
139 // Allocate a new item with space for the string at the end and a null
141 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
143 unsigned Alignment = alignOf<StringMapEntry>();
145 StringMapEntry *NewItem =
146 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
148 // Default construct the value.
149 new (NewItem) StringMapEntry(KeyLength, std::move(InitVal));
151 // Copy the string information.
152 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
153 memcpy(StrBuffer, KeyStart, KeyLength);
154 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
158 template<typename AllocatorTy>
159 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
160 AllocatorTy &Allocator) {
161 return Create(KeyStart, KeyEnd, Allocator, 0);
164 /// Create - Create a StringMapEntry with normal malloc/free.
165 template<typename InitType>
166 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
169 return Create(KeyStart, KeyEnd, A, std::move(InitVal));
172 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
173 return Create(KeyStart, KeyEnd, ValueTy());
176 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
177 /// into a StringMapEntry, return the StringMapEntry itself.
178 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
179 StringMapEntry *EPtr = 0;
180 char *Ptr = reinterpret_cast<char*>(&V) -
181 (reinterpret_cast<char*>(&EPtr->second) -
182 reinterpret_cast<char*>(EPtr));
183 return *reinterpret_cast<StringMapEntry*>(Ptr);
185 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
186 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
189 /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
190 /// into a StringMapEntry, return the StringMapEntry itself.
191 static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
192 char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
193 return *reinterpret_cast<StringMapEntry*>(Ptr);
196 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
197 /// specified allocator.
198 template<typename AllocatorTy>
199 void Destroy(AllocatorTy &Allocator) {
200 // Free memory referenced by the item.
202 static_cast<unsigned>(sizeof(StringMapEntry)) + getKeyLength() + 1;
203 this->~StringMapEntry();
204 Allocator.Deallocate(static_cast<void *>(this), AllocSize);
207 /// Destroy this object, releasing memory back to the malloc allocator.
215 /// StringMap - This is an unconventional map that is specialized for handling
216 /// keys that are "strings", which are basically ranges of bytes. This does some
217 /// funky memory allocation and hashing things to make it extremely efficient,
218 /// storing the string data *after* the value in the map.
219 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
220 class StringMap : public StringMapImpl {
221 AllocatorTy Allocator;
223 typedef StringMapEntry<ValueTy> MapEntryTy;
225 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
226 explicit StringMap(unsigned InitialSize)
227 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
229 explicit StringMap(AllocatorTy A)
230 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
232 StringMap(unsigned InitialSize, AllocatorTy A)
233 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))),
236 StringMap(const StringMap &RHS)
237 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
238 assert(RHS.empty() &&
239 "Copy ctor from non-empty stringmap not implemented yet!");
242 void operator=(const StringMap &RHS) {
243 assert(RHS.empty() &&
244 "assignment from non-empty stringmap not implemented yet!");
249 AllocatorTy &getAllocator() { return Allocator; }
250 const AllocatorTy &getAllocator() const { return Allocator; }
252 typedef const char* key_type;
253 typedef ValueTy mapped_type;
254 typedef StringMapEntry<ValueTy> value_type;
255 typedef size_t size_type;
257 typedef StringMapConstIterator<ValueTy> const_iterator;
258 typedef StringMapIterator<ValueTy> iterator;
261 return iterator(TheTable, NumBuckets == 0);
264 return iterator(TheTable+NumBuckets, true);
266 const_iterator begin() const {
267 return const_iterator(TheTable, NumBuckets == 0);
269 const_iterator end() const {
270 return const_iterator(TheTable+NumBuckets, true);
273 iterator find(StringRef Key) {
274 int Bucket = FindKey(Key);
275 if (Bucket == -1) return end();
276 return iterator(TheTable+Bucket, true);
279 const_iterator find(StringRef Key) const {
280 int Bucket = FindKey(Key);
281 if (Bucket == -1) return end();
282 return const_iterator(TheTable+Bucket, true);
285 /// lookup - Return the entry for the specified key, or a default
286 /// constructed value if no such entry exists.
287 ValueTy lookup(StringRef Key) const {
288 const_iterator it = find(Key);
294 ValueTy &operator[](StringRef Key) {
295 return GetOrCreateValue(Key).getValue();
298 /// count - Return 1 if the element is in the map, 0 otherwise.
299 size_type count(StringRef Key) const {
300 return find(Key) == end() ? 0 : 1;
303 /// insert - Insert the specified key/value pair into the map. If the key
304 /// already exists in the map, return false and ignore the request, otherwise
305 /// insert it and return true.
306 bool insert(MapEntryTy *KeyValue) {
307 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
308 StringMapEntryBase *&Bucket = TheTable[BucketNo];
309 if (Bucket && Bucket != getTombstoneVal())
310 return false; // Already exists in map.
312 if (Bucket == getTombstoneVal())
316 assert(NumItems + NumTombstones <= NumBuckets);
322 // clear - Empties out the StringMap
326 // Zap all values, resetting the keys back to non-present (not tombstone),
327 // which is safe because we're removing all elements.
328 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
329 StringMapEntryBase *&Bucket = TheTable[I];
330 if (Bucket && Bucket != getTombstoneVal()) {
331 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
340 /// GetOrCreateValue - Look up the specified key in the table. If a value
341 /// exists, return it. Otherwise, default construct a value, insert it, and
343 template <typename InitTy>
344 MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
345 unsigned BucketNo = LookupBucketFor(Key);
346 StringMapEntryBase *&Bucket = TheTable[BucketNo];
347 if (Bucket && Bucket != getTombstoneVal())
348 return *static_cast<MapEntryTy*>(Bucket);
350 MapEntryTy *NewItem =
351 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, std::move(Val));
353 if (Bucket == getTombstoneVal())
356 assert(NumItems + NumTombstones <= NumBuckets);
358 // Fill in the bucket for the hash table. The FullHashValue was already
359 // filled in by LookupBucketFor.
366 MapEntryTy &GetOrCreateValue(StringRef Key) {
367 return GetOrCreateValue(Key, ValueTy());
370 /// remove - Remove the specified key/value pair from the map, but do not
371 /// erase it. This aborts if the key is not in the map.
372 void remove(MapEntryTy *KeyValue) {
376 void erase(iterator I) {
379 V.Destroy(Allocator);
382 bool erase(StringRef Key) {
383 iterator I = find(Key);
384 if (I == end()) return false;
390 // Delete all the elements in the map, but don't reset the elements
391 // to default values. This is a copy of clear(), but avoids unnecessary
392 // work not required in the destructor.
394 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
395 StringMapEntryBase *Bucket = TheTable[I];
396 if (Bucket && Bucket != getTombstoneVal()) {
397 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
406 template<typename ValueTy>
407 class StringMapConstIterator {
409 StringMapEntryBase **Ptr;
411 typedef StringMapEntry<ValueTy> value_type;
413 StringMapConstIterator() : Ptr(nullptr) { }
415 explicit StringMapConstIterator(StringMapEntryBase **Bucket,
416 bool NoAdvance = false)
418 if (!NoAdvance) AdvancePastEmptyBuckets();
421 const value_type &operator*() const {
422 return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
424 const value_type *operator->() const {
425 return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
428 bool operator==(const StringMapConstIterator &RHS) const {
429 return Ptr == RHS.Ptr;
431 bool operator!=(const StringMapConstIterator &RHS) const {
432 return Ptr != RHS.Ptr;
435 inline StringMapConstIterator& operator++() { // Preincrement
437 AdvancePastEmptyBuckets();
440 StringMapConstIterator operator++(int) { // Postincrement
441 StringMapConstIterator tmp = *this; ++*this; return tmp;
445 void AdvancePastEmptyBuckets() {
446 while (*Ptr == nullptr || *Ptr == StringMapImpl::getTombstoneVal())
451 template<typename ValueTy>
452 class StringMapIterator : public StringMapConstIterator<ValueTy> {
454 StringMapIterator() {}
455 explicit StringMapIterator(StringMapEntryBase **Bucket,
456 bool NoAdvance = false)
457 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
459 StringMapEntry<ValueTy> &operator*() const {
460 return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
462 StringMapEntry<ValueTy> *operator->() const {
463 return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);