1 //===--- StringMap.h - String Hash table map interface ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the StringMap class.
11 //
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
17 #include "llvm/Support/Allocator.h"
18 #include <cstring>
20 namespace llvm {
21 template<typename ValueT>
22 class StringMapConstIterator;
23 template<typename ValueT>
24 class StringMapIterator;
27 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
28 class StringMapEntryBase {
29 unsigned StrLen;
30 public:
31 StringMapEntryBase(unsigned Len) : StrLen(Len) {}
33 unsigned getKeyLength() const { return StrLen; }
34 };
36 /// StringMapImpl - This is the base class of StringMap that is shared among
37 /// all of its instantiations.
38 class StringMapImpl {
39 public:
40 /// ItemBucket - The hash table consists of an array of these. If Item is
41 /// non-null, this is an extant entry, otherwise, it is a hole.
42 struct ItemBucket {
43 /// FullHashValue - This remembers the full hash value of the key for
44 /// easy scanning.
45 unsigned FullHashValue;
47 /// Item - This is a pointer to the actual item object.
48 StringMapEntryBase *Item;
49 };
51 protected:
52 ItemBucket *TheTable;
53 unsigned NumBuckets;
54 unsigned NumItems;
55 unsigned NumTombstones;
56 unsigned ItemSize;
57 protected:
58 StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
59 // Initialize the map with zero buckets to allocation.
60 TheTable = 0;
61 NumBuckets = 0;
62 NumItems = 0;
63 NumTombstones = 0;
64 }
65 StringMapImpl(unsigned InitSize, unsigned ItemSize);
66 void RehashTable();
68 /// ShouldRehash - Return true if the table should be rehashed after a new
69 /// element was recently inserted.
70 bool ShouldRehash() const {
71 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
72 // the buckets are empty (meaning that many are filled with tombstones),
73 // grow the table.
74 return NumItems*4 > NumBuckets*3 ||
75 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
76 }
78 /// LookupBucketFor - Look up the bucket that the specified string should end
79 /// up in. If it already exists as a key in the map, the Item pointer for the
80 /// specified bucket will be non-null. Otherwise, it will be null. In either
81 /// case, the FullHashValue field of the bucket will be set to the hash value
82 /// of the string.
83 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
85 /// FindKey - Look up the bucket that contains the specified key. If it exists
86 /// in the map, return the bucket number of the key. Otherwise return -1.
87 /// This does not modify the map.
88 int FindKey(const char *KeyStart, const char *KeyEnd) const;
90 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
91 /// delete it. This aborts if the value isn't in the table.
92 void RemoveKey(StringMapEntryBase *V);
94 /// RemoveKey - Remove the StringMapEntry for the specified key from the
95 /// table, returning it. If the key is not in the table, this returns null.
96 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
97 private:
98 void init(unsigned Size);
99 public:
100 static StringMapEntryBase *getTombstoneVal() {
101 return (StringMapEntryBase*)-1;
102 }
104 unsigned getNumBuckets() const { return NumBuckets; }
105 unsigned getNumItems() const { return NumItems; }
107 bool empty() const { return NumItems == 0; }
108 unsigned size() const { return NumItems; }
109 };
111 /// StringMapEntry - This is used to represent one value that is inserted into
112 /// a StringMap. It contains the Value itself and the key: the string length
113 /// and data.
114 template<typename ValueTy>
115 class StringMapEntry : public StringMapEntryBase {
116 ValueTy Val;
117 public:
118 StringMapEntry(unsigned StrLen)
119 : StringMapEntryBase(StrLen), Val() {}
120 StringMapEntry(unsigned StrLen, const ValueTy &V)
121 : StringMapEntryBase(StrLen), Val(V) {}
123 const ValueTy &getValue() const { return Val; }
124 ValueTy &getValue() { return Val; }
126 void setValue(const ValueTy &V) { Val = V; }
128 /// getKeyData - Return the start of the string data that is the key for this
129 /// value. The string data is always stored immediately after the
130 /// StringMapEntry object.
131 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
133 /// Create - Create a StringMapEntry for the specified key and default
134 /// construct the value.
135 template<typename AllocatorTy>
136 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
137 AllocatorTy &Allocator) {
138 unsigned KeyLength = KeyEnd-KeyStart;
140 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
141 // in. Allocate a new item with space for the string at the end and a null
142 // terminator.
143 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
145 #ifdef __GNUC__
146 unsigned Alignment = __alignof__(StringMapEntry);
147 #else
148 // FIXME: ugly.
149 unsigned Alignment = 8;
150 #endif
151 StringMapEntry *NewItem =
152 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize, Alignment));
154 // Default construct the value.
155 new (NewItem) StringMapEntry(KeyLength);
157 // Copy the string information.
158 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
159 memcpy(StrBuffer, KeyStart, KeyLength);
160 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
161 return NewItem;
162 }
164 /// Create - Create a StringMapEntry with normal malloc/free.
165 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
166 MallocAllocator A;
167 return Create(KeyStart, KeyEnd, A);
168 }
170 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
171 /// specified allocator.
172 template<typename AllocatorTy>
173 void Destroy(AllocatorTy &Allocator) {
174 // Free memory referenced by the item.
175 this->~StringMapEntry();
176 Allocator.Deallocate(this);
177 }
179 /// Destroy this object, releasing memory back to the malloc allocator.
180 void Destroy() {
181 MallocAllocator A;
182 Destroy(A);
183 }
184 };
187 /// StringMap - This is an unconventional map that is specialized for handling
188 /// keys that are "strings", which are basically ranges of bytes. This does some
189 /// funky memory allocation and hashing things to make it extremely efficient,
190 /// storing the string data *after* the value in the map.
191 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
192 class StringMap : public StringMapImpl {
193 AllocatorTy Allocator;
194 typedef StringMapEntry<ValueTy> MapEntryTy;
195 public:
196 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
197 StringMap(unsigned InitialSize)
198 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
200 AllocatorTy &getAllocator() { return Allocator; }
201 const AllocatorTy &getAllocator() const { return Allocator; }
203 typedef StringMapConstIterator<ValueTy> const_iterator;
204 typedef StringMapIterator<ValueTy> iterator;
206 iterator begin() {
207 return iterator(TheTable, NumBuckets == 0);
208 }
209 iterator end() {
210 return iterator(TheTable+NumBuckets, true);
211 }
212 const_iterator begin() const {
213 return const_iterator(TheTable, NumBuckets == 0);
214 }
215 const_iterator end() const {
216 return const_iterator(TheTable+NumBuckets, true);
217 }
219 iterator find(const char *KeyStart, const char *KeyEnd) {
220 int Bucket = FindKey(KeyStart, KeyEnd);
221 if (Bucket == -1) return end();
222 return iterator(TheTable+Bucket);
223 }
225 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
226 int Bucket = FindKey(KeyStart, KeyEnd);
227 if (Bucket == -1) return end();
228 return const_iterator(TheTable+Bucket);
229 }
231 /// insert - Insert the specified key/value pair into the map. If the key
232 /// already exists in the map, return false and ignore the request, otherwise
233 /// insert it and return true.
234 bool insert(MapEntryTy *KeyValue) {
235 unsigned BucketNo =
236 LookupBucketFor(KeyValue->getKeyData(),
237 KeyValue->getKeyData()+KeyValue->getKeyLength());
238 ItemBucket &Bucket = TheTable[BucketNo];
239 if (Bucket.Item && Bucket.Item != getTombstoneVal())
240 return false; // Already exists in map.
242 if (Bucket.Item == getTombstoneVal())
243 --NumTombstones;
244 Bucket.Item = KeyValue;
245 ++NumItems;
247 if (ShouldRehash())
248 RehashTable();
249 return true;
250 }
252 /// GetOrCreateValue - Look up the specified key in the table. If a value
253 /// exists, return it. Otherwise, default construct a value, insert it, and
254 /// return.
255 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
256 const char *KeyEnd) {
257 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
258 ItemBucket &Bucket = TheTable[BucketNo];
259 if (Bucket.Item && Bucket.Item != getTombstoneVal())
260 return *static_cast<MapEntryTy*>(Bucket.Item);
262 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
264 if (Bucket.Item == getTombstoneVal())
265 --NumTombstones;
266 ++NumItems;
268 // Fill in the bucket for the hash table. The FullHashValue was already
269 // filled in by LookupBucketFor.
270 Bucket.Item = NewItem;
272 if (ShouldRehash())
273 RehashTable();
274 return *NewItem;
275 }
277 /// remove - Remove the specified key/value pair from the map, but do not
278 /// erase it. This aborts if the key is not in the map.
279 void remove(MapEntryTy *KeyValue) {
280 RemoveKey(KeyValue);
281 }
283 void erase(iterator I) {
284 MapEntryTy &V = *I;
285 remove(&V);
286 V.Destroy(Allocator);
287 }
289 ~StringMap() {
290 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
291 if (I->Item && I->Item != getTombstoneVal())
292 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
293 }
294 free(TheTable);
295 }
296 private:
297 StringMap(const StringMap &); // FIXME: Implement.
298 void operator=(const StringMap &); // FIXME: Implement.
299 };
302 template<typename ValueTy>
303 class StringMapConstIterator {
304 protected:
305 StringMapImpl::ItemBucket *Ptr;
306 public:
307 StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
308 bool NoAdvance = false)
309 : Ptr(Bucket) {
310 if (!NoAdvance) AdvancePastEmptyBuckets();
311 }
313 const StringMapEntry<ValueTy> &operator*() const {
314 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
315 }
316 const StringMapEntry<ValueTy> *operator->() const {
317 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
318 }
320 bool operator==(const StringMapConstIterator &RHS) const {
321 return Ptr == RHS.Ptr;
322 }
323 bool operator!=(const StringMapConstIterator &RHS) const {
324 return Ptr != RHS.Ptr;
325 }
327 inline StringMapConstIterator& operator++() { // Preincrement
328 ++Ptr;
329 AdvancePastEmptyBuckets();
330 return *this;
331 }
332 StringMapConstIterator operator++(int) { // Postincrement
333 StringMapConstIterator tmp = *this; ++*this; return tmp;
334 }
336 private:
337 void AdvancePastEmptyBuckets() {
338 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
339 ++Ptr;
340 }
341 };
343 template<typename ValueTy>
344 class StringMapIterator : public StringMapConstIterator<ValueTy> {
345 public:
346 StringMapIterator(StringMapImpl::ItemBucket *Bucket,
347 bool NoAdvance = false)
348 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
349 }
350 StringMapEntry<ValueTy> &operator*() const {
351 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
352 }
353 StringMapEntry<ValueTy> *operator->() const {
354 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
355 }
356 };
358 }
360 #endif