1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a hash set that can be used to remove duplication of
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/Host.h"
20 #include "llvm/Support/MathExtras.h"
25 //===----------------------------------------------------------------------===//
26 // FoldingSetNodeIDRef Implementation
28 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
29 /// used to lookup the node in the FoldingSetImpl.
30 unsigned FoldingSetNodeIDRef::ComputeHash() const {
31 return static_cast<unsigned>(hash_combine_range(Data, Data+Size));
34 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS) const {
35 if (Size != RHS.Size) return false;
36 return memcmp(Data, RHS.Data, Size*sizeof(*Data)) == 0;
39 /// Used to compare the "ordering" of two nodes as defined by the
40 /// profiled bits and their ordering defined by memcmp().
41 bool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS) const {
43 return Size < RHS.Size;
44 return memcmp(Data, RHS.Data, Size*sizeof(*Data)) < 0;
47 //===----------------------------------------------------------------------===//
48 // FoldingSetNodeID Implementation
50 /// Add* - Add various data types to Bit data.
52 void FoldingSetNodeID::AddPointer(const void *Ptr) {
53 // Note: this adds pointers to the hash using sizes and endianness that
54 // depend on the host. It doesn't matter however, because hashing on
55 // pointer values in inherently unstable. Nothing should depend on the
56 // ordering of nodes in the folding set.
57 Bits.append(reinterpret_cast<unsigned *>(&Ptr),
58 reinterpret_cast<unsigned *>(&Ptr+1));
60 void FoldingSetNodeID::AddInteger(signed I) {
63 void FoldingSetNodeID::AddInteger(unsigned I) {
66 void FoldingSetNodeID::AddInteger(long I) {
67 AddInteger((unsigned long)I);
69 void FoldingSetNodeID::AddInteger(unsigned long I) {
70 if (sizeof(long) == sizeof(int))
71 AddInteger(unsigned(I));
72 else if (sizeof(long) == sizeof(long long)) {
73 AddInteger((unsigned long long)I);
75 llvm_unreachable("unexpected sizeof(long)");
78 void FoldingSetNodeID::AddInteger(long long I) {
79 AddInteger((unsigned long long)I);
81 void FoldingSetNodeID::AddInteger(unsigned long long I) {
82 AddInteger(unsigned(I));
83 if ((uint64_t)(unsigned)I != I)
84 Bits.push_back(unsigned(I >> 32));
87 void FoldingSetNodeID::AddString(StringRef String) {
88 unsigned Size = String.size();
92 unsigned Units = Size / 4;
94 const unsigned *Base = (const unsigned*) String.data();
96 // If the string is aligned do a bulk transfer.
97 if (!((intptr_t)Base & 3)) {
98 Bits.append(Base, Base + Units);
99 Pos = (Units + 1) * 4;
101 // Otherwise do it the hard way.
102 // To be compatible with above bulk transfer, we need to take endianness
104 if (sys::IsBigEndianHost) {
105 for (Pos += 4; Pos <= Size; Pos += 4) {
106 unsigned V = ((unsigned char)String[Pos - 4] << 24) |
107 ((unsigned char)String[Pos - 3] << 16) |
108 ((unsigned char)String[Pos - 2] << 8) |
109 (unsigned char)String[Pos - 1];
113 assert(sys::IsLittleEndianHost && "Unexpected host endianness");
114 for (Pos += 4; Pos <= Size; Pos += 4) {
115 unsigned V = ((unsigned char)String[Pos - 1] << 24) |
116 ((unsigned char)String[Pos - 2] << 16) |
117 ((unsigned char)String[Pos - 3] << 8) |
118 (unsigned char)String[Pos - 4];
124 // With the leftover bits.
126 // Pos will have overshot size by 4 - #bytes left over.
127 // No need to take endianness into account here - this is always executed.
128 switch (Pos - Size) {
129 case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
130 case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
131 case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
132 default: return; // Nothing left.
138 // AddNodeID - Adds the Bit data of another ID to *this.
139 void FoldingSetNodeID::AddNodeID(const FoldingSetNodeID &ID) {
140 Bits.append(ID.Bits.begin(), ID.Bits.end());
143 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
144 /// lookup the node in the FoldingSetImpl.
145 unsigned FoldingSetNodeID::ComputeHash() const {
146 return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
149 /// operator== - Used to compare two nodes to each other.
151 bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS) const {
152 return *this == FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
155 /// operator== - Used to compare two nodes to each other.
157 bool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS) const {
158 return FoldingSetNodeIDRef(Bits.data(), Bits.size()) == RHS;
161 /// Used to compare the "ordering" of two nodes as defined by the
162 /// profiled bits and their ordering defined by memcmp().
163 bool FoldingSetNodeID::operator<(const FoldingSetNodeID &RHS) const {
164 return *this < FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
167 bool FoldingSetNodeID::operator<(FoldingSetNodeIDRef RHS) const {
168 return FoldingSetNodeIDRef(Bits.data(), Bits.size()) < RHS;
171 /// Intern - Copy this node's data to a memory region allocated from the
172 /// given allocator and return a FoldingSetNodeIDRef describing the
175 FoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const {
176 unsigned *New = Allocator.Allocate<unsigned>(Bits.size());
177 std::uninitialized_copy(Bits.begin(), Bits.end(), New);
178 return FoldingSetNodeIDRef(New, Bits.size());
181 //===----------------------------------------------------------------------===//
182 /// Helper functions for FoldingSetImpl.
184 /// GetNextPtr - In order to save space, each bucket is a
185 /// singly-linked-list. In order to make deletion more efficient, we make
186 /// the list circular, so we can delete a node without computing its hash.
187 /// The problem with this is that the start of the hash buckets are not
188 /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null:
189 /// use GetBucketPtr when this happens.
190 static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
191 // The low bit is set if this is the pointer back to the bucket.
192 if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
195 return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
200 static void **GetBucketPtr(void *NextInBucketPtr) {
201 intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
202 assert((Ptr & 1) && "Not a bucket pointer");
203 return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
206 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
207 /// the specified ID.
208 static 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;
214 /// AllocateBuckets - Allocated initialized bucket memory.
215 static 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);
222 //===----------------------------------------------------------------------===//
223 // FoldingSetImpl Implementation
225 FoldingSetImpl::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);
232 FoldingSetImpl::~FoldingSetImpl() {
235 void FoldingSetImpl::clear() {
236 // Set all but the last bucket to null pointers.
237 memset(Buckets, 0, NumBuckets*sizeof(void*));
239 // Set the very last bucket to be a non-null "pointer".
240 Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
242 // Reset the node count to zero.
246 /// GrowHashTable - Double the size of the hash table and rehash everything.
248 void FoldingSetImpl::GrowHashTable() {
249 void **OldBuckets = Buckets;
250 unsigned OldNumBuckets = NumBuckets;
253 // Clear out new buckets.
254 Buckets = AllocateBuckets(NumBuckets);
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);
267 // Insert the node into the new bucket, after recomputing the hash.
268 InsertNode(NodeInBucket,
269 GetBucketFor(ComputeNodeHash(NodeInBucket, TempID),
270 Buckets, NumBuckets));
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
282 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
284 unsigned IDHash = ID.ComputeHash();
285 void **Bucket = GetBucketFor(IDHash, Buckets, NumBuckets);
286 void *Probe = *Bucket;
290 FoldingSetNodeID TempID;
291 while (Node *NodeInBucket = GetNextPtr(Probe)) {
292 if (NodeEquals(NodeInBucket, ID, IDHash, TempID))
296 Probe = NodeInBucket->getNextInBucket();
299 // Didn't find the node, return null with the bucket as the InsertPos.
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.
307 void 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) {
312 FoldingSetNodeID TempID;
313 InsertPos = GetBucketFor(ComputeNodeHash(N, TempID), Buckets, NumBuckets);
318 /// The insert position is actually a bucket pointer.
319 void **Bucket = static_cast<void**>(InsertPos);
321 void *Next = *Bucket;
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.
327 Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
329 // Set the node's next pointer, and make the bucket point to the node.
330 N->SetNextInBucket(Next);
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.
336 bool FoldingSetImpl::RemoveNode(Node *N) {
337 // Because each bucket is a circular list, we don't need to compute N's hash
339 void *Ptr = N->getNextInBucket();
340 if (Ptr == 0) return false; // Not in folding set.
343 N->SetNextInBucket(0);
345 // Remember what N originally pointed to, either a bucket or another node.
346 void *NodeNextPtr = Ptr;
348 // Chase around the list until we find the node (or bucket) which points to N.
350 if (Node *NodeInBucket = GetNextPtr(Ptr)) {
352 Ptr = NodeInBucket->getNextInBucket();
354 // We found a node that points to N, change it to point to N's next node,
355 // removing N from the list.
357 NodeInBucket->SetNextInBucket(NodeNextPtr);
361 void **Bucket = GetBucketPtr(Ptr);
364 // If we found that the bucket points to N, update the bucket to point to
367 *Bucket = NodeNextPtr;
374 /// GetOrInsertNode - If there is an existing simple Node exactly
375 /// equal to the specified node, return it. Otherwise, insert 'N' and it
377 FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
379 GetNodeProfile(N, ID);
381 if (Node *E = FindNodeOrInsertPos(ID, IP))
387 //===----------------------------------------------------------------------===//
388 // FoldingSetIteratorImpl Implementation
390 FoldingSetIteratorImpl::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))
396 NodePtr = static_cast<FoldingSetNode*>(*Bucket);
399 void FoldingSetIteratorImpl::advance() {
400 // If there is another link within this bucket, go to it.
401 void *Probe = NodePtr->getNextInBucket();
403 if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
404 NodePtr = NextNodeInBucket;
406 // Otherwise, this is the last link in this bucket.
407 void **Bucket = GetBucketPtr(Probe);
409 // Skip to the next non-null non-self-cycle bucket.
412 } while (*Bucket != reinterpret_cast<void*>(-1) &&
413 (*Bucket == 0 || GetNextPtr(*Bucket) == 0));
415 NodePtr = static_cast<FoldingSetNode*>(*Bucket);
419 //===----------------------------------------------------------------------===//
420 // FoldingSetBucketIteratorImpl Implementation
422 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
423 Ptr = (*Bucket == 0 || GetNextPtr(*Bucket) == 0) ? (void*) Bucket : *Bucket;