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, const ValueTy &V)
113 : StringMapEntryBase(strLen), second(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, 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, 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 typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
250 typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
251 AllocatorRefTy getAllocator() { return Allocator; }
252 AllocatorCRefTy getAllocator() const { return Allocator; }
254 typedef const char* key_type;
255 typedef ValueTy mapped_type;
256 typedef StringMapEntry<ValueTy> value_type;
257 typedef size_t size_type;
259 typedef StringMapConstIterator<ValueTy> const_iterator;
260 typedef StringMapIterator<ValueTy> iterator;
263 return iterator(TheTable, NumBuckets == 0);
266 return iterator(TheTable+NumBuckets, true);
268 const_iterator begin() const {
269 return const_iterator(TheTable, NumBuckets == 0);
271 const_iterator end() const {
272 return const_iterator(TheTable+NumBuckets, true);
275 iterator find(StringRef Key) {
276 int Bucket = FindKey(Key);
277 if (Bucket == -1) return end();
278 return iterator(TheTable+Bucket, true);
281 const_iterator find(StringRef Key) const {
282 int Bucket = FindKey(Key);
283 if (Bucket == -1) return end();
284 return const_iterator(TheTable+Bucket, true);
287 /// lookup - Return the entry for the specified key, or a default
288 /// constructed value if no such entry exists.
289 ValueTy lookup(StringRef Key) const {
290 const_iterator it = find(Key);
296 ValueTy &operator[](StringRef Key) {
297 return GetOrCreateValue(Key).getValue();
300 /// count - Return 1 if the element is in the map, 0 otherwise.
301 size_type count(StringRef Key) const {
302 return find(Key) == end() ? 0 : 1;
305 /// insert - Insert the specified key/value pair into the map. If the key
306 /// already exists in the map, return false and ignore the request, otherwise
307 /// insert it and return true.
308 bool insert(MapEntryTy *KeyValue) {
309 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
310 StringMapEntryBase *&Bucket = TheTable[BucketNo];
311 if (Bucket && Bucket != getTombstoneVal())
312 return false; // Already exists in map.
314 if (Bucket == getTombstoneVal())
318 assert(NumItems + NumTombstones <= NumBuckets);
324 // clear - Empties out the StringMap
328 // Zap all values, resetting the keys back to non-present (not tombstone),
329 // which is safe because we're removing all elements.
330 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
331 StringMapEntryBase *&Bucket = TheTable[I];
332 if (Bucket && Bucket != getTombstoneVal()) {
333 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
342 /// GetOrCreateValue - Look up the specified key in the table. If a value
343 /// exists, return it. Otherwise, default construct a value, insert it, and
345 template <typename InitTy>
346 MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
347 unsigned BucketNo = LookupBucketFor(Key);
348 StringMapEntryBase *&Bucket = TheTable[BucketNo];
349 if (Bucket && Bucket != getTombstoneVal())
350 return *static_cast<MapEntryTy*>(Bucket);
352 MapEntryTy *NewItem =
353 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
355 if (Bucket == getTombstoneVal())
358 assert(NumItems + NumTombstones <= NumBuckets);
360 // Fill in the bucket for the hash table. The FullHashValue was already
361 // filled in by LookupBucketFor.
368 MapEntryTy &GetOrCreateValue(StringRef Key) {
369 return GetOrCreateValue(Key, ValueTy());
372 /// remove - Remove the specified key/value pair from the map, but do not
373 /// erase it. This aborts if the key is not in the map.
374 void remove(MapEntryTy *KeyValue) {
378 void erase(iterator I) {
381 V.Destroy(Allocator);
384 bool erase(StringRef Key) {
385 iterator I = find(Key);
386 if (I == end()) return false;
392 // Delete all the elements in the map, but don't reset the elements
393 // to default values. This is a copy of clear(), but avoids unnecessary
394 // work not required in the destructor.
396 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
397 StringMapEntryBase *Bucket = TheTable[I];
398 if (Bucket && Bucket != getTombstoneVal()) {
399 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
408 template<typename ValueTy>
409 class StringMapConstIterator {
411 StringMapEntryBase **Ptr;
413 typedef StringMapEntry<ValueTy> value_type;
415 StringMapConstIterator() : Ptr(nullptr) { }
417 explicit StringMapConstIterator(StringMapEntryBase **Bucket,
418 bool NoAdvance = false)
420 if (!NoAdvance) AdvancePastEmptyBuckets();
423 const value_type &operator*() const {
424 return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
426 const value_type *operator->() const {
427 return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
430 bool operator==(const StringMapConstIterator &RHS) const {
431 return Ptr == RHS.Ptr;
433 bool operator!=(const StringMapConstIterator &RHS) const {
434 return Ptr != RHS.Ptr;
437 inline StringMapConstIterator& operator++() { // Preincrement
439 AdvancePastEmptyBuckets();
442 StringMapConstIterator operator++(int) { // Postincrement
443 StringMapConstIterator tmp = *this; ++*this; return tmp;
447 void AdvancePastEmptyBuckets() {
448 while (*Ptr == nullptr || *Ptr == StringMapImpl::getTombstoneVal())
453 template<typename ValueTy>
454 class StringMapIterator : public StringMapConstIterator<ValueTy> {
456 StringMapIterator() {}
457 explicit StringMapIterator(StringMapEntryBase **Bucket,
458 bool NoAdvance = false)
459 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
461 StringMapEntry<ValueTy> &operator*() const {
462 return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
464 StringMapEntry<ValueTy> *operator->() const {
465 return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);