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 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
30 class StringMapEntryBase {
33 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
35 unsigned getKeyLength() const { return StrLen; }
38 /// StringMapImpl - This is the base class of StringMap that is shared among
39 /// all of its instantiations.
42 // Array of NumBuckets pointers to entries, null pointers are holes.
43 // TheTable[NumBuckets] contains a sentinel value for easy iteration. Followed
44 // by an array of the actual hash values as unsigned integers.
45 StringMapEntryBase **TheTable;
48 unsigned NumTombstones;
51 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
52 // Initialize the map with zero buckets to allocation.
58 StringMapImpl(unsigned InitSize, unsigned ItemSize);
61 /// LookupBucketFor - Look up the bucket that the specified string should end
62 /// up in. If it already exists as a key in the map, the Item pointer for the
63 /// specified bucket will be non-null. Otherwise, it will be null. In either
64 /// case, the FullHashValue field of the bucket will be set to the hash value
66 unsigned LookupBucketFor(StringRef Key);
68 /// FindKey - Look up the bucket that contains the specified key. If it exists
69 /// in the map, return the bucket number of the key. Otherwise return -1.
70 /// This does not modify the map.
71 int FindKey(StringRef Key) const;
73 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
74 /// delete it. This aborts if the value isn't in the table.
75 void RemoveKey(StringMapEntryBase *V);
77 /// RemoveKey - Remove the StringMapEntry for the specified key from the
78 /// table, returning it. If the key is not in the table, this returns null.
79 StringMapEntryBase *RemoveKey(StringRef Key);
81 void init(unsigned Size);
83 static StringMapEntryBase *getTombstoneVal() {
84 return (StringMapEntryBase*)-1;
87 unsigned getNumBuckets() const { return NumBuckets; }
88 unsigned getNumItems() const { return NumItems; }
90 bool empty() const { return NumItems == 0; }
91 unsigned size() const { return NumItems; }
93 void swap(StringMapImpl &Other) {
94 std::swap(TheTable, Other.TheTable);
95 std::swap(NumBuckets, Other.NumBuckets);
96 std::swap(NumItems, Other.NumItems);
97 std::swap(NumTombstones, Other.NumTombstones);
101 /// StringMapEntry - This is used to represent one value that is inserted into
102 /// a StringMap. It contains the Value itself and the key: the string length
104 template<typename ValueTy>
105 class StringMapEntry : public StringMapEntryBase {
106 StringMapEntry(StringMapEntry &E) LLVM_DELETED_FUNCTION;
110 explicit StringMapEntry(unsigned strLen)
111 : StringMapEntryBase(strLen), second() {}
112 StringMapEntry(unsigned strLen, const ValueTy &V)
113 : StringMapEntryBase(strLen), second(V) {}
115 StringRef getKey() const {
116 return StringRef(getKeyData(), getKeyLength());
119 const ValueTy &getValue() const { return second; }
120 ValueTy &getValue() { return second; }
122 void setValue(const ValueTy &V) { second = V; }
124 /// getKeyData - Return the start of the string data that is the key for this
125 /// value. The string data is always stored immediately after the
126 /// StringMapEntry object.
127 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
129 StringRef first() const { return StringRef(getKeyData(), getKeyLength()); }
131 /// Create - Create a StringMapEntry for the specified key and default
132 /// construct the value.
133 template<typename AllocatorTy, typename InitType>
134 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
135 AllocatorTy &Allocator,
137 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
139 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
140 // in. Allocate a new item with space for the string at the end and a null
143 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
145 unsigned Alignment = alignOf<StringMapEntry>();
147 StringMapEntry *NewItem =
148 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
150 // Default construct the value.
151 new (NewItem) StringMapEntry(KeyLength, InitVal);
153 // Copy the string information.
154 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
155 memcpy(StrBuffer, KeyStart, KeyLength);
156 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
160 template<typename AllocatorTy>
161 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
162 AllocatorTy &Allocator) {
163 return Create(KeyStart, KeyEnd, Allocator, 0);
166 /// Create - Create a StringMapEntry with normal malloc/free.
167 template<typename InitType>
168 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
171 return Create(KeyStart, KeyEnd, A, InitVal);
174 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
175 return Create(KeyStart, KeyEnd, ValueTy());
178 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
179 /// into a StringMapEntry, return the StringMapEntry itself.
180 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
181 StringMapEntry *EPtr = 0;
182 char *Ptr = reinterpret_cast<char*>(&V) -
183 (reinterpret_cast<char*>(&EPtr->second) -
184 reinterpret_cast<char*>(EPtr));
185 return *reinterpret_cast<StringMapEntry*>(Ptr);
187 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
188 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
191 /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
192 /// into a StringMapEntry, return the StringMapEntry itself.
193 static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
194 char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
195 return *reinterpret_cast<StringMapEntry*>(Ptr);
198 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
199 /// specified allocator.
200 template<typename AllocatorTy>
201 void Destroy(AllocatorTy &Allocator) {
202 // Free memory referenced by the item.
203 this->~StringMapEntry();
204 Allocator.Deallocate(this);
207 /// Destroy this object, releasing memory back to the malloc allocator.
215 /// StringMap - This is an unconventional map that is specialized for handling
216 /// keys that are "strings", which are basically ranges of bytes. This does some
217 /// funky memory allocation and hashing things to make it extremely efficient,
218 /// storing the string data *after* the value in the map.
219 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
220 class StringMap : public StringMapImpl {
221 AllocatorTy Allocator;
223 typedef StringMapEntry<ValueTy> MapEntryTy;
225 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
226 explicit StringMap(unsigned InitialSize)
227 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
229 explicit StringMap(AllocatorTy A)
230 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
232 StringMap(unsigned InitialSize, AllocatorTy A)
233 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))),
236 StringMap(const StringMap &RHS)
237 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
238 assert(RHS.empty() &&
239 "Copy ctor from non-empty stringmap not implemented yet!");
242 void operator=(const StringMap &RHS) {
243 assert(RHS.empty() &&
244 "assignment from non-empty stringmap not implemented yet!");
249 typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
250 typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
251 AllocatorRefTy getAllocator() { return Allocator; }
252 AllocatorCRefTy getAllocator() const { return Allocator; }
254 typedef const char* key_type;
255 typedef ValueTy mapped_type;
256 typedef StringMapEntry<ValueTy> value_type;
257 typedef size_t size_type;
259 typedef StringMapConstIterator<ValueTy> const_iterator;
260 typedef StringMapIterator<ValueTy> iterator;
263 return iterator(TheTable, NumBuckets == 0);
266 return iterator(TheTable+NumBuckets, true);
268 const_iterator begin() const {
269 return const_iterator(TheTable, NumBuckets == 0);
271 const_iterator end() const {
272 return const_iterator(TheTable+NumBuckets, true);
275 iterator find(StringRef Key) {
276 int Bucket = FindKey(Key);
277 if (Bucket == -1) return end();
278 return iterator(TheTable+Bucket, true);
281 const_iterator find(StringRef Key) const {
282 int Bucket = FindKey(Key);
283 if (Bucket == -1) return end();
284 return const_iterator(TheTable+Bucket, true);
287 /// lookup - Return the entry for the specified key, or a default
288 /// constructed value if no such entry exists.
289 ValueTy lookup(StringRef Key) const {
290 const_iterator it = find(Key);
296 ValueTy &operator[](StringRef Key) {
297 return GetOrCreateValue(Key).getValue();
300 /// count - Return 1 if the element is in the map, 0 otherwise.
301 size_type count(StringRef Key) const {
302 return find(Key) == end() ? 0 : 1;
305 /// insert - Insert the specified key/value pair into the map. If the key
306 /// already exists in the map, return false and ignore the request, otherwise
307 /// insert it and return true.
308 bool insert(MapEntryTy *KeyValue) {
309 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
310 StringMapEntryBase *&Bucket = TheTable[BucketNo];
311 if (Bucket && Bucket != getTombstoneVal())
312 return false; // Already exists in map.
314 if (Bucket == getTombstoneVal())
318 assert(NumItems + NumTombstones <= NumBuckets);
324 // clear - Empties out the StringMap
328 // Zap all values, resetting the keys back to non-present (not tombstone),
329 // which is safe because we're removing all elements.
330 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
331 StringMapEntryBase *&Bucket = TheTable[I];
332 if (Bucket && Bucket != getTombstoneVal()) {
333 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
342 /// GetOrCreateValue - Look up the specified key in the table. If a value
343 /// exists, return it. Otherwise, default construct a value, insert it, and
345 template <typename InitTy>
346 MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
347 unsigned BucketNo = LookupBucketFor(Key);
348 StringMapEntryBase *&Bucket = TheTable[BucketNo];
349 if (Bucket && Bucket != getTombstoneVal())
350 return *static_cast<MapEntryTy*>(Bucket);
352 MapEntryTy *NewItem =
353 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
355 if (Bucket == getTombstoneVal())
358 assert(NumItems + NumTombstones <= NumBuckets);
360 // Fill in the bucket for the hash table. The FullHashValue was already
361 // filled in by LookupBucketFor.
368 MapEntryTy &GetOrCreateValue(StringRef Key) {
369 return GetOrCreateValue(Key, ValueTy());
372 /// remove - Remove the specified key/value pair from the map, but do not
373 /// erase it. This aborts if the key is not in the map.
374 void remove(MapEntryTy *KeyValue) {
378 void erase(iterator I) {
381 V.Destroy(Allocator);
384 bool erase(StringRef Key) {
385 iterator I = find(Key);
386 if (I == end()) return false;
398 template<typename ValueTy>
399 class StringMapConstIterator {
401 StringMapEntryBase **Ptr;
403 typedef StringMapEntry<ValueTy> value_type;
405 StringMapConstIterator() : Ptr(0) { }
407 explicit StringMapConstIterator(StringMapEntryBase **Bucket,
408 bool NoAdvance = false)
410 if (!NoAdvance) AdvancePastEmptyBuckets();
413 const value_type &operator*() const {
414 return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
416 const value_type *operator->() const {
417 return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
420 bool operator==(const StringMapConstIterator &RHS) const {
421 return Ptr == RHS.Ptr;
423 bool operator!=(const StringMapConstIterator &RHS) const {
424 return Ptr != RHS.Ptr;
427 inline StringMapConstIterator& operator++() { // Preincrement
429 AdvancePastEmptyBuckets();
432 StringMapConstIterator operator++(int) { // Postincrement
433 StringMapConstIterator tmp = *this; ++*this; return tmp;
437 void AdvancePastEmptyBuckets() {
438 while (*Ptr == 0 || *Ptr == StringMapImpl::getTombstoneVal())
443 template<typename ValueTy>
444 class StringMapIterator : public StringMapConstIterator<ValueTy> {
446 StringMapIterator() {}
447 explicit StringMapIterator(StringMapEntryBase **Bucket,
448 bool NoAdvance = false)
449 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
451 StringMapEntry<ValueTy> &operator*() const {
452 return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
454 StringMapEntry<ValueTy> *operator->() const {
455 return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);