add new ShouldRehash method to factor out common code. Fix the dtor to not
[oota-llvm.git] / include / llvm / ADT / StringMap.h
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 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
16
17 #include "llvm/Support/Allocator.h"
18 #include <cstring>
19
20 namespace llvm {
21   template<typename ValueT>
22   class StringMapConstIterator;
23   template<typename ValueT>
24   class StringMapIterator;
25
26   
27 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
28 class StringMapEntryBase {
29   unsigned StrLen;
30 public:
31   StringMapEntryBase(unsigned Len) : StrLen(Len) {}
32   
33   unsigned getKeyLength() const { return StrLen; }
34 };
35   
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;
46     
47     /// Item - This is a pointer to the actual item object.
48     StringMapEntryBase *Item;
49   };
50   
51 protected:
52   ItemBucket *TheTable;
53   unsigned NumBuckets;
54   unsigned NumItems;
55   unsigned NumTombstones;
56   unsigned ItemSize;
57 protected:
58   StringMapImpl(unsigned InitSize, unsigned ItemSize);
59   void RehashTable();
60   
61   /// ShouldRehash - Return true if the table should be rehashed after a new
62   /// element was recently inserted.
63   bool ShouldRehash() const {
64     // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
65     // the buckets are empty (meaning that many are filled with tombstones),
66     // grow the table.
67     return NumItems*4 > NumBuckets*3 ||
68            NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
69   }
70   
71   /// LookupBucketFor - Look up the bucket that the specified string should end
72   /// up in.  If it already exists as a key in the map, the Item pointer for the
73   /// specified bucket will be non-null.  Otherwise, it will be null.  In either
74   /// case, the FullHashValue field of the bucket will be set to the hash value
75   /// of the string.
76   unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
77   
78   /// FindKey - Look up the bucket that contains the specified key. If it exists
79   /// in the map, return the bucket number of the key.  Otherwise return -1.
80   /// This does not modify the map.
81   int FindKey(const char *KeyStart, const char *KeyEnd) const;
82
83   /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
84   /// delete it.  This aborts if the value isn't in the table.
85   void RemoveKey(StringMapEntryBase *V);
86
87   /// RemoveKey - Remove the StringMapEntry for the specified key from the
88   /// table, returning it.  If the key is not in the table, this returns null.
89   StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
90   
91 public:
92   static StringMapEntryBase *getTombstoneVal() {
93     return (StringMapEntryBase*)-1;
94   }
95   
96   unsigned getNumBuckets() const { return NumBuckets; }
97   unsigned getNumItems() const { return NumItems; }
98
99   bool empty() const { return NumItems == 0; }
100   unsigned size() const { return NumItems; }
101 };
102
103 /// StringMapEntry - This is used to represent one value that is inserted into
104 /// a StringMap.  It contains the Value itself and the key: the string length
105 /// and data.
106 template<typename ValueTy>
107 class StringMapEntry : public StringMapEntryBase {
108   ValueTy Val;
109 public:
110   StringMapEntry(unsigned StrLen)
111     : StringMapEntryBase(StrLen), Val() {}
112   StringMapEntry(unsigned StrLen, const ValueTy &V)
113     : StringMapEntryBase(StrLen), Val(V) {}
114
115   const ValueTy &getValue() const { return Val; }
116   ValueTy &getValue() { return Val; }
117   
118   void setValue(const ValueTy &V) { Val = V; }
119   
120   /// getKeyData - Return the start of the string data that is the key for this
121   /// value.  The string data is always stored immediately after the
122   /// StringMapEntry object.
123   const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
124   
125   /// Create - Create a StringMapEntry for the specified key and default
126   /// construct the value.
127   template<typename AllocatorTy>
128   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
129                                 AllocatorTy &Allocator) {
130     unsigned KeyLength = KeyEnd-KeyStart;
131     
132     // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
133     // in.  Allocate a new item with space for the string at the end and a null
134     // terminator.
135     unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
136     
137 #ifdef __GNUC__
138     unsigned Alignment = __alignof__(StringMapEntry);
139 #else
140     // FIXME: ugly.
141     unsigned Alignment = 8;
142 #endif
143     StringMapEntry *NewItem = 
144       static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize, Alignment));
145     
146     // Default construct the value.
147     new (NewItem) StringMapEntry(KeyLength);
148     
149     // Copy the string information.
150     char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
151     memcpy(StrBuffer, KeyStart, KeyLength);
152     StrBuffer[KeyLength] = 0;  // Null terminate for convenience of clients.
153     return NewItem;
154   }
155   
156   /// Create - Create a StringMapEntry with normal malloc/free.
157   static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
158     MallocAllocator A;
159     return Create(KeyStart, KeyEnd, A);
160   }
161
162   /// Destroy - Destroy this StringMapEntry, releasing memory back to the
163   /// specified allocator.
164   template<typename AllocatorTy>
165   void Destroy(AllocatorTy &Allocator) {
166     // Free memory referenced by the item.
167     this->~StringMapEntry();
168     Allocator.Deallocate(this);
169   }
170   
171   /// Destroy this object, releasing memory back to the malloc allocator.
172   void Destroy() {
173     MallocAllocator A;
174     Destroy(A);
175   }
176 };
177
178
179 /// StringMap - This is an unconventional map that is specialized for handling
180 /// keys that are "strings", which are basically ranges of bytes. This does some
181 /// funky memory allocation and hashing things to make it extremely efficient,
182 /// storing the string data *after* the value in the map.
183 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
184 class StringMap : public StringMapImpl {
185   AllocatorTy Allocator;
186   typedef StringMapEntry<ValueTy> MapEntryTy;
187 public:
188   StringMap(unsigned InitialSize = 0)
189     : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
190   
191   AllocatorTy &getAllocator() { return Allocator; }
192   const AllocatorTy &getAllocator() const { return Allocator; }
193
194   typedef StringMapConstIterator<ValueTy> const_iterator;
195   typedef StringMapIterator<ValueTy> iterator;
196   
197   iterator begin() { return iterator(TheTable); }
198   iterator end() { return iterator(TheTable+NumBuckets); }
199   const_iterator begin() const { return const_iterator(TheTable); }
200   const_iterator end() const { return const_iterator(TheTable+NumBuckets); }
201   
202   
203   iterator find(const char *KeyStart, const char *KeyEnd) {
204     int Bucket = FindKey(KeyStart, KeyEnd);
205     if (Bucket == -1) return end();
206     return iterator(TheTable+Bucket);
207   }
208
209   const_iterator find(const char *KeyStart, const char *KeyEnd) const {
210     int Bucket = FindKey(KeyStart, KeyEnd);
211     if (Bucket == -1) return end();
212     return const_iterator(TheTable+Bucket);
213   }
214   
215   /// insert - Insert the specified key/value pair into the map.  If the key
216   /// already exists in the map, return false and ignore the request, otherwise
217   /// insert it and return true.
218   bool insert(MapEntryTy *KeyValue) {
219     unsigned BucketNo =
220       LookupBucketFor(KeyValue->getKeyData(),
221                       KeyValue->getKeyData()+KeyValue->getKeyLength());
222     ItemBucket &Bucket = TheTable[BucketNo];
223     if (Bucket.Item && Bucket.Item != getTombstoneVal()) 
224       return false;  // Already exists in map.
225     
226     if (Bucket.Item == getTombstoneVal())
227       --NumTombstones;
228     Bucket.Item = KeyValue;
229     ++NumItems;
230     
231     if (ShouldRehash())
232       RehashTable();
233     return true;
234   }
235   
236   /// GetOrCreateValue - Look up the specified key in the table.  If a value
237   /// exists, return it.  Otherwise, default construct a value, insert it, and
238   /// return.
239   StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart, 
240                                             const char *KeyEnd) {
241     unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
242     ItemBucket &Bucket = TheTable[BucketNo];
243     if (Bucket.Item && Bucket.Item != getTombstoneVal())
244       return *static_cast<MapEntryTy*>(Bucket.Item);
245     
246     MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
247     
248     if (Bucket.Item == getTombstoneVal())
249       --NumTombstones;
250     ++NumItems;
251     
252     // Fill in the bucket for the hash table.  The FullHashValue was already
253     // filled in by LookupBucketFor.
254     Bucket.Item = NewItem;
255     
256     if (ShouldRehash())
257       RehashTable();
258     return *NewItem;
259   }
260   
261   /// remove - Remove the specified key/value pair from the map, but do not
262   /// erase it.  This aborts if the key is not in the map.
263   void remove(MapEntryTy *KeyValue) {
264     RemoveKey(KeyValue);
265   }
266   
267   ~StringMap() {
268     for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
269       if (I->Item && I->Item != getTombstoneVal())
270         static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
271     }
272     delete [] TheTable;
273   }
274 };
275   
276
277 template<typename ValueTy>
278 class StringMapConstIterator {
279 protected:
280   StringMapImpl::ItemBucket *Ptr;
281 public:
282   StringMapConstIterator(StringMapImpl::ItemBucket *Bucket) : Ptr(Bucket) {
283     AdvancePastEmptyBuckets();
284   }
285   
286   const StringMapEntry<ValueTy> &operator*() const {
287     return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
288   }
289   const StringMapEntry<ValueTy> *operator->() const {
290     return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
291   }
292   
293   bool operator==(const StringMapConstIterator &RHS) const {
294     return Ptr == RHS.Ptr;
295   }
296   bool operator!=(const StringMapConstIterator &RHS) const {
297     return Ptr != RHS.Ptr;
298   }
299   
300   inline StringMapConstIterator& operator++() {          // Preincrement
301     ++Ptr;
302     AdvancePastEmptyBuckets();
303     return *this;
304   }
305   StringMapConstIterator operator++(int) {        // Postincrement
306     StringMapConstIterator tmp = *this; ++*this; return tmp;
307   }
308   
309 private:
310   void AdvancePastEmptyBuckets() {
311     while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
312       ++Ptr;
313   }
314 };
315
316 template<typename ValueTy>
317 class StringMapIterator : public StringMapConstIterator<ValueTy> {
318 public:  
319   StringMapIterator(StringMapImpl::ItemBucket *Bucket)
320     : StringMapConstIterator<ValueTy>(Bucket) {
321   }
322   StringMapEntry<ValueTy> &operator*() const {
323     return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
324   }
325   StringMapEntry<ValueTy> *operator->() const {
326     return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
327   }
328 };
329
330 }
331
332 #endif
333