StringMap.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. //===--- StringMap.cpp - String Hash table map implementation -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the StringMap class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/StringMap.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/Support/Compiler.h"
  16. #include "llvm/Support/MathExtras.h"
  17. #include <cassert>
  18. using namespace llvm;
  19. /// Returns the number of buckets to allocate to ensure that the DenseMap can
  20. /// accommodate \p NumEntries without need to grow().
  21. static unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
  22. // Ensure that "NumEntries * 4 < NumBuckets * 3"
  23. if (NumEntries == 0)
  24. return 0;
  25. // +1 is required because of the strict equality.
  26. // For example if NumEntries is 48, we need to return 401.
  27. return NextPowerOf2(NumEntries * 4 / 3 + 1);
  28. }
  29. StringMapImpl::StringMapImpl(unsigned InitSize, unsigned itemSize) {
  30. ItemSize = itemSize;
  31. // If a size is specified, initialize the table with that many buckets.
  32. if (InitSize) {
  33. // The table will grow when the number of entries reach 3/4 of the number of
  34. // buckets. To guarantee that "InitSize" number of entries can be inserted
  35. // in the table without growing, we allocate just what is needed here.
  36. init(getMinBucketToReserveForEntries(InitSize));
  37. return;
  38. }
  39. // Otherwise, initialize it with zero buckets to avoid the allocation.
  40. TheTable = nullptr;
  41. NumBuckets = 0;
  42. NumItems = 0;
  43. NumTombstones = 0;
  44. }
  45. void StringMapImpl::init(unsigned InitSize) {
  46. assert((InitSize & (InitSize-1)) == 0 &&
  47. "Init Size must be a power of 2 or zero!");
  48. unsigned NewNumBuckets = InitSize ? InitSize : 16;
  49. NumItems = 0;
  50. NumTombstones = 0;
  51. TheTable = (StringMapEntryBase **)calloc(NewNumBuckets+1,
  52. sizeof(StringMapEntryBase **) +
  53. sizeof(unsigned));
  54. if (TheTable == nullptr)
  55. report_bad_alloc_error("Allocation of StringMap table failed.");
  56. // Set the member only if TheTable was successfully allocated
  57. NumBuckets = NewNumBuckets;
  58. // Allocate one extra bucket, set it to look filled so the iterators stop at
  59. // end.
  60. TheTable[NumBuckets] = (StringMapEntryBase*)2;
  61. }
  62. /// LookupBucketFor - Look up the bucket that the specified string should end
  63. /// up in. If it already exists as a key in the map, the Item pointer for the
  64. /// specified bucket will be non-null. Otherwise, it will be null. In either
  65. /// case, the FullHashValue field of the bucket will be set to the hash value
  66. /// of the string.
  67. unsigned StringMapImpl::LookupBucketFor(StringRef Name) {
  68. unsigned HTSize = NumBuckets;
  69. if (HTSize == 0) { // Hash table unallocated so far?
  70. init(16);
  71. HTSize = NumBuckets;
  72. }
  73. unsigned FullHashValue = HashString(Name);
  74. unsigned BucketNo = FullHashValue & (HTSize-1);
  75. unsigned *HashTable = (unsigned *)(TheTable + NumBuckets + 1);
  76. unsigned ProbeAmt = 1;
  77. int FirstTombstone = -1;
  78. while (true) {
  79. StringMapEntryBase *BucketItem = TheTable[BucketNo];
  80. // If we found an empty bucket, this key isn't in the table yet, return it.
  81. if (LLVM_LIKELY(!BucketItem)) {
  82. // If we found a tombstone, we want to reuse the tombstone instead of an
  83. // empty bucket. This reduces probing.
  84. if (FirstTombstone != -1) {
  85. HashTable[FirstTombstone] = FullHashValue;
  86. return FirstTombstone;
  87. }
  88. HashTable[BucketNo] = FullHashValue;
  89. return BucketNo;
  90. }
  91. if (BucketItem == getTombstoneVal()) {
  92. // Skip over tombstones. However, remember the first one we see.
  93. if (FirstTombstone == -1) FirstTombstone = BucketNo;
  94. } else if (LLVM_LIKELY(HashTable[BucketNo] == FullHashValue)) {
  95. // If the full hash value matches, check deeply for a match. The common
  96. // case here is that we are only looking at the buckets (for item info
  97. // being non-null and for the full hash value) not at the items. This
  98. // is important for cache locality.
  99. // Do the comparison like this because Name isn't necessarily
  100. // null-terminated!
  101. char *ItemStr = (char*)BucketItem+ItemSize;
  102. if (Name == StringRef(ItemStr, BucketItem->getKeyLength())) {
  103. // We found a match!
  104. return BucketNo;
  105. }
  106. }
  107. // Okay, we didn't find the item. Probe to the next bucket.
  108. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1);
  109. // Use quadratic probing, it has fewer clumping artifacts than linear
  110. // probing and has good cache behavior in the common case.
  111. ++ProbeAmt;
  112. }
  113. }
  114. /// FindKey - Look up the bucket that contains the specified key. If it exists
  115. /// in the map, return the bucket number of the key. Otherwise return -1.
  116. /// This does not modify the map.
  117. int StringMapImpl::FindKey(StringRef Key) const {
  118. unsigned HTSize = NumBuckets;
  119. if (HTSize == 0) return -1; // Really empty table?
  120. unsigned FullHashValue = HashString(Key);
  121. unsigned BucketNo = FullHashValue & (HTSize-1);
  122. unsigned *HashTable = (unsigned *)(TheTable + NumBuckets + 1);
  123. unsigned ProbeAmt = 1;
  124. while (true) {
  125. StringMapEntryBase *BucketItem = TheTable[BucketNo];
  126. // If we found an empty bucket, this key isn't in the table yet, return.
  127. if (LLVM_LIKELY(!BucketItem))
  128. return -1;
  129. if (BucketItem == getTombstoneVal()) {
  130. // Ignore tombstones.
  131. } else if (LLVM_LIKELY(HashTable[BucketNo] == FullHashValue)) {
  132. // If the full hash value matches, check deeply for a match. The common
  133. // case here is that we are only looking at the buckets (for item info
  134. // being non-null and for the full hash value) not at the items. This
  135. // is important for cache locality.
  136. // Do the comparison like this because NameStart isn't necessarily
  137. // null-terminated!
  138. char *ItemStr = (char*)BucketItem+ItemSize;
  139. if (Key == StringRef(ItemStr, BucketItem->getKeyLength())) {
  140. // We found a match!
  141. return BucketNo;
  142. }
  143. }
  144. // Okay, we didn't find the item. Probe to the next bucket.
  145. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1);
  146. // Use quadratic probing, it has fewer clumping artifacts than linear
  147. // probing and has good cache behavior in the common case.
  148. ++ProbeAmt;
  149. }
  150. }
  151. /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
  152. /// delete it. This aborts if the value isn't in the table.
  153. void StringMapImpl::RemoveKey(StringMapEntryBase *V) {
  154. const char *VStr = (char*)V + ItemSize;
  155. StringMapEntryBase *V2 = RemoveKey(StringRef(VStr, V->getKeyLength()));
  156. (void)V2;
  157. assert(V == V2 && "Didn't find key?");
  158. }
  159. /// RemoveKey - Remove the StringMapEntry for the specified key from the
  160. /// table, returning it. If the key is not in the table, this returns null.
  161. StringMapEntryBase *StringMapImpl::RemoveKey(StringRef Key) {
  162. int Bucket = FindKey(Key);
  163. if (Bucket == -1) return nullptr;
  164. StringMapEntryBase *Result = TheTable[Bucket];
  165. TheTable[Bucket] = getTombstoneVal();
  166. --NumItems;
  167. ++NumTombstones;
  168. assert(NumItems + NumTombstones <= NumBuckets);
  169. return Result;
  170. }
  171. /// RehashTable - Grow the table, redistributing values into the buckets with
  172. /// the appropriate mod-of-hashtable-size.
  173. unsigned StringMapImpl::RehashTable(unsigned BucketNo) {
  174. unsigned NewSize;
  175. unsigned *HashTable = (unsigned *)(TheTable + NumBuckets + 1);
  176. // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
  177. // the buckets are empty (meaning that many are filled with tombstones),
  178. // grow/rehash the table.
  179. if (LLVM_UNLIKELY(NumItems * 4 > NumBuckets * 3)) {
  180. NewSize = NumBuckets*2;
  181. } else if (LLVM_UNLIKELY(NumBuckets - (NumItems + NumTombstones) <=
  182. NumBuckets / 8)) {
  183. NewSize = NumBuckets;
  184. } else {
  185. return BucketNo;
  186. }
  187. unsigned NewBucketNo = BucketNo;
  188. // Allocate one extra bucket which will always be non-empty. This allows the
  189. // iterators to stop at end.
  190. StringMapEntryBase **NewTableArray =
  191. (StringMapEntryBase **)calloc(NewSize+1, sizeof(StringMapEntryBase *) +
  192. sizeof(unsigned));
  193. if (NewTableArray == nullptr)
  194. report_bad_alloc_error("Allocation of StringMap hash table failed.");
  195. unsigned *NewHashArray = (unsigned *)(NewTableArray + NewSize + 1);
  196. NewTableArray[NewSize] = (StringMapEntryBase*)2;
  197. // Rehash all the items into their new buckets. Luckily :) we already have
  198. // the hash values available, so we don't have to rehash any strings.
  199. for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
  200. StringMapEntryBase *Bucket = TheTable[I];
  201. if (Bucket && Bucket != getTombstoneVal()) {
  202. // Fast case, bucket available.
  203. unsigned FullHash = HashTable[I];
  204. unsigned NewBucket = FullHash & (NewSize-1);
  205. if (!NewTableArray[NewBucket]) {
  206. NewTableArray[FullHash & (NewSize-1)] = Bucket;
  207. NewHashArray[FullHash & (NewSize-1)] = FullHash;
  208. if (I == BucketNo)
  209. NewBucketNo = NewBucket;
  210. continue;
  211. }
  212. // Otherwise probe for a spot.
  213. unsigned ProbeSize = 1;
  214. do {
  215. NewBucket = (NewBucket + ProbeSize++) & (NewSize-1);
  216. } while (NewTableArray[NewBucket]);
  217. // Finally found a slot. Fill it in.
  218. NewTableArray[NewBucket] = Bucket;
  219. NewHashArray[NewBucket] = FullHash;
  220. if (I == BucketNo)
  221. NewBucketNo = NewBucket;
  222. }
  223. }
  224. free(TheTable);
  225. TheTable = NewTableArray;
  226. NumBuckets = NewSize;
  227. NumTombstones = 0;
  228. return NewBucketNo;
  229. }