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 /// StringMapEntryInitializer - This datatype can be partially specialized for
30 /// various datatypes in a stringmap to allow them to be initialized when an
31 /// entry is default constructed for the map.
32 template<typename ValueTy>
33 class StringMapEntryInitializer {
35 template <typename InitTy>
36 static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
42 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
43 class StringMapEntryBase {
46 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
48 unsigned getKeyLength() const { return StrLen; }
51 /// StringMapImpl - This is the base class of StringMap that is shared among
52 /// all of its instantiations.
55 /// ItemBucket - The hash table consists of an array of these. If Item is
56 /// non-null, this is an extant entry, otherwise, it is a hole.
58 /// FullHashValue - This remembers the full hash value of the key for
60 unsigned FullHashValue;
62 /// Item - This is a pointer to the actual item object.
63 StringMapEntryBase *Item;
70 unsigned NumTombstones;
73 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
74 // Initialize the map with zero buckets to allocation.
80 StringMapImpl(unsigned InitSize, unsigned ItemSize);
83 /// LookupBucketFor - Look up the bucket that the specified string should end
84 /// up in. If it already exists as a key in the map, the Item pointer for the
85 /// specified bucket will be non-null. Otherwise, it will be null. In either
86 /// case, the FullHashValue field of the bucket will be set to the hash value
88 unsigned LookupBucketFor(StringRef Key);
90 /// FindKey - Look up the bucket that contains the specified key. If it exists
91 /// in the map, return the bucket number of the key. Otherwise return -1.
92 /// This does not modify the map.
93 int FindKey(StringRef Key) const;
95 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
96 /// delete it. This aborts if the value isn't in the table.
97 void RemoveKey(StringMapEntryBase *V);
99 /// RemoveKey - Remove the StringMapEntry for the specified key from the
100 /// table, returning it. If the key is not in the table, this returns null.
101 StringMapEntryBase *RemoveKey(StringRef Key);
103 void init(unsigned Size);
105 static StringMapEntryBase *getTombstoneVal() {
106 return (StringMapEntryBase*)-1;
109 unsigned getNumBuckets() const { return NumBuckets; }
110 unsigned getNumItems() const { return NumItems; }
112 bool empty() const { return NumItems == 0; }
113 unsigned size() const { return NumItems; }
116 /// StringMapEntry - This is used to represent one value that is inserted into
117 /// a StringMap. It contains the Value itself and the key: the string length
119 template<typename ValueTy>
120 class StringMapEntry : public StringMapEntryBase {
124 explicit StringMapEntry(unsigned strLen)
125 : StringMapEntryBase(strLen), second() {}
126 StringMapEntry(unsigned strLen, const ValueTy &V)
127 : StringMapEntryBase(strLen), second(V) {}
129 StringRef getKey() const {
130 return StringRef(getKeyData(), getKeyLength());
133 const ValueTy &getValue() const { return second; }
134 ValueTy &getValue() { return second; }
136 void setValue(const ValueTy &V) { second = V; }
138 /// getKeyData - Return the start of the string data that is the key for this
139 /// value. The string data is always stored immediately after the
140 /// StringMapEntry object.
141 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
143 const char *first() const { return getKeyData(); }
145 /// Create - Create a StringMapEntry for the specified key and default
146 /// construct the value.
147 template<typename AllocatorTy, typename InitType>
148 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
149 AllocatorTy &Allocator,
151 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
153 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
154 // in. Allocate a new item with space for the string at the end and a null
157 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
159 unsigned Alignment = alignOf<StringMapEntry>();
161 StringMapEntry *NewItem =
162 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
164 // Default construct the value.
165 new (NewItem) StringMapEntry(KeyLength);
167 // Copy the string information.
168 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
169 memcpy(StrBuffer, KeyStart, KeyLength);
170 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
172 // Initialize the value if the client wants to.
173 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
177 template<typename AllocatorTy>
178 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
179 AllocatorTy &Allocator) {
180 return Create(KeyStart, KeyEnd, Allocator, 0);
184 /// Create - Create a StringMapEntry with normal malloc/free.
185 template<typename InitType>
186 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
189 return Create(KeyStart, KeyEnd, A, InitVal);
192 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
193 return Create(KeyStart, KeyEnd, ValueTy());
196 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
197 /// into a StringMapEntry, return the StringMapEntry itself.
198 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
199 StringMapEntry *EPtr = 0;
200 char *Ptr = reinterpret_cast<char*>(&V) -
201 (reinterpret_cast<char*>(&EPtr->second) -
202 reinterpret_cast<char*>(EPtr));
203 return *reinterpret_cast<StringMapEntry*>(Ptr);
205 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
206 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
209 /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
210 /// into a StringMapEntry, return the StringMapEntry itself.
211 static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
212 char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
213 return *reinterpret_cast<StringMapEntry*>(Ptr);
217 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
218 /// specified allocator.
219 template<typename AllocatorTy>
220 void Destroy(AllocatorTy &Allocator) {
221 // Free memory referenced by the item.
222 this->~StringMapEntry();
223 Allocator.Deallocate(this);
226 /// Destroy this object, releasing memory back to the malloc allocator.
234 /// StringMap - This is an unconventional map that is specialized for handling
235 /// keys that are "strings", which are basically ranges of bytes. This does some
236 /// funky memory allocation and hashing things to make it extremely efficient,
237 /// storing the string data *after* the value in the map.
238 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
239 class StringMap : public StringMapImpl {
240 AllocatorTy Allocator;
241 typedef StringMapEntry<ValueTy> MapEntryTy;
243 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
244 explicit StringMap(unsigned InitialSize)
245 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
247 explicit StringMap(AllocatorTy A)
248 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
250 explicit StringMap(const StringMap &RHS)
251 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
252 assert(RHS.empty() &&
253 "Copy ctor from non-empty stringmap not implemented yet!");
256 void operator=(const StringMap &RHS) {
257 assert(RHS.empty() &&
258 "assignment from non-empty stringmap not implemented yet!");
263 typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
264 typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
265 AllocatorRefTy getAllocator() { return Allocator; }
266 AllocatorCRefTy getAllocator() const { return Allocator; }
268 typedef const char* key_type;
269 typedef ValueTy mapped_type;
270 typedef StringMapEntry<ValueTy> value_type;
271 typedef size_t size_type;
273 typedef StringMapConstIterator<ValueTy> const_iterator;
274 typedef StringMapIterator<ValueTy> iterator;
277 return iterator(TheTable, NumBuckets == 0);
280 return iterator(TheTable+NumBuckets, true);
282 const_iterator begin() const {
283 return const_iterator(TheTable, NumBuckets == 0);
285 const_iterator end() const {
286 return const_iterator(TheTable+NumBuckets, true);
289 iterator find(StringRef Key) {
290 int Bucket = FindKey(Key);
291 if (Bucket == -1) return end();
292 return iterator(TheTable+Bucket);
295 const_iterator find(StringRef Key) const {
296 int Bucket = FindKey(Key);
297 if (Bucket == -1) return end();
298 return const_iterator(TheTable+Bucket);
301 /// lookup - Return the entry for the specified key, or a default
302 /// constructed value if no such entry exists.
303 ValueTy lookup(StringRef Key) const {
304 const_iterator it = find(Key);
310 ValueTy &operator[](StringRef Key) {
311 return GetOrCreateValue(Key).getValue();
314 size_type count(StringRef Key) const {
315 return find(Key) == end() ? 0 : 1;
318 /// insert - Insert the specified key/value pair into the map. If the key
319 /// already exists in the map, return false and ignore the request, otherwise
320 /// insert it and return true.
321 bool insert(MapEntryTy *KeyValue) {
322 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
323 ItemBucket &Bucket = TheTable[BucketNo];
324 if (Bucket.Item && Bucket.Item != getTombstoneVal())
325 return false; // Already exists in map.
327 if (Bucket.Item == getTombstoneVal())
329 Bucket.Item = KeyValue;
331 assert(NumItems + NumTombstones <= NumBuckets);
337 // clear - Empties out the StringMap
341 // Zap all values, resetting the keys back to non-present (not tombstone),
342 // which is safe because we're removing all elements.
343 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
344 if (I->Item && I->Item != getTombstoneVal()) {
345 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
354 /// GetOrCreateValue - Look up the specified key in the table. If a value
355 /// exists, return it. Otherwise, default construct a value, insert it, and
357 template <typename InitTy>
358 MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
359 unsigned BucketNo = LookupBucketFor(Key);
360 ItemBucket &Bucket = TheTable[BucketNo];
361 if (Bucket.Item && Bucket.Item != getTombstoneVal())
362 return *static_cast<MapEntryTy*>(Bucket.Item);
364 MapEntryTy *NewItem =
365 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
367 if (Bucket.Item == getTombstoneVal())
370 assert(NumItems + NumTombstones <= NumBuckets);
372 // Fill in the bucket for the hash table. The FullHashValue was already
373 // filled in by LookupBucketFor.
374 Bucket.Item = NewItem;
380 MapEntryTy &GetOrCreateValue(StringRef Key) {
381 return GetOrCreateValue(Key, ValueTy());
384 /// remove - Remove the specified key/value pair from the map, but do not
385 /// erase it. This aborts if the key is not in the map.
386 void remove(MapEntryTy *KeyValue) {
390 void erase(iterator I) {
393 V.Destroy(Allocator);
396 bool erase(StringRef Key) {
397 iterator I = find(Key);
398 if (I == end()) return false;
410 template<typename ValueTy>
411 class StringMapConstIterator {
413 StringMapImpl::ItemBucket *Ptr;
415 typedef StringMapEntry<ValueTy> value_type;
417 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
418 bool NoAdvance = false)
420 if (!NoAdvance) AdvancePastEmptyBuckets();
423 const value_type &operator*() const {
424 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
426 const value_type *operator->() const {
427 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
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->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
453 template<typename ValueTy>
454 class StringMapIterator : public StringMapConstIterator<ValueTy> {
456 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
457 bool NoAdvance = false)
458 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
460 StringMapEntry<ValueTy> &operator*() const {
461 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
463 StringMapEntry<ValueTy> *operator->() const {
464 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);