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