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