FoldingSet.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
  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 a hash set that can be used to remove duplication of
  11. // nodes in a graph. This code was originally created by Chris Lattner for use
  12. // with SelectionDAGCSEMap, but was isolated to provide use across the llvm code
  13. // set.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/Support/ErrorHandling.h"
  18. #include "llvm/Support/MathExtras.h"
  19. #include <cassert>
  20. #include <cstring>
  21. using namespace llvm;
  22. //===----------------------------------------------------------------------===//
  23. // FoldingSetNodeID Implementation
  24. /// Add* - Add various data types to Bit data.
  25. ///
  26. void FoldingSetNodeID::AddPointer(const void *Ptr) {
  27. // Note: this adds pointers to the hash using sizes and endianness that
  28. // depend on the host. It doesn't matter however, because hashing on
  29. // pointer values in inherently unstable. Nothing should depend on the
  30. // ordering of nodes in the folding set.
  31. intptr_t PtrI = (intptr_t)Ptr;
  32. Bits.push_back(unsigned(PtrI));
  33. if (sizeof(intptr_t) > sizeof(unsigned))
  34. Bits.push_back(unsigned(uint64_t(PtrI) >> 32));
  35. }
  36. void FoldingSetNodeID::AddInteger(signed I) {
  37. Bits.push_back(I);
  38. }
  39. void FoldingSetNodeID::AddInteger(unsigned I) {
  40. Bits.push_back(I);
  41. }
  42. void FoldingSetNodeID::AddInteger(long I) {
  43. AddInteger((unsigned long)I);
  44. }
  45. void FoldingSetNodeID::AddInteger(unsigned long I) {
  46. if (sizeof(long) == sizeof(int))
  47. AddInteger(unsigned(I));
  48. else if (sizeof(long) == sizeof(long long)) {
  49. AddInteger((unsigned long long)I);
  50. } else {
  51. LLVM_UNREACHABLE("unexpected sizeof(long)");
  52. }
  53. }
  54. void FoldingSetNodeID::AddInteger(long long I) {
  55. AddInteger((unsigned long long)I);
  56. }
  57. void FoldingSetNodeID::AddInteger(unsigned long long I) {
  58. AddInteger(unsigned(I));
  59. if ((uint64_t)(int)I != I)
  60. Bits.push_back(unsigned(I >> 32));
  61. }
  62. void FoldingSetNodeID::AddString(const char *String, const char *End) {
  63. unsigned Size = static_cast<unsigned>(End - String);
  64. Bits.push_back(Size);
  65. if (!Size) return;
  66. unsigned Units = Size / 4;
  67. unsigned Pos = 0;
  68. const unsigned *Base = (const unsigned *)String;
  69. // If the string is aligned do a bulk transfer.
  70. if (!((intptr_t)Base & 3)) {
  71. Bits.append(Base, Base + Units);
  72. Pos = (Units + 1) * 4;
  73. } else {
  74. // Otherwise do it the hard way.
  75. for (Pos += 4; Pos <= Size; Pos += 4) {
  76. unsigned V = ((unsigned char)String[Pos - 4] << 24) |
  77. ((unsigned char)String[Pos - 3] << 16) |
  78. ((unsigned char)String[Pos - 2] << 8) |
  79. (unsigned char)String[Pos - 1];
  80. Bits.push_back(V);
  81. }
  82. }
  83. // With the leftover bits.
  84. unsigned V = 0;
  85. // Pos will have overshot size by 4 - #bytes left over.
  86. switch (Pos - Size) {
  87. case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
  88. case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
  89. case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
  90. default: return; // Nothing left.
  91. }
  92. Bits.push_back(V);
  93. }
  94. void FoldingSetNodeID::AddString(const char *String) {
  95. AddString(String, String + strlen(String));
  96. }
  97. void FoldingSetNodeID::AddString(const std::string &String) {
  98. AddString(&*String.begin(), &*String.end());
  99. }
  100. /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
  101. /// lookup the node in the FoldingSetImpl.
  102. unsigned FoldingSetNodeID::ComputeHash() const {
  103. // This is adapted from SuperFastHash by Paul Hsieh.
  104. unsigned Hash = static_cast<unsigned>(Bits.size());
  105. for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) {
  106. unsigned Data = *BP;
  107. Hash += Data & 0xFFFF;
  108. unsigned Tmp = ((Data >> 16) << 11) ^ Hash;
  109. Hash = (Hash << 16) ^ Tmp;
  110. Hash += Hash >> 11;
  111. }
  112. // Force "avalanching" of final 127 bits.
  113. Hash ^= Hash << 3;
  114. Hash += Hash >> 5;
  115. Hash ^= Hash << 4;
  116. Hash += Hash >> 17;
  117. Hash ^= Hash << 25;
  118. Hash += Hash >> 6;
  119. return Hash;
  120. }
  121. /// operator== - Used to compare two nodes to each other.
  122. ///
  123. bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS)const{
  124. if (Bits.size() != RHS.Bits.size()) return false;
  125. return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0;
  126. }
  127. //===----------------------------------------------------------------------===//
  128. /// Helper functions for FoldingSetImpl.
  129. /// GetNextPtr - In order to save space, each bucket is a
  130. /// singly-linked-list. In order to make deletion more efficient, we make
  131. /// the list circular, so we can delete a node without computing its hash.
  132. /// The problem with this is that the start of the hash buckets are not
  133. /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null:
  134. /// use GetBucketPtr when this happens.
  135. static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
  136. // The low bit is set if this is the pointer back to the bucket.
  137. if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
  138. return 0;
  139. return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
  140. }
  141. /// testing.
  142. static void **GetBucketPtr(void *NextInBucketPtr) {
  143. intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
  144. assert((Ptr & 1) && "Not a bucket pointer");
  145. return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
  146. }
  147. /// GetBucketFor - Hash the specified node ID and return the hash bucket for
  148. /// the specified ID.
  149. static void **GetBucketFor(const FoldingSetNodeID &ID,
  150. void **Buckets, unsigned NumBuckets) {
  151. // NumBuckets is always a power of 2.
  152. unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1);
  153. return Buckets + BucketNum;
  154. }
  155. //===----------------------------------------------------------------------===//
  156. // FoldingSetImpl Implementation
  157. FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) {
  158. assert(5 < Log2InitSize && Log2InitSize < 32 &&
  159. "Initial hash table size out of range");
  160. NumBuckets = 1 << Log2InitSize;
  161. Buckets = new void*[NumBuckets+1];
  162. clear();
  163. }
  164. FoldingSetImpl::~FoldingSetImpl() {
  165. delete [] Buckets;
  166. }
  167. void FoldingSetImpl::clear() {
  168. // Set all but the last bucket to null pointers.
  169. memset(Buckets, 0, NumBuckets*sizeof(void*));
  170. // Set the very last bucket to be a non-null "pointer".
  171. Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
  172. // Reset the node count to zero.
  173. NumNodes = 0;
  174. }
  175. /// GrowHashTable - Double the size of the hash table and rehash everything.
  176. ///
  177. void FoldingSetImpl::GrowHashTable() {
  178. void **OldBuckets = Buckets;
  179. unsigned OldNumBuckets = NumBuckets;
  180. NumBuckets <<= 1;
  181. // Clear out new buckets.
  182. Buckets = new void*[NumBuckets+1];
  183. clear();
  184. // Walk the old buckets, rehashing nodes into their new place.
  185. FoldingSetNodeID ID;
  186. for (unsigned i = 0; i != OldNumBuckets; ++i) {
  187. void *Probe = OldBuckets[i];
  188. if (!Probe) continue;
  189. while (Node *NodeInBucket = GetNextPtr(Probe)) {
  190. // Figure out the next link, remove NodeInBucket from the old link.
  191. Probe = NodeInBucket->getNextInBucket();
  192. NodeInBucket->SetNextInBucket(0);
  193. // Insert the node into the new bucket, after recomputing the hash.
  194. GetNodeProfile(ID, NodeInBucket);
  195. InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets));
  196. ID.clear();
  197. }
  198. }
  199. delete[] OldBuckets;
  200. }
  201. /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
  202. /// return it. If not, return the insertion token that will make insertion
  203. /// faster.
  204. FoldingSetImpl::Node
  205. *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  206. void *&InsertPos) {
  207. void **Bucket = GetBucketFor(ID, Buckets, NumBuckets);
  208. void *Probe = *Bucket;
  209. InsertPos = 0;
  210. FoldingSetNodeID OtherID;
  211. while (Node *NodeInBucket = GetNextPtr(Probe)) {
  212. GetNodeProfile(OtherID, NodeInBucket);
  213. if (OtherID == ID)
  214. return NodeInBucket;
  215. Probe = NodeInBucket->getNextInBucket();
  216. OtherID.clear();
  217. }
  218. // Didn't find the node, return null with the bucket as the InsertPos.
  219. InsertPos = Bucket;
  220. return 0;
  221. }
  222. /// InsertNode - Insert the specified node into the folding set, knowing that it
  223. /// is not already in the map. InsertPos must be obtained from
  224. /// FindNodeOrInsertPos.
  225. void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) {
  226. assert(N->getNextInBucket() == 0);
  227. // Do we need to grow the hashtable?
  228. if (NumNodes+1 > NumBuckets*2) {
  229. GrowHashTable();
  230. FoldingSetNodeID ID;
  231. GetNodeProfile(ID, N);
  232. InsertPos = GetBucketFor(ID, Buckets, NumBuckets);
  233. }
  234. ++NumNodes;
  235. /// The insert position is actually a bucket pointer.
  236. void **Bucket = static_cast<void**>(InsertPos);
  237. void *Next = *Bucket;
  238. // If this is the first insertion into this bucket, its next pointer will be
  239. // null. Pretend as if it pointed to itself, setting the low bit to indicate
  240. // that it is a pointer to the bucket.
  241. if (Next == 0)
  242. Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
  243. // Set the node's next pointer, and make the bucket point to the node.
  244. N->SetNextInBucket(Next);
  245. *Bucket = N;
  246. }
  247. /// RemoveNode - Remove a node from the folding set, returning true if one was
  248. /// removed or false if the node was not in the folding set.
  249. bool FoldingSetImpl::RemoveNode(Node *N) {
  250. // Because each bucket is a circular list, we don't need to compute N's hash
  251. // to remove it.
  252. void *Ptr = N->getNextInBucket();
  253. if (Ptr == 0) return false; // Not in folding set.
  254. --NumNodes;
  255. N->SetNextInBucket(0);
  256. // Remember what N originally pointed to, either a bucket or another node.
  257. void *NodeNextPtr = Ptr;
  258. // Chase around the list until we find the node (or bucket) which points to N.
  259. while (true) {
  260. if (Node *NodeInBucket = GetNextPtr(Ptr)) {
  261. // Advance pointer.
  262. Ptr = NodeInBucket->getNextInBucket();
  263. // We found a node that points to N, change it to point to N's next node,
  264. // removing N from the list.
  265. if (Ptr == N) {
  266. NodeInBucket->SetNextInBucket(NodeNextPtr);
  267. return true;
  268. }
  269. } else {
  270. void **Bucket = GetBucketPtr(Ptr);
  271. Ptr = *Bucket;
  272. // If we found that the bucket points to N, update the bucket to point to
  273. // whatever is next.
  274. if (Ptr == N) {
  275. *Bucket = NodeNextPtr;
  276. return true;
  277. }
  278. }
  279. }
  280. }
  281. /// GetOrInsertNode - If there is an existing simple Node exactly
  282. /// equal to the specified node, return it. Otherwise, insert 'N' and it
  283. /// instead.
  284. FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
  285. FoldingSetNodeID ID;
  286. GetNodeProfile(ID, N);
  287. void *IP;
  288. if (Node *E = FindNodeOrInsertPos(ID, IP))
  289. return E;
  290. InsertNode(N, IP);
  291. return N;
  292. }
  293. //===----------------------------------------------------------------------===//
  294. // FoldingSetIteratorImpl Implementation
  295. FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
  296. // Skip to the first non-null non-self-cycle bucket.
  297. while (*Bucket != reinterpret_cast<void*>(-1) &&
  298. (*Bucket == 0 || GetNextPtr(*Bucket) == 0))
  299. ++Bucket;
  300. NodePtr = static_cast<FoldingSetNode*>(*Bucket);
  301. }
  302. void FoldingSetIteratorImpl::advance() {
  303. // If there is another link within this bucket, go to it.
  304. void *Probe = NodePtr->getNextInBucket();
  305. if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
  306. NodePtr = NextNodeInBucket;
  307. else {
  308. // Otherwise, this is the last link in this bucket.
  309. void **Bucket = GetBucketPtr(Probe);
  310. // Skip to the next non-null non-self-cycle bucket.
  311. do {
  312. ++Bucket;
  313. } while (*Bucket != reinterpret_cast<void*>(-1) &&
  314. (*Bucket == 0 || GetNextPtr(*Bucket) == 0));
  315. NodePtr = static_cast<FoldingSetNode*>(*Bucket);
  316. }
  317. }
  318. //===----------------------------------------------------------------------===//
  319. // FoldingSetBucketIteratorImpl Implementation
  320. FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
  321. Ptr = (*Bucket == 0 || GetNextPtr(*Bucket) == 0) ? (void*) Bucket : *Bucket;
  322. }