FoldingSet.cpp revision 226633
166458Sdfr//===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
266458Sdfr//
396912Smarcel//                     The LLVM Compiler Infrastructure
496912Smarcel//
5139790Simp// This file is distributed under the University of Illinois Open Source
666458Sdfr// License. See LICENSE.TXT for details.
766458Sdfr//
866458Sdfr//===----------------------------------------------------------------------===//
966458Sdfr//
1066458Sdfr// This file implements a hash set that can be used to remove duplication of
1166458Sdfr// nodes in a graph.  This code was originally created by Chris Lattner for use
1266458Sdfr// with SelectionDAGCSEMap, but was isolated to provide use across the llvm code
1366458Sdfr// set.
1466458Sdfr//
1566458Sdfr//===----------------------------------------------------------------------===//
1666458Sdfr
1766458Sdfr#include "llvm/ADT/FoldingSet.h"
1866458Sdfr#include "llvm/Support/Allocator.h"
1966458Sdfr#include "llvm/Support/ErrorHandling.h"
2066458Sdfr#include "llvm/Support/MathExtras.h"
2166458Sdfr#include "llvm/Support/Host.h"
2266458Sdfr#include <cassert>
2366458Sdfr#include <cstring>
2466458Sdfrusing namespace llvm;
2566458Sdfr
2666458Sdfr//===----------------------------------------------------------------------===//
2766458Sdfr// FoldingSetNodeIDRef Implementation
2866458Sdfr
2966458Sdfr/// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
3066458Sdfr/// used to lookup the node in the FoldingSetImpl.
3166458Sdfrunsigned FoldingSetNodeIDRef::ComputeHash() const {
3266458Sdfr  // This is adapted from SuperFastHash by Paul Hsieh.
3366458Sdfr  unsigned Hash = static_cast<unsigned>(Size);
3466458Sdfr  for (const unsigned *BP = Data, *E = BP+Size; BP != E; ++BP) {
3566458Sdfr    unsigned Data = *BP;
3666458Sdfr    Hash         += Data & 0xFFFF;
3766458Sdfr    unsigned Tmp  = ((Data >> 16) << 11) ^ Hash;
3866458Sdfr    Hash          = (Hash << 16) ^ Tmp;
3966458Sdfr    Hash         += Hash >> 11;
4066458Sdfr  }
4166458Sdfr
4266458Sdfr  // Force "avalanching" of final 127 bits.
4366458Sdfr  Hash ^= Hash << 3;
4496912Smarcel  Hash += Hash >> 5;
4566458Sdfr  Hash ^= Hash << 4;
4666458Sdfr  Hash += Hash >> 17;
47170033Salc  Hash ^= Hash << 25;
48170033Salc  Hash += Hash >> 6;
4966458Sdfr  return Hash;
50115084Smarcel}
5166458Sdfr
5266458Sdfrbool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS) const {
5366458Sdfr  if (Size != RHS.Size) return false;
5466458Sdfr  return memcmp(Data, RHS.Data, Size*sizeof(*Data)) == 0;
5566458Sdfr}
5666458Sdfr
5766458Sdfr//===----------------------------------------------------------------------===//
5866458Sdfr// FoldingSetNodeID Implementation
5966458Sdfr
6066458Sdfr/// Add* - Add various data types to Bit data.
6166458Sdfr///
6266458Sdfrvoid FoldingSetNodeID::AddPointer(const void *Ptr) {
6366458Sdfr  // Note: this adds pointers to the hash using sizes and endianness that
6466458Sdfr  // depend on the host.  It doesn't matter however, because hashing on
6566458Sdfr  // pointer values in inherently unstable.  Nothing  should depend on the
6666458Sdfr  // ordering of nodes in the folding set.
6766458Sdfr  Bits.append(reinterpret_cast<unsigned *>(&Ptr),
6892670Speter              reinterpret_cast<unsigned *>(&Ptr+1));
6966458Sdfr}
7066458Sdfrvoid FoldingSetNodeID::AddInteger(signed I) {
7166458Sdfr  Bits.push_back(I);
7266458Sdfr}
7366458Sdfrvoid FoldingSetNodeID::AddInteger(unsigned I) {
7466458Sdfr  Bits.push_back(I);
7566458Sdfr}
7666458Sdfrvoid FoldingSetNodeID::AddInteger(long I) {
7766458Sdfr  AddInteger((unsigned long)I);
7866458Sdfr}
7966458Sdfrvoid FoldingSetNodeID::AddInteger(unsigned long I) {
8066458Sdfr  if (sizeof(long) == sizeof(int))
8166458Sdfr    AddInteger(unsigned(I));
8266458Sdfr  else if (sizeof(long) == sizeof(long long)) {
8366458Sdfr    AddInteger((unsigned long long)I);
8466458Sdfr  } else {
8566458Sdfr    llvm_unreachable("unexpected sizeof(long)");
8666458Sdfr  }
8766458Sdfr}
8866458Sdfrvoid FoldingSetNodeID::AddInteger(long long I) {
8966458Sdfr  AddInteger((unsigned long long)I);
9066458Sdfr}
9166458Sdfrvoid FoldingSetNodeID::AddInteger(unsigned long long I) {
9266458Sdfr  AddInteger(unsigned(I));
9366458Sdfr  if ((uint64_t)(unsigned)I != I)
9466458Sdfr    Bits.push_back(unsigned(I >> 32));
9566458Sdfr}
9666458Sdfr
9766458Sdfrvoid FoldingSetNodeID::AddString(StringRef String) {
9866458Sdfr  unsigned Size =  String.size();
9966458Sdfr  Bits.push_back(Size);
10066458Sdfr  if (!Size) return;
10166458Sdfr
102150008Salc  unsigned Units = Size / 4;
10366458Sdfr  unsigned Pos = 0;
10466458Sdfr  const unsigned *Base = (const unsigned*) String.data();
10566458Sdfr
10666458Sdfr  // If the string is aligned do a bulk transfer.
10766458Sdfr  if (!((intptr_t)Base & 3)) {
10866458Sdfr    Bits.append(Base, Base + Units);
109106486Smarcel    Pos = (Units + 1) * 4;
110106486Smarcel  } else {
111106486Smarcel    // Otherwise do it the hard way.
112106486Smarcel    // To be compatible with above bulk transfer, we need to take endianness
113106486Smarcel    // into account.
114169291Salc    if (sys::isBigEndianHost()) {
115169291Salc      for (Pos += 4; Pos <= Size; Pos += 4) {
116169291Salc        unsigned V = ((unsigned char)String[Pos - 4] << 24) |
117169291Salc                     ((unsigned char)String[Pos - 3] << 16) |
118169291Salc                     ((unsigned char)String[Pos - 2] << 8) |
119170519Salc                      (unsigned char)String[Pos - 1];
120170519Salc        Bits.push_back(V);
121170519Salc      }
122170519Salc    } else {
123170519Salc      assert(sys::isLittleEndianHost() && "Unexpected host endianness");
124170519Salc      for (Pos += 4; Pos <= Size; Pos += 4) {
125172317Salc        unsigned V = ((unsigned char)String[Pos - 1] << 24) |
126170519Salc                     ((unsigned char)String[Pos - 2] << 16) |
127170519Salc                     ((unsigned char)String[Pos - 3] << 8) |
128170519Salc                      (unsigned char)String[Pos - 4];
129170519Salc        Bits.push_back(V);
130172317Salc      }
131172317Salc    }
132170519Salc  }
133170519Salc
134170519Salc  // With the leftover bits.
135170519Salc  unsigned V = 0;
136170519Salc  // Pos will have overshot size by 4 - #bytes left over.
137170519Salc  // No need to take endianness into account here - this is always executed.
138170519Salc  switch (Pos - Size) {
139170519Salc  case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
140170519Salc  case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
141170519Salc  case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
142170519Salc  default: return; // Nothing left.
143170519Salc  }
144170519Salc
145170519Salc  Bits.push_back(V);
146170519Salc}
147170519Salc
14896912Smarcel// AddNodeID - Adds the Bit data of another ID to *this.
14996912Smarcelvoid FoldingSetNodeID::AddNodeID(const FoldingSetNodeID &ID) {
15096912Smarcel  Bits.append(ID.Bits.begin(), ID.Bits.end());
15196912Smarcel}
15296912Smarcel
15396912Smarcel/// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
15496912Smarcel/// lookup the node in the FoldingSetImpl.
15596912Smarcelunsigned FoldingSetNodeID::ComputeHash() const {
15696912Smarcel  return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
157119906Smarcel}
158119906Smarcel
159119906Smarcel/// operator== - Used to compare two nodes to each other.
160119906Smarcel///
161119906Smarcelbool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS)const{
162119906Smarcel  return *this == FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
163119906Smarcel}
164119906Smarcel
165119906Smarcel/// operator== - Used to compare two nodes to each other.
166119906Smarcel///
167121268Smarcelbool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS) const {
168121268Smarcel  return FoldingSetNodeIDRef(Bits.data(), Bits.size()) == RHS;
169119906Smarcel}
17066458Sdfr
17166458Sdfr/// Intern - Copy this node's data to a memory region allocated from the
17266458Sdfr/// given allocator and return a FoldingSetNodeIDRef describing the
17366458Sdfr/// interned data.
17466458SdfrFoldingSetNodeIDRef
175115084SmarcelFoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const {
176115084Smarcel  unsigned *New = Allocator.Allocate<unsigned>(Bits.size());
177115084Smarcel  std::uninitialized_copy(Bits.begin(), Bits.end(), New);
178115084Smarcel  return FoldingSetNodeIDRef(New, Bits.size());
17966458Sdfr}
18066458Sdfr
181115084Smarcel//===----------------------------------------------------------------------===//
18296912Smarcel/// Helper functions for FoldingSetImpl.
18366458Sdfr
18466458Sdfr/// GetNextPtr - In order to save space, each bucket is a
18566458Sdfr/// singly-linked-list. In order to make deletion more efficient, we make
18666458Sdfr/// the list circular, so we can delete a node without computing its hash.
18766458Sdfr/// The problem with this is that the start of the hash buckets are not
18866458Sdfr/// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
18966458Sdfr/// use GetBucketPtr when this happens.
190168920Ssepotvinstatic FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
191168920Ssepotvin  // The low bit is set if this is the pointer back to the bucket.
19266458Sdfr  if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
19366458Sdfr    return 0;
19466458Sdfr
19566458Sdfr  return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
19666458Sdfr}
19766458Sdfr
19866458Sdfr
19966458Sdfr/// testing.
20066458Sdfrstatic void **GetBucketPtr(void *NextInBucketPtr) {
20166458Sdfr  intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
20266458Sdfr  assert((Ptr & 1) && "Not a bucket pointer");
20396912Smarcel  return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
204}
205
206/// GetBucketFor - Hash the specified node ID and return the hash bucket for
207/// the specified ID.
208static void **GetBucketFor(unsigned Hash, void **Buckets, unsigned NumBuckets) {
209  // NumBuckets is always a power of 2.
210  unsigned BucketNum = Hash & (NumBuckets-1);
211  return Buckets + BucketNum;
212}
213
214/// AllocateBuckets - Allocated initialized bucket memory.
215static void **AllocateBuckets(unsigned NumBuckets) {
216  void **Buckets = static_cast<void**>(calloc(NumBuckets+1, sizeof(void*)));
217  // Set the very last bucket to be a non-null "pointer".
218  Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
219  return Buckets;
220}
221
222//===----------------------------------------------------------------------===//
223// FoldingSetImpl Implementation
224
225FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) {
226  assert(5 < Log2InitSize && Log2InitSize < 32 &&
227         "Initial hash table size out of range");
228  NumBuckets = 1 << Log2InitSize;
229  Buckets = AllocateBuckets(NumBuckets);
230  NumNodes = 0;
231}
232FoldingSetImpl::~FoldingSetImpl() {
233  free(Buckets);
234}
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
285  void **Bucket = GetBucketFor(ID.ComputeHash(), 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, 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