FoldingSet.cpp revision 251662
174462Salfred//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
274462Salfred//
3259118Shrs//                     The LLVM Compiler Infrastructure
4259118Shrs//
58870Srgrimes// This file is distributed under the University of Illinois Open Source
6259118Shrs// License. See LICENSE.TXT for details.
7259118Shrs//
8259118Shrs//===----------------------------------------------------------------------===//
98870Srgrimes//
10259118Shrs// This file implements a hash set that can be used to remove duplication of
11259118Shrs// nodes in a graph.
12259118Shrs//
13259118Shrs//===----------------------------------------------------------------------===//
14259118Shrs
15259118Shrs#include "llvm/ADT/FoldingSet.h"
16259118Shrs#include "llvm/ADT/Hashing.h"
17259118Shrs#include "llvm/Support/Allocator.h"
18259118Shrs#include "llvm/Support/ErrorHandling.h"
198870Srgrimes#include "llvm/Support/Host.h"
20259118Shrs#include "llvm/Support/MathExtras.h"
21259118Shrs#include <cassert>
22259118Shrs#include <cstring>
23259118Shrsusing namespace llvm;
24259118Shrs
25259118Shrs//===----------------------------------------------------------------------===//
26259118Shrs// FoldingSetNodeIDRef Implementation
27259118Shrs
28259118Shrs/// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
29259118Shrs/// used to lookup the node in the FoldingSetImpl.
30259118Shrsunsigned FoldingSetNodeIDRef::ComputeHash() const {
31259118Shrs  return static_cast<unsigned>(hash_combine_range(Data, Data+Size));
321902Swollman}
331902Swollman
341902Swollmanbool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS) const {
35136582Sobrien  if (Size != RHS.Size) return false;
3692986Sobrien  return memcmp(Data, RHS.Data, Size*sizeof(*Data)) == 0;
371902Swollman}
3892986Sobrien
3992986Sobrien/// Used to compare the "ordering" of two nodes as defined by the
401902Swollman/// profiled bits and their ordering defined by memcmp().
411902Swollmanbool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS) const {
421902Swollman  if (Size != RHS.Size)
431902Swollman    return Size < RHS.Size;
441902Swollman  return memcmp(Data, RHS.Data, Size*sizeof(*Data)) < 0;
451902Swollman}
461902Swollman
471902Swollman//===----------------------------------------------------------------------===//
481902Swollman// FoldingSetNodeID Implementation
491902Swollman
5074462Salfred/// Add* - Add various data types to Bit data.
5174462Salfred///
5274462Salfredvoid FoldingSetNodeID::AddPointer(const void *Ptr) {
5374462Salfred  // Note: this adds pointers to the hash using sizes and endianness that
5474462Salfred  // depend on the host.  It doesn't matter however, because hashing on
5511669Sphk  // pointer values in inherently unstable.  Nothing  should depend on the
5674462Salfred  // ordering of nodes in the folding set.
571902Swollman  Bits.append(reinterpret_cast<unsigned *>(&Ptr),
581902Swollman              reinterpret_cast<unsigned *>(&Ptr+1));
5974462Salfred}
601902Swollmanvoid FoldingSetNodeID::AddInteger(signed I) {
6192905Sobrien  Bits.push_back(I);
6292905Sobrien}
6392905Sobrienvoid FoldingSetNodeID::AddInteger(unsigned I) {
6492905Sobrien  Bits.push_back(I);
6592905Sobrien}
6692905Sobrienvoid FoldingSetNodeID::AddInteger(long I) {
6792905Sobrien  AddInteger((unsigned long)I);
6874462Salfred}
6992905Sobrienvoid FoldingSetNodeID::AddInteger(unsigned long I) {
7092905Sobrien  if (sizeof(long) == sizeof(int))
7192905Sobrien    AddInteger(unsigned(I));
7292905Sobrien  else if (sizeof(long) == sizeof(long long)) {
731902Swollman    AddInteger((unsigned long long)I);
7474462Salfred  } else {
7521062Speter    llvm_unreachable("unexpected sizeof(long)");
7621062Speter  }
771902Swollman}
781902Swollmanvoid FoldingSetNodeID::AddInteger(long long I) {
791902Swollman  AddInteger((unsigned long long)I);
801902Swollman}
8121062Spetervoid FoldingSetNodeID::AddInteger(unsigned long long I) {
821902Swollman  AddInteger(unsigned(I));
831902Swollman  if ((uint64_t)(unsigned)I != I)
841902Swollman    Bits.push_back(unsigned(I >> 32));
8574462Salfred}
8621062Speter
8721062Spetervoid FoldingSetNodeID::AddString(StringRef String) {
8821062Speter  unsigned Size =  String.size();
8921062Speter  Bits.push_back(Size);
9021062Speter  if (!Size) return;
9121062Speter
9221062Speter  unsigned Units = Size / 4;
9321062Speter  unsigned Pos = 0;
9421062Speter  const unsigned *Base = (const unsigned*) String.data();
9521062Speter
961902Swollman  // If the string is aligned do a bulk transfer.
971902Swollman  if (!((intptr_t)Base & 3)) {
988870Srgrimes    Bits.append(Base, Base + Units);
991902Swollman    Pos = (Units + 1) * 4;
1001902Swollman  } else {
101283833Srodrigc    // Otherwise do it the hard way.
1021902Swollman    // To be compatible with above bulk transfer, we need to take endianness
1031902Swollman    // into account.
1041902Swollman    if (sys::IsBigEndianHost) {
10574462Salfred      for (Pos += 4; Pos <= Size; Pos += 4) {
10674462Salfred        unsigned V = ((unsigned char)String[Pos - 4] << 24) |
1071902Swollman                     ((unsigned char)String[Pos - 3] << 16) |
1081902Swollman                     ((unsigned char)String[Pos - 2] << 8) |
1091902Swollman                      (unsigned char)String[Pos - 1];
1101902Swollman        Bits.push_back(V);
11174462Salfred      }
1121902Swollman    } else {
113283833Srodrigc      assert(sys::IsLittleEndianHost && "Unexpected host endianness");
1141902Swollman      for (Pos += 4; Pos <= Size; Pos += 4) {
11521062Speter        unsigned V = ((unsigned char)String[Pos - 1] << 24) |
1161902Swollman                     ((unsigned char)String[Pos - 2] << 16) |
1171902Swollman                     ((unsigned char)String[Pos - 3] << 8) |
1181902Swollman                      (unsigned char)String[Pos - 4];
119283833Srodrigc        Bits.push_back(V);
1201902Swollman      }
1211902Swollman    }
122111962Snectar  }
1231902Swollman
124111962Snectar  // With the leftover bits.
12574462Salfred  unsigned V = 0;
12674462Salfred  // Pos will have overshot size by 4 - #bytes left over.
1271902Swollman  // No need to take endianness into account here - this is always executed.
1281902Swollman  switch (Pos - Size) {
1291902Swollman  case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
1301902Swollman  case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
131283833Srodrigc  case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
1321902Swollman  default: return; // Nothing left.
1331902Swollman  }
134111962Snectar
1351902Swollman  Bits.push_back(V);
136111962Snectar}
13774462Salfred
13874462Salfred// AddNodeID - Adds the Bit data of another ID to *this.
1391902Swollmanvoid FoldingSetNodeID::AddNodeID(const FoldingSetNodeID &ID) {
1401902Swollman  Bits.append(ID.Bits.begin(), ID.Bits.end());
1411902Swollman}
1421902Swollman
143283833Srodrigc/// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
14421062Speter/// lookup the node in the FoldingSetImpl.
14574462Salfredunsigned FoldingSetNodeID::ComputeHash() const {
14621062Speter  return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
147111962Snectar}
14821062Speter
149111962Snectar/// operator== - Used to compare two nodes to each other.
15074462Salfred///
15121062Speterbool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS) const {
15274462Salfred  return *this == FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
15321062Speter}
15421062Speter
15521062Speter/// operator== - Used to compare two nodes to each other.
15621062Speter///
157283833Srodrigcbool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS) const {
15821062Speter  return FoldingSetNodeIDRef(Bits.data(), Bits.size()) == RHS;
15974462Salfred}
16021062Speter
161111962Snectar/// Used to compare the "ordering" of two nodes as defined by the
16221062Speter/// profiled bits and their ordering defined by memcmp().
163111962Snectarbool FoldingSetNodeID::operator<(const FoldingSetNodeID &RHS) const {
16474462Salfred  return *this < FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
16574462Salfred}
16674462Salfred
16721062Speterbool FoldingSetNodeID::operator<(FoldingSetNodeIDRef RHS) const {
16821062Speter  return FoldingSetNodeIDRef(Bits.data(), Bits.size()) < RHS;
16921062Speter}
17021062Speter
171283833Srodrigc/// Intern - Copy this node's data to a memory region allocated from the
1721902Swollman/// given allocator and return a FoldingSetNodeIDRef describing the
1731902Swollman/// interned data.
174111962SnectarFoldingSetNodeIDRef
1751902SwollmanFoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const {
176111962Snectar  unsigned *New = Allocator.Allocate<unsigned>(Bits.size());
17774462Salfred  std::uninitialized_copy(Bits.begin(), Bits.end(), New);
17874462Salfred  return FoldingSetNodeIDRef(New, Bits.size());
1791902Swollman}
1801902Swollman
1811902Swollman//===----------------------------------------------------------------------===//
1821902Swollman/// Helper functions for FoldingSetImpl.
183283833Srodrigc
1841902Swollman/// GetNextPtr - In order to save space, each bucket is a
1851902Swollman/// singly-linked-list. In order to make deletion more efficient, we make
186111962Snectar/// the list circular, so we can delete a node without computing its hash.
1871902Swollman/// The problem with this is that the start of the hash buckets are not
188111962Snectar/// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
18974462Salfred/// use GetBucketPtr when this happens.
19074462Salfredstatic FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
1911902Swollman  // The low bit is set if this is the pointer back to the bucket.
1921902Swollman  if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
1931902Swollman    return 0;
1941902Swollman
195283833Srodrigc  return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
1961902Swollman}
1971902Swollman
19821062Speter
19974462Salfred/// testing.
2001902Swollmanstatic void **GetBucketPtr(void *NextInBucketPtr) {
2011902Swollman  intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
2021902Swollman  assert((Ptr & 1) && "Not a bucket pointer");
203283833Srodrigc  return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
2041902Swollman}
20574462Salfred
20674462Salfred/// GetBucketFor - Hash the specified node ID and return the hash bucket for
2071902Swollman/// the specified ID.
208111962Snectarstatic void **GetBucketFor(unsigned Hash, void **Buckets, unsigned NumBuckets) {
2091902Swollman  // NumBuckets is always a power of 2.
2101902Swollman  unsigned BucketNum = Hash & (NumBuckets-1);
211111962Snectar  return Buckets + BucketNum;
2121902Swollman}
2131902Swollman
2141902Swollman/// AllocateBuckets - Allocated initialized bucket memory.
21521062Speterstatic void **AllocateBuckets(unsigned NumBuckets) {
216283833Srodrigc  void **Buckets = static_cast<void**>(calloc(NumBuckets+1, sizeof(void*)));
2171902Swollman  // Set the very last bucket to be a non-null "pointer".
218297790Spfg  Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
2191902Swollman  return Buckets;
2201902Swollman}
2211902Swollman
22274462Salfred//===----------------------------------------------------------------------===//
22374462Salfred// FoldingSetImpl Implementation
2241902Swollman
2251902SwollmanFoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) {
2261902Swollman  assert(5 < Log2InitSize && Log2InitSize < 32 &&
22721062Speter         "Initial hash table size out of range");
22874462Salfred  NumBuckets = 1 << Log2InitSize;
22921062Speter  Buckets = AllocateBuckets(NumBuckets);
230283833Srodrigc  NumNodes = 0;
23121062Speter}
23274462SalfredFoldingSetImpl::~FoldingSetImpl() {
23321062Speter  free(Buckets);
23421062Speter}
235void FoldingSetImpl::clear() {
236  // Set all but the last bucket to null pointers.
237  memset(Buckets, 0, NumBuckets*sizeof(void*));
238
239  // Set the very last bucket to be a non-null "pointer".
240  Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
241
242  // Reset the node count to zero.
243  NumNodes = 0;
244}
245
246/// GrowHashTable - Double the size of the hash table and rehash everything.
247///
248void FoldingSetImpl::GrowHashTable() {
249  void **OldBuckets = Buckets;
250  unsigned OldNumBuckets = NumBuckets;
251  NumBuckets <<= 1;
252
253  // Clear out new buckets.
254  Buckets = AllocateBuckets(NumBuckets);
255  NumNodes = 0;
256
257  // Walk the old buckets, rehashing nodes into their new place.
258  FoldingSetNodeID TempID;
259  for (unsigned i = 0; i != OldNumBuckets; ++i) {
260    void *Probe = OldBuckets[i];
261    if (!Probe) continue;
262    while (Node *NodeInBucket = GetNextPtr(Probe)) {
263      // Figure out the next link, remove NodeInBucket from the old link.
264      Probe = NodeInBucket->getNextInBucket();
265      NodeInBucket->SetNextInBucket(0);
266
267      // Insert the node into the new bucket, after recomputing the hash.
268      InsertNode(NodeInBucket,
269                 GetBucketFor(ComputeNodeHash(NodeInBucket, TempID),
270                              Buckets, NumBuckets));
271      TempID.clear();
272    }
273  }
274
275  free(OldBuckets);
276}
277
278/// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
279/// return it.  If not, return the insertion token that will make insertion
280/// faster.
281FoldingSetImpl::Node
282*FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
283                                     void *&InsertPos) {
284  unsigned IDHash = ID.ComputeHash();
285  void **Bucket = GetBucketFor(IDHash, Buckets, NumBuckets);
286  void *Probe = *Bucket;
287
288  InsertPos = 0;
289
290  FoldingSetNodeID TempID;
291  while (Node *NodeInBucket = GetNextPtr(Probe)) {
292    if (NodeEquals(NodeInBucket, ID, IDHash, TempID))
293      return NodeInBucket;
294    TempID.clear();
295
296    Probe = NodeInBucket->getNextInBucket();
297  }
298
299  // Didn't find the node, return null with the bucket as the InsertPos.
300  InsertPos = Bucket;
301  return 0;
302}
303
304/// InsertNode - Insert the specified node into the folding set, knowing that it
305/// is not already in the map.  InsertPos must be obtained from
306/// FindNodeOrInsertPos.
307void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) {
308  assert(N->getNextInBucket() == 0);
309  // Do we need to grow the hashtable?
310  if (NumNodes+1 > NumBuckets*2) {
311    GrowHashTable();
312    FoldingSetNodeID TempID;
313    InsertPos = GetBucketFor(ComputeNodeHash(N, TempID), Buckets, NumBuckets);
314  }
315
316  ++NumNodes;
317
318  /// The insert position is actually a bucket pointer.
319  void **Bucket = static_cast<void**>(InsertPos);
320
321  void *Next = *Bucket;
322
323  // If this is the first insertion into this bucket, its next pointer will be
324  // null.  Pretend as if it pointed to itself, setting the low bit to indicate
325  // that it is a pointer to the bucket.
326  if (Next == 0)
327    Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
328
329  // Set the node's next pointer, and make the bucket point to the node.
330  N->SetNextInBucket(Next);
331  *Bucket = N;
332}
333
334/// RemoveNode - Remove a node from the folding set, returning true if one was
335/// removed or false if the node was not in the folding set.
336bool FoldingSetImpl::RemoveNode(Node *N) {
337  // Because each bucket is a circular list, we don't need to compute N's hash
338  // to remove it.
339  void *Ptr = N->getNextInBucket();
340  if (Ptr == 0) return false;  // Not in folding set.
341
342  --NumNodes;
343  N->SetNextInBucket(0);
344
345  // Remember what N originally pointed to, either a bucket or another node.
346  void *NodeNextPtr = Ptr;
347
348  // Chase around the list until we find the node (or bucket) which points to N.
349  while (true) {
350    if (Node *NodeInBucket = GetNextPtr(Ptr)) {
351      // Advance pointer.
352      Ptr = NodeInBucket->getNextInBucket();
353
354      // We found a node that points to N, change it to point to N's next node,
355      // removing N from the list.
356      if (Ptr == N) {
357        NodeInBucket->SetNextInBucket(NodeNextPtr);
358        return true;
359      }
360    } else {
361      void **Bucket = GetBucketPtr(Ptr);
362      Ptr = *Bucket;
363
364      // If we found that the bucket points to N, update the bucket to point to
365      // whatever is next.
366      if (Ptr == N) {
367        *Bucket = NodeNextPtr;
368        return true;
369      }
370    }
371  }
372}
373
374/// GetOrInsertNode - If there is an existing simple Node exactly
375/// equal to the specified node, return it.  Otherwise, insert 'N' and it
376/// instead.
377FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
378  FoldingSetNodeID ID;
379  GetNodeProfile(N, ID);
380  void *IP;
381  if (Node *E = FindNodeOrInsertPos(ID, IP))
382    return E;
383  InsertNode(N, IP);
384  return N;
385}
386
387//===----------------------------------------------------------------------===//
388// FoldingSetIteratorImpl Implementation
389
390FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
391  // Skip to the first non-null non-self-cycle bucket.
392  while (*Bucket != reinterpret_cast<void*>(-1) &&
393         (*Bucket == 0 || GetNextPtr(*Bucket) == 0))
394    ++Bucket;
395
396  NodePtr = static_cast<FoldingSetNode*>(*Bucket);
397}
398
399void FoldingSetIteratorImpl::advance() {
400  // If there is another link within this bucket, go to it.
401  void *Probe = NodePtr->getNextInBucket();
402
403  if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
404    NodePtr = NextNodeInBucket;
405  else {
406    // Otherwise, this is the last link in this bucket.
407    void **Bucket = GetBucketPtr(Probe);
408
409    // Skip to the next non-null non-self-cycle bucket.
410    do {
411      ++Bucket;
412    } while (*Bucket != reinterpret_cast<void*>(-1) &&
413             (*Bucket == 0 || GetNextPtr(*Bucket) == 0));
414
415    NodePtr = static_cast<FoldingSetNode*>(*Bucket);
416  }
417}
418
419//===----------------------------------------------------------------------===//
420// FoldingSetBucketIteratorImpl Implementation
421
422FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
423  Ptr = (*Bucket == 0 || GetNextPtr(*Bucket) == 0) ? (void*) Bucket : *Bucket;
424}
425