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
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
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/Support/Allocator.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Host.h"
26 //===----------------------------------------------------------------------===//
27 // FoldingSetNodeIDRef Implementation
29 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
30 /// used to lookup the node in the FoldingSetImpl.
31 unsigned FoldingSetNodeIDRef::ComputeHash() const {
32 // This is adapted from SuperFastHash by Paul Hsieh.
33 unsigned Hash
= static_cast<unsigned>(Size
);
34 for (const unsigned *BP
= Data
, *E
= BP
+Size
; BP
!= E
; ++BP
) {
36 Hash
+= Data
& 0xFFFF;
37 unsigned Tmp
= ((Data
>> 16) << 11) ^ Hash
;
38 Hash
= (Hash
<< 16) ^ Tmp
;
42 // Force "avalanching" of final 127 bits.
52 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS
) const {
53 if (Size
!= RHS
.Size
) return false;
54 return memcmp(Data
, RHS
.Data
, Size
*sizeof(*Data
)) == 0;
57 //===----------------------------------------------------------------------===//
58 // FoldingSetNodeID Implementation
60 /// Add* - Add various data types to Bit data.
62 void FoldingSetNodeID::AddPointer(const void *Ptr
) {
63 // Note: this adds pointers to the hash using sizes and endianness that
64 // depend on the host. It doesn't matter however, because hashing on
65 // pointer values in inherently unstable. Nothing should depend on the
66 // ordering of nodes in the folding set.
67 intptr_t PtrI
= (intptr_t)Ptr
;
68 Bits
.push_back(unsigned(PtrI
));
69 if (sizeof(intptr_t) > sizeof(unsigned))
70 Bits
.push_back(unsigned(uint64_t(PtrI
) >> 32));
72 void FoldingSetNodeID::AddInteger(signed I
) {
75 void FoldingSetNodeID::AddInteger(unsigned I
) {
78 void FoldingSetNodeID::AddInteger(long I
) {
79 AddInteger((unsigned long)I
);
81 void FoldingSetNodeID::AddInteger(unsigned long I
) {
82 if (sizeof(long) == sizeof(int))
83 AddInteger(unsigned(I
));
84 else if (sizeof(long) == sizeof(long long)) {
85 AddInteger((unsigned long long)I
);
87 llvm_unreachable("unexpected sizeof(long)");
90 void FoldingSetNodeID::AddInteger(long long I
) {
91 AddInteger((unsigned long long)I
);
93 void FoldingSetNodeID::AddInteger(unsigned long long I
) {
94 AddInteger(unsigned(I
));
95 if ((uint64_t)(int)I
!= I
)
96 Bits
.push_back(unsigned(I
>> 32));
99 void FoldingSetNodeID::AddString(StringRef String
) {
100 unsigned Size
= String
.size();
101 Bits
.push_back(Size
);
104 unsigned Units
= Size
/ 4;
106 const unsigned *Base
= (const unsigned*) String
.data();
108 // If the string is aligned do a bulk transfer.
109 if (!((intptr_t)Base
& 3)) {
110 Bits
.append(Base
, Base
+ Units
);
111 Pos
= (Units
+ 1) * 4;
113 // Otherwise do it the hard way.
114 // To be compatible with above bulk transfer, we need to take endianness
116 if (sys::isBigEndianHost()) {
117 for (Pos
+= 4; Pos
<= Size
; Pos
+= 4) {
118 unsigned V
= ((unsigned char)String
[Pos
- 4] << 24) |
119 ((unsigned char)String
[Pos
- 3] << 16) |
120 ((unsigned char)String
[Pos
- 2] << 8) |
121 (unsigned char)String
[Pos
- 1];
125 assert(sys::isLittleEndianHost() && "Unexpected host endianness");
126 for (Pos
+= 4; Pos
<= Size
; Pos
+= 4) {
127 unsigned V
= ((unsigned char)String
[Pos
- 1] << 24) |
128 ((unsigned char)String
[Pos
- 2] << 16) |
129 ((unsigned char)String
[Pos
- 3] << 8) |
130 (unsigned char)String
[Pos
- 4];
136 // With the leftover bits.
138 // Pos will have overshot size by 4 - #bytes left over.
139 // No need to take endianness into account here - this is always executed.
140 switch (Pos
- Size
) {
141 case 1: V
= (V
<< 8) | (unsigned char)String
[Size
- 3]; // Fall thru.
142 case 2: V
= (V
<< 8) | (unsigned char)String
[Size
- 2]; // Fall thru.
143 case 3: V
= (V
<< 8) | (unsigned char)String
[Size
- 1]; break;
144 default: return; // Nothing left.
150 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to
151 /// lookup the node in the FoldingSetImpl.
152 unsigned FoldingSetNodeID::ComputeHash() const {
153 return FoldingSetNodeIDRef(Bits
.data(), Bits
.size()).ComputeHash();
156 /// operator== - Used to compare two nodes to each other.
158 bool FoldingSetNodeID::operator==(const FoldingSetNodeID
&RHS
)const{
159 return *this == FoldingSetNodeIDRef(RHS
.Bits
.data(), RHS
.Bits
.size());
162 /// operator== - Used to compare two nodes to each other.
164 bool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS
) const {
165 return FoldingSetNodeIDRef(Bits
.data(), Bits
.size()) == RHS
;
168 /// Intern - Copy this node's data to a memory region allocated from the
169 /// given allocator and return a FoldingSetNodeIDRef describing the
172 FoldingSetNodeID::Intern(BumpPtrAllocator
&Allocator
) const {
173 unsigned *New
= Allocator
.Allocate
<unsigned>(Bits
.size());
174 std::uninitialized_copy(Bits
.begin(), Bits
.end(), New
);
175 return FoldingSetNodeIDRef(New
, Bits
.size());
178 //===----------------------------------------------------------------------===//
179 /// Helper functions for FoldingSetImpl.
181 /// GetNextPtr - In order to save space, each bucket is a
182 /// singly-linked-list. In order to make deletion more efficient, we make
183 /// the list circular, so we can delete a node without computing its hash.
184 /// The problem with this is that the start of the hash buckets are not
185 /// Nodes. If NextInBucketPtr is a bucket pointer, this method returns null:
186 /// use GetBucketPtr when this happens.
187 static FoldingSetImpl::Node
*GetNextPtr(void *NextInBucketPtr
) {
188 // The low bit is set if this is the pointer back to the bucket.
189 if (reinterpret_cast<intptr_t>(NextInBucketPtr
) & 1)
192 return static_cast<FoldingSetImpl::Node
*>(NextInBucketPtr
);
197 static void **GetBucketPtr(void *NextInBucketPtr
) {
198 intptr_t Ptr
= reinterpret_cast<intptr_t>(NextInBucketPtr
);
199 assert((Ptr
& 1) && "Not a bucket pointer");
200 return reinterpret_cast<void**>(Ptr
& ~intptr_t(1));
203 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
204 /// the specified ID.
205 static void **GetBucketFor(unsigned Hash
, void **Buckets
, unsigned NumBuckets
) {
206 // NumBuckets is always a power of 2.
207 unsigned BucketNum
= Hash
& (NumBuckets
-1);
208 return Buckets
+ BucketNum
;
211 /// AllocateBuckets - Allocated initialized bucket memory.
212 static void **AllocateBuckets(unsigned NumBuckets
) {
213 void **Buckets
= static_cast<void**>(calloc(NumBuckets
+1, sizeof(void*)));
214 // Set the very last bucket to be a non-null "pointer".
215 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
219 //===----------------------------------------------------------------------===//
220 // FoldingSetImpl Implementation
222 FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize
) {
223 assert(5 < Log2InitSize
&& Log2InitSize
< 32 &&
224 "Initial hash table size out of range");
225 NumBuckets
= 1 << Log2InitSize
;
226 Buckets
= AllocateBuckets(NumBuckets
);
229 FoldingSetImpl::~FoldingSetImpl() {
232 void FoldingSetImpl::clear() {
233 // Set all but the last bucket to null pointers.
234 memset(Buckets
, 0, NumBuckets
*sizeof(void*));
236 // Set the very last bucket to be a non-null "pointer".
237 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
239 // Reset the node count to zero.
243 /// GrowHashTable - Double the size of the hash table and rehash everything.
245 void FoldingSetImpl::GrowHashTable() {
246 void **OldBuckets
= Buckets
;
247 unsigned OldNumBuckets
= NumBuckets
;
250 // Clear out new buckets.
251 Buckets
= AllocateBuckets(NumBuckets
);
254 // Walk the old buckets, rehashing nodes into their new place.
255 FoldingSetNodeID TempID
;
256 for (unsigned i
= 0; i
!= OldNumBuckets
; ++i
) {
257 void *Probe
= OldBuckets
[i
];
258 if (!Probe
) continue;
259 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
260 // Figure out the next link, remove NodeInBucket from the old link.
261 Probe
= NodeInBucket
->getNextInBucket();
262 NodeInBucket
->SetNextInBucket(0);
264 // Insert the node into the new bucket, after recomputing the hash.
265 InsertNode(NodeInBucket
,
266 GetBucketFor(ComputeNodeHash(NodeInBucket
, TempID
),
267 Buckets
, NumBuckets
));
275 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
276 /// return it. If not, return the insertion token that will make insertion
279 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID
&ID
,
282 void **Bucket
= GetBucketFor(ID
.ComputeHash(), Buckets
, NumBuckets
);
283 void *Probe
= *Bucket
;
287 FoldingSetNodeID TempID
;
288 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
289 if (NodeEquals(NodeInBucket
, ID
, TempID
))
293 Probe
= NodeInBucket
->getNextInBucket();
296 // Didn't find the node, return null with the bucket as the InsertPos.
301 /// InsertNode - Insert the specified node into the folding set, knowing that it
302 /// is not already in the map. InsertPos must be obtained from
303 /// FindNodeOrInsertPos.
304 void FoldingSetImpl::InsertNode(Node
*N
, void *InsertPos
) {
305 assert(N
->getNextInBucket() == 0);
306 // Do we need to grow the hashtable?
307 if (NumNodes
+1 > NumBuckets
*2) {
309 FoldingSetNodeID TempID
;
310 InsertPos
= GetBucketFor(ComputeNodeHash(N
, TempID
), Buckets
, NumBuckets
);
315 /// The insert position is actually a bucket pointer.
316 void **Bucket
= static_cast<void**>(InsertPos
);
318 void *Next
= *Bucket
;
320 // If this is the first insertion into this bucket, its next pointer will be
321 // null. Pretend as if it pointed to itself, setting the low bit to indicate
322 // that it is a pointer to the bucket.
324 Next
= reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket
)|1);
326 // Set the node's next pointer, and make the bucket point to the node.
327 N
->SetNextInBucket(Next
);
331 /// RemoveNode - Remove a node from the folding set, returning true if one was
332 /// removed or false if the node was not in the folding set.
333 bool FoldingSetImpl::RemoveNode(Node
*N
) {
334 // Because each bucket is a circular list, we don't need to compute N's hash
336 void *Ptr
= N
->getNextInBucket();
337 if (Ptr
== 0) return false; // Not in folding set.
340 N
->SetNextInBucket(0);
342 // Remember what N originally pointed to, either a bucket or another node.
343 void *NodeNextPtr
= Ptr
;
345 // Chase around the list until we find the node (or bucket) which points to N.
347 if (Node
*NodeInBucket
= GetNextPtr(Ptr
)) {
349 Ptr
= NodeInBucket
->getNextInBucket();
351 // We found a node that points to N, change it to point to N's next node,
352 // removing N from the list.
354 NodeInBucket
->SetNextInBucket(NodeNextPtr
);
358 void **Bucket
= GetBucketPtr(Ptr
);
361 // If we found that the bucket points to N, update the bucket to point to
364 *Bucket
= NodeNextPtr
;
371 /// GetOrInsertNode - If there is an existing simple Node exactly
372 /// equal to the specified node, return it. Otherwise, insert 'N' and it
374 FoldingSetImpl::Node
*FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node
*N
) {
376 GetNodeProfile(N
, ID
);
378 if (Node
*E
= FindNodeOrInsertPos(ID
, IP
))
384 //===----------------------------------------------------------------------===//
385 // FoldingSetIteratorImpl Implementation
387 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket
) {
388 // Skip to the first non-null non-self-cycle bucket.
389 while (*Bucket
!= reinterpret_cast<void*>(-1) &&
390 (*Bucket
== 0 || GetNextPtr(*Bucket
) == 0))
393 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
396 void FoldingSetIteratorImpl::advance() {
397 // If there is another link within this bucket, go to it.
398 void *Probe
= NodePtr
->getNextInBucket();
400 if (FoldingSetNode
*NextNodeInBucket
= GetNextPtr(Probe
))
401 NodePtr
= NextNodeInBucket
;
403 // Otherwise, this is the last link in this bucket.
404 void **Bucket
= GetBucketPtr(Probe
);
406 // Skip to the next non-null non-self-cycle bucket.
409 } while (*Bucket
!= reinterpret_cast<void*>(-1) &&
410 (*Bucket
== 0 || GetNextPtr(*Bucket
) == 0));
412 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
416 //===----------------------------------------------------------------------===//
417 // FoldingSetBucketIteratorImpl Implementation
419 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket
) {
420 Ptr
= (*Bucket
== 0 || GetNextPtr(*Bucket
) == 0) ? (void*) Bucket
: *Bucket
;