Allow FoldingSet clients to pump up the initial hash size.
[oota-llvm.git] / lib / Support / FoldingSet.cpp
1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under
6 // the University of Illinois Open Source 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
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/Support/MathExtras.h"
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // FoldingSetImpl::NodeID Implementation
23
24 /// Add* - Add various data types to Bit data.
25 ///
26 void FoldingSetImpl::NodeID::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 FoldingSetImpl::NodeID::AddInteger(signed I) {
37   Bits.push_back(I);
38 }
39 void FoldingSetImpl::NodeID::AddInteger(unsigned I) {
40   Bits.push_back(I);
41 }
42 void FoldingSetImpl::NodeID::AddInteger(uint64_t I) {
43   Bits.push_back(unsigned(I));
44   Bits.push_back(unsigned(I >> 32));
45 }
46 void FoldingSetImpl::NodeID::AddFloat(float F) {
47   Bits.push_back(FloatToBits(F));
48 }
49 void FoldingSetImpl::NodeID::AddDouble(double D) {
50  AddInteger(DoubleToBits(D));
51 }
52 void FoldingSetImpl::NodeID::AddString(const std::string &String) {
53   unsigned Size = String.size();
54   Bits.push_back(Size);
55   if (!Size) return;
56
57   unsigned Units = Size / 4;
58   unsigned Pos = 0;
59   const unsigned *Base = (const unsigned *)String.data();
60   
61   // If the string is aligned do a bulk transfer.
62   if (!((intptr_t)Base & 3)) {
63     Bits.append(Base, Base + Units);
64     Pos = (Units + 1) * 4;
65   } else {
66     // Otherwise do it the hard way.
67     for ( Pos += 4; Pos <= Size; Pos += 4) {
68       unsigned V = ((unsigned char)String[Pos - 4] << 24) |
69                    ((unsigned char)String[Pos - 3] << 16) |
70                    ((unsigned char)String[Pos - 2] << 8) |
71                     (unsigned char)String[Pos - 1];
72       Bits.push_back(V);
73     }
74   }
75   
76   // With the leftover bits.
77   unsigned V = 0;
78   // Pos will have overshot size by 4 - #bytes left over. 
79   switch (Pos - Size) {
80   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
81   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
82   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
83   default: return; // Nothing left.
84   }
85
86   Bits.push_back(V);
87 }
88
89 /// ComputeHash - Compute a strong hash value for this NodeID, used to 
90 /// lookup the node in the FoldingSetImpl.
91 unsigned FoldingSetImpl::NodeID::ComputeHash() const {
92   // This is adapted from SuperFastHash by Paul Hsieh.
93   unsigned Hash = Bits.size();
94   for (const unsigned *BP = &Bits[0], *E = BP+Bits.size(); BP != E; ++BP) {
95     unsigned Data = *BP;
96     Hash         += Data & 0xFFFF;
97     unsigned Tmp  = ((Data >> 16) << 11) ^ Hash;
98     Hash          = (Hash << 16) ^ Tmp;
99     Hash         += Hash >> 11;
100   }
101   
102   // Force "avalanching" of final 127 bits.
103   Hash ^= Hash << 3;
104   Hash += Hash >> 5;
105   Hash ^= Hash << 4;
106   Hash += Hash >> 17;
107   Hash ^= Hash << 25;
108   Hash += Hash >> 6;
109   return Hash;
110 }
111
112 /// operator== - Used to compare two nodes to each other.
113 ///
114 bool FoldingSetImpl::NodeID::operator==(const FoldingSetImpl::NodeID &RHS)const{
115   if (Bits.size() != RHS.Bits.size()) return false;
116   return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()*sizeof(Bits[0])) == 0;
117 }
118
119
120 //===----------------------------------------------------------------------===//
121 /// Helper functions for FoldingSetImpl.
122
123 /// GetNextPtr - In order to save space, each bucket is a
124 /// singly-linked-list. In order to make deletion more efficient, we make
125 /// the list circular, so we can delete a node without computing its hash.
126 /// The problem with this is that the start of the hash buckets are not
127 /// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null
128 /// : use GetBucketPtr when this happens.
129 static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr,
130                                         void **Buckets, unsigned NumBuckets) {
131   if (NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets + NumBuckets)
132     return 0;
133   return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
134 }
135
136 /// GetBucketPtr - Provides a casting of a bucket pointer for isNode
137 /// testing.
138 static void **GetBucketPtr(void *NextInBucketPtr) {
139   return static_cast<void**>(NextInBucketPtr);
140 }
141
142 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
143 /// the specified ID.
144 static void **GetBucketFor(const FoldingSetImpl::NodeID &ID,
145                            void **Buckets, unsigned NumBuckets) {
146   // NumBuckets is always a power of 2.
147   unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1);
148   return Buckets + BucketNum;
149 }
150
151 //===----------------------------------------------------------------------===//
152 // FoldingSetImpl Implementation
153
154 FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) : NumNodes(0) {
155   assert(5 < Log2InitSize && Log2InitSize < 32 &&
156          "Initial hash table size out of range");
157   NumBuckets = 1 << Log2InitSize;
158   Buckets = new void*[NumBuckets];
159   memset(Buckets, 0, NumBuckets*sizeof(void*));
160 }
161 FoldingSetImpl::~FoldingSetImpl() {
162   delete [] Buckets;
163 }
164
165 /// GrowHashTable - Double the size of the hash table and rehash everything.
166 ///
167 void FoldingSetImpl::GrowHashTable() {
168   void **OldBuckets = Buckets;
169   unsigned OldNumBuckets = NumBuckets;
170   NumBuckets <<= 1;
171   
172   // Reset the node count to zero: we're going to reinsert everything.
173   NumNodes = 0;
174   
175   // Clear out new buckets.
176   Buckets = new void*[NumBuckets];
177   memset(Buckets, 0, NumBuckets*sizeof(void*));
178
179   // Walk the old buckets, rehashing nodes into their new place.
180   for (unsigned i = 0; i != OldNumBuckets; ++i) {
181     void *Probe = OldBuckets[i];
182     if (!Probe) continue;
183     while (Node *NodeInBucket = GetNextPtr(Probe, OldBuckets, OldNumBuckets)){
184       // Figure out the next link, remove NodeInBucket from the old link.
185       Probe = NodeInBucket->getNextInBucket();
186       NodeInBucket->SetNextInBucket(0);
187
188       // Insert the node into the new bucket, after recomputing the hash.
189       NodeID ID;
190       GetNodeProfile(ID, NodeInBucket);
191       InsertNode(NodeInBucket, GetBucketFor(ID, Buckets, NumBuckets));
192     }
193   }
194   
195   delete[] OldBuckets;
196 }
197
198 /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
199 /// return it.  If not, return the insertion token that will make insertion
200 /// faster.
201 FoldingSetImpl::Node *FoldingSetImpl::FindNodeOrInsertPos(const NodeID &ID,
202                                                           void *&InsertPos) {
203   void **Bucket = GetBucketFor(ID, Buckets, NumBuckets);
204   void *Probe = *Bucket;
205   
206   InsertPos = 0;
207   
208   while (Node *NodeInBucket = GetNextPtr(Probe, Buckets, NumBuckets)) {
209     NodeID OtherID;
210     GetNodeProfile(OtherID, NodeInBucket);
211     if (OtherID == ID)
212       return NodeInBucket;
213
214     Probe = NodeInBucket->getNextInBucket();
215   }
216   
217   // Didn't find the node, return null with the bucket as the InsertPos.
218   InsertPos = Bucket;
219   return 0;
220 }
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   ++NumNodes;
227   // Do we need to grow the hashtable?
228   if (NumNodes > NumBuckets*2) {
229     GrowHashTable();
230     NodeID ID;
231     GetNodeProfile(ID, N);
232     InsertPos = GetBucketFor(ID, Buckets, NumBuckets);
233   }
234   
235   /// The insert position is actually a bucket pointer.
236   void **Bucket = static_cast<void**>(InsertPos);
237   
238   void *Next = *Bucket;
239   
240   // If this is the first insertion into this bucket, its next pointer will be
241   // null.  Pretend as if it pointed to itself.
242   if (Next == 0)
243     Next = Bucket;
244
245   // Set the nodes next pointer, and make the bucket point to the node.
246   N->SetNextInBucket(Next);
247   *Bucket = N;
248 }
249
250 /// RemoveNode - Remove a node from the folding set, returning true if one was
251 /// removed or false if the node was not in the folding set.
252 bool FoldingSetImpl::RemoveNode(Node *N) {
253   // Because each bucket is a circular list, we don't need to compute N's hash
254   // to remove it.  Chase around the list until we find the node (or bucket)
255   // which points to N.
256   void *Ptr = N->getNextInBucket();
257   if (Ptr == 0) return false;  // Not in folding set.
258
259   --NumNodes;
260
261   void *NodeNextPtr = Ptr;
262   N->SetNextInBucket(0);
263   while (true) {
264     if (Node *NodeInBucket = GetNextPtr(Ptr, Buckets, NumBuckets)) {
265       // Advance pointer.
266       Ptr = NodeInBucket->getNextInBucket();
267       
268       // We found a node that points to N, change it to point to N's next node,
269       // removing N from the list.
270       if (Ptr == N) {
271         NodeInBucket->SetNextInBucket(NodeNextPtr);
272         return true;
273       }
274     } else {
275       void **Bucket = GetBucketPtr(Ptr);
276       Ptr = *Bucket;
277       
278       // If we found that the bucket points to N, update the bucket to point to
279       // whatever is next.
280       if (Ptr == N) {
281         *Bucket = NodeNextPtr;
282         return true;
283       }
284     }
285   }
286 }
287
288 /// GetOrInsertNode - If there is an existing simple Node exactly
289 /// equal to the specified node, return it.  Otherwise, insert 'N' and it
290 /// instead.
291 FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
292   NodeID ID;
293   GetNodeProfile(ID, N);
294   void *IP;
295   if (Node *E = FindNodeOrInsertPos(ID, IP))
296     return E;
297   InsertNode(N, IP);
298   return N;
299 }