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"
23 template<typename ValueT>
24 class StringMapConstIterator;
25 template<typename ValueT>
26 class StringMapIterator;
27 template<typename ValueTy>
30 /// StringMapEntryInitializer - This datatype can be partially specialized for
31 /// various datatypes in a stringmap to allow them to be initialized when an
32 /// entry is default constructed for the map.
33 template<typename ValueTy>
34 class StringMapEntryInitializer {
36 template <typename InitTy>
37 static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
43 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
44 class StringMapEntryBase {
47 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
49 unsigned getKeyLength() const { return StrLen; }
52 /// StringMapImpl - This is the base class of StringMap that is shared among
53 /// all of its instantiations.
56 /// ItemBucket - The hash table consists of an array of these. If Item is
57 /// non-null, this is an extant entry, otherwise, it is a hole.
59 /// FullHashValue - This remembers the full hash value of the key for
61 unsigned FullHashValue;
63 /// Item - This is a pointer to the actual item object.
64 StringMapEntryBase *Item;
71 unsigned NumTombstones;
74 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
75 // Initialize the map with zero buckets to allocation.
81 StringMapImpl(unsigned InitSize, unsigned ItemSize);
84 /// LookupBucketFor - Look up the bucket that the specified string should end
85 /// up in. If it already exists as a key in the map, the Item pointer for the
86 /// specified bucket will be non-null. Otherwise, it will be null. In either
87 /// case, the FullHashValue field of the bucket will be set to the hash value
89 unsigned LookupBucketFor(StringRef Key);
91 /// FindKey - Look up the bucket that contains the specified key. If it exists
92 /// in the map, return the bucket number of the key. Otherwise return -1.
93 /// This does not modify the map.
94 int FindKey(StringRef Key) const;
96 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
97 /// delete it. This aborts if the value isn't in the table.
98 void RemoveKey(StringMapEntryBase *V);
100 /// RemoveKey - Remove the StringMapEntry for the specified key from the
101 /// table, returning it. If the key is not in the table, this returns null.
102 StringMapEntryBase *RemoveKey(StringRef Key);
104 void init(unsigned Size);
106 static StringMapEntryBase *getTombstoneVal() {
107 return (StringMapEntryBase*)-1;
110 unsigned getNumBuckets() const { return NumBuckets; }
111 unsigned getNumItems() const { return NumItems; }
113 bool empty() const { return NumItems == 0; }
114 unsigned size() const { return NumItems; }
117 /// StringMapEntry - This is used to represent one value that is inserted into
118 /// a StringMap. It contains the Value itself and the key: the string length
120 template<typename ValueTy>
121 class StringMapEntry : public StringMapEntryBase {
125 explicit StringMapEntry(unsigned strLen)
126 : StringMapEntryBase(strLen), second() {}
127 StringMapEntry(unsigned strLen, const ValueTy &V)
128 : StringMapEntryBase(strLen), second(V) {}
130 StringRef getKey() const {
131 return StringRef(getKeyData(), getKeyLength());
134 const ValueTy &getValue() const { return second; }
135 ValueTy &getValue() { return second; }
137 void setValue(const ValueTy &V) { second = V; }
139 /// getKeyData - Return the start of the string data that is the key for this
140 /// value. The string data is always stored immediately after the
141 /// StringMapEntry object.
142 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
144 const char *first() const { return getKeyData(); }
146 /// Create - Create a StringMapEntry for the specified key and default
147 /// construct the value.
148 template<typename AllocatorTy, typename InitType>
149 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
150 AllocatorTy &Allocator,
152 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
154 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
155 // in. Allocate a new item with space for the string at the end and a null
158 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
160 unsigned Alignment = alignOf<StringMapEntry>();
162 StringMapEntry *NewItem =
163 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
165 // Default construct the value.
166 new (NewItem) StringMapEntry(KeyLength);
168 // Copy the string information.
169 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
170 memcpy(StrBuffer, KeyStart, KeyLength);
171 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
173 // Initialize the value if the client wants to.
174 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
178 template<typename AllocatorTy>
179 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
180 AllocatorTy &Allocator) {
181 return Create(KeyStart, KeyEnd, Allocator, 0);
185 /// Create - Create a StringMapEntry with normal malloc/free.
186 template<typename InitType>
187 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
190 return Create(KeyStart, KeyEnd, A, InitVal);
193 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
194 return Create(KeyStart, KeyEnd, ValueTy());
197 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
198 /// into a StringMapEntry, return the StringMapEntry itself.
199 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
200 StringMapEntry *EPtr = 0;
201 char *Ptr = reinterpret_cast<char*>(&V) -
202 (reinterpret_cast<char*>(&EPtr->second) -
203 reinterpret_cast<char*>(EPtr));
204 return *reinterpret_cast<StringMapEntry*>(Ptr);
206 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
207 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
210 /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
211 /// into a StringMapEntry, return the StringMapEntry itself.
212 static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
213 char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
214 return *reinterpret_cast<StringMapEntry*>(Ptr);
218 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
219 /// specified allocator.
220 template<typename AllocatorTy>
221 void Destroy(AllocatorTy &Allocator) {
222 // Free memory referenced by the item.
223 this->~StringMapEntry();
224 Allocator.Deallocate(this);
227 /// Destroy this object, releasing memory back to the malloc allocator.
235 /// StringMap - This is an unconventional map that is specialized for handling
236 /// keys that are "strings", which are basically ranges of bytes. This does some
237 /// funky memory allocation and hashing things to make it extremely efficient,
238 /// storing the string data *after* the value in the map.
239 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
240 class StringMap : public StringMapImpl {
241 AllocatorTy Allocator;
242 typedef StringMapEntry<ValueTy> MapEntryTy;
244 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
245 explicit StringMap(unsigned InitialSize)
246 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
248 explicit StringMap(AllocatorTy A)
249 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
251 explicit StringMap(const StringMap &RHS)
252 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
253 assert(RHS.empty() &&
254 "Copy ctor from non-empty stringmap not implemented yet!");
257 void operator=(const StringMap &RHS) {
258 assert(RHS.empty() &&
259 "assignment from non-empty stringmap not implemented yet!");
264 typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
265 typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
266 AllocatorRefTy getAllocator() { return Allocator; }
267 AllocatorCRefTy getAllocator() const { return Allocator; }
269 typedef const char* key_type;
270 typedef ValueTy mapped_type;
271 typedef StringMapEntry<ValueTy> value_type;
272 typedef size_t size_type;
274 typedef StringMapConstIterator<ValueTy> const_iterator;
275 typedef StringMapIterator<ValueTy> iterator;
278 return iterator(TheTable, NumBuckets == 0);
281 return iterator(TheTable+NumBuckets, true);
283 const_iterator begin() const {
284 return const_iterator(TheTable, NumBuckets == 0);
286 const_iterator end() const {
287 return const_iterator(TheTable+NumBuckets, true);
290 iterator find(StringRef Key) {
291 int Bucket = FindKey(Key);
292 if (Bucket == -1) return end();
293 return iterator(TheTable+Bucket);
296 const_iterator find(StringRef Key) const {
297 int Bucket = FindKey(Key);
298 if (Bucket == -1) return end();
299 return const_iterator(TheTable+Bucket);
302 /// lookup - Return the entry for the specified key, or a default
303 /// constructed value if no such entry exists.
304 ValueTy lookup(StringRef Key) const {
305 const_iterator it = find(Key);
311 ValueTy& operator[](StringRef Key) {
312 return GetOrCreateValue(Key).getValue();
315 size_type count(StringRef Key) const {
316 return find(Key) == end() ? 0 : 1;
319 /// insert - Insert the specified key/value pair into the map. If the key
320 /// already exists in the map, return false and ignore the request, otherwise
321 /// insert it and return true.
322 bool insert(MapEntryTy *KeyValue) {
323 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
324 ItemBucket &Bucket = TheTable[BucketNo];
325 if (Bucket.Item && Bucket.Item != getTombstoneVal())
326 return false; // Already exists in map.
328 if (Bucket.Item == getTombstoneVal())
330 Bucket.Item = KeyValue;
332 assert(NumItems + NumTombstones <= NumBuckets);
338 // clear - Empties out the StringMap
342 // Zap all values, resetting the keys back to non-present (not tombstone),
343 // which is safe because we're removing all elements.
344 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
345 if (I->Item && I->Item != getTombstoneVal()) {
346 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
355 /// GetOrCreateValue - Look up the specified key in the table. If a value
356 /// exists, return it. Otherwise, default construct a value, insert it, and
358 template <typename InitTy>
359 StringMapEntry<ValueTy> &GetOrCreateValue(StringRef Key,
361 unsigned BucketNo = LookupBucketFor(Key);
362 ItemBucket &Bucket = TheTable[BucketNo];
363 if (Bucket.Item && Bucket.Item != getTombstoneVal())
364 return *static_cast<MapEntryTy*>(Bucket.Item);
366 MapEntryTy *NewItem =
367 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
369 if (Bucket.Item == getTombstoneVal())
372 assert(NumItems + NumTombstones <= NumBuckets);
374 // Fill in the bucket for the hash table. The FullHashValue was already
375 // filled in by LookupBucketFor.
376 Bucket.Item = NewItem;
382 StringMapEntry<ValueTy> &GetOrCreateValue(StringRef Key) {
383 return GetOrCreateValue(Key, ValueTy());
386 template <typename InitTy>
387 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
390 return GetOrCreateValue(StringRef(KeyStart, KeyEnd - KeyStart), Val);
393 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
394 const char *KeyEnd) {
395 return GetOrCreateValue(StringRef(KeyStart, KeyEnd - KeyStart));
398 /// remove - Remove the specified key/value pair from the map, but do not
399 /// erase it. This aborts if the key is not in the map.
400 void remove(MapEntryTy *KeyValue) {
404 void erase(iterator I) {
407 V.Destroy(Allocator);
410 bool erase(StringRef Key) {
411 iterator I = find(Key);
412 if (I == end()) return false;
424 template<typename ValueTy>
425 class StringMapConstIterator {
427 StringMapImpl::ItemBucket *Ptr;
429 typedef StringMapEntry<ValueTy> value_type;
431 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
432 bool NoAdvance = false)
434 if (!NoAdvance) AdvancePastEmptyBuckets();
437 const value_type &operator*() const {
438 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
440 const value_type *operator->() const {
441 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
444 bool operator==(const StringMapConstIterator &RHS) const {
445 return Ptr == RHS.Ptr;
447 bool operator!=(const StringMapConstIterator &RHS) const {
448 return Ptr != RHS.Ptr;
451 inline StringMapConstIterator& operator++() { // Preincrement
453 AdvancePastEmptyBuckets();
456 StringMapConstIterator operator++(int) { // Postincrement
457 StringMapConstIterator tmp = *this; ++*this; return tmp;
461 void AdvancePastEmptyBuckets() {
462 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
467 template<typename ValueTy>
468 class StringMapIterator : public StringMapConstIterator<ValueTy> {
470 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
471 bool NoAdvance = false)
472 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
474 StringMapEntry<ValueTy> &operator*() const {
475 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
477 StringMapEntry<ValueTy> *operator->() const {
478 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);