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