1 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements a hash set that can be used to remove duplication of
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/FoldingSet.h"
15 #include "llvm/ADT/Hashing.h"
16 #include "llvm/Support/Allocator.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Host.h"
19 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
25 // FoldingSetNodeIDRef Implementation
27 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
28 /// used to lookup the node in the FoldingSetBase.
29 unsigned FoldingSetNodeIDRef::ComputeHash() const {
30 return static_cast<unsigned>(hash_combine_range(Data
, Data
+Size
));
33 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS
) const {
34 if (Size
!= RHS
.Size
) return false;
35 return memcmp(Data
, RHS
.Data
, Size
*sizeof(*Data
)) == 0;
38 /// Used to compare the "ordering" of two nodes as defined by the
39 /// profiled bits and their ordering defined by memcmp().
40 bool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS
) const {
42 return Size
< RHS
.Size
;
43 return memcmp(Data
, RHS
.Data
, Size
*sizeof(*Data
)) < 0;
46 //===----------------------------------------------------------------------===//
47 // FoldingSetNodeID Implementation
49 /// Add* - Add various data types to Bit data.
51 void FoldingSetNodeID::AddPointer(const void *Ptr
) {
52 // Note: this adds pointers to the hash using sizes and endianness that
53 // depend on the host. It doesn't matter, however, because hashing on
54 // pointer values is inherently unstable. Nothing should depend on the
55 // ordering of nodes in the folding set.
56 static_assert(sizeof(uintptr_t) <= sizeof(unsigned long long),
57 "unexpected pointer size");
58 AddInteger(reinterpret_cast<uintptr_t>(Ptr
));
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 AddInteger(unsigned(I
>> 32));
86 void FoldingSetNodeID::AddString(StringRef String
) {
87 unsigned Size
= String
.size();
91 unsigned Units
= Size
/ 4;
93 const unsigned *Base
= (const unsigned*) String
.data();
95 // If the string is aligned do a bulk transfer.
96 if (!((intptr_t)Base
& 3)) {
97 Bits
.append(Base
, Base
+ Units
);
98 Pos
= (Units
+ 1) * 4;
100 // Otherwise do it the hard way.
101 // To be compatible with above bulk transfer, we need to take endianness
103 static_assert(sys::IsBigEndianHost
|| sys::IsLittleEndianHost
,
104 "Unexpected host endianness");
105 if (sys::IsBigEndianHost
) {
106 for (Pos
+= 4; Pos
<= Size
; Pos
+= 4) {
107 unsigned V
= ((unsigned char)String
[Pos
- 4] << 24) |
108 ((unsigned char)String
[Pos
- 3] << 16) |
109 ((unsigned char)String
[Pos
- 2] << 8) |
110 (unsigned char)String
[Pos
- 1];
113 } else { // Little-endian host
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]; LLVM_FALLTHROUGH
;
130 case 2: V
= (V
<< 8) | (unsigned char)String
[Size
- 2]; LLVM_FALLTHROUGH
;
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 FoldingSetBase.
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 FoldingSetBase.
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 FoldingSetBase::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<FoldingSetBase::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**>(safe_calloc(NumBuckets
+ 1,
218 // Set the very last bucket to be a non-null "pointer".
219 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
223 //===----------------------------------------------------------------------===//
224 // FoldingSetBase Implementation
226 void FoldingSetBase::anchor() {}
228 FoldingSetBase::FoldingSetBase(unsigned Log2InitSize
) {
229 assert(5 < Log2InitSize
&& Log2InitSize
< 32 &&
230 "Initial hash table size out of range");
231 NumBuckets
= 1 << Log2InitSize
;
232 Buckets
= AllocateBuckets(NumBuckets
);
236 FoldingSetBase::FoldingSetBase(FoldingSetBase
&&Arg
)
237 : Buckets(Arg
.Buckets
), NumBuckets(Arg
.NumBuckets
), NumNodes(Arg
.NumNodes
) {
238 Arg
.Buckets
= nullptr;
243 FoldingSetBase
&FoldingSetBase::operator=(FoldingSetBase
&&RHS
) {
244 free(Buckets
); // This may be null if the set is in a moved-from state.
245 Buckets
= RHS
.Buckets
;
246 NumBuckets
= RHS
.NumBuckets
;
247 NumNodes
= RHS
.NumNodes
;
248 RHS
.Buckets
= nullptr;
254 FoldingSetBase::~FoldingSetBase() {
258 void FoldingSetBase::clear() {
259 // Set all but the last bucket to null pointers.
260 memset(Buckets
, 0, NumBuckets
*sizeof(void*));
262 // Set the very last bucket to be a non-null "pointer".
263 Buckets
[NumBuckets
] = reinterpret_cast<void*>(-1);
265 // Reset the node count to zero.
269 void FoldingSetBase::GrowBucketCount(unsigned NewBucketCount
) {
270 assert((NewBucketCount
> NumBuckets
) && "Can't shrink a folding set with GrowBucketCount");
271 assert(isPowerOf2_32(NewBucketCount
) && "Bad bucket count!");
272 void **OldBuckets
= Buckets
;
273 unsigned OldNumBuckets
= NumBuckets
;
275 // Clear out new buckets.
276 Buckets
= AllocateBuckets(NewBucketCount
);
277 // Set NumBuckets only if allocation of new buckets was successful.
278 NumBuckets
= NewBucketCount
;
281 // Walk the old buckets, rehashing nodes into their new place.
282 FoldingSetNodeID TempID
;
283 for (unsigned i
= 0; i
!= OldNumBuckets
; ++i
) {
284 void *Probe
= OldBuckets
[i
];
285 if (!Probe
) continue;
286 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
287 // Figure out the next link, remove NodeInBucket from the old link.
288 Probe
= NodeInBucket
->getNextInBucket();
289 NodeInBucket
->SetNextInBucket(nullptr);
291 // Insert the node into the new bucket, after recomputing the hash.
292 InsertNode(NodeInBucket
,
293 GetBucketFor(ComputeNodeHash(NodeInBucket
, TempID
),
294 Buckets
, NumBuckets
));
302 /// GrowHashTable - Double the size of the hash table and rehash everything.
304 void FoldingSetBase::GrowHashTable() {
305 GrowBucketCount(NumBuckets
* 2);
308 void FoldingSetBase::reserve(unsigned EltCount
) {
309 // This will give us somewhere between EltCount / 2 and
310 // EltCount buckets. This puts us in the load factor
311 // range of 1.0 - 2.0.
312 if(EltCount
< capacity())
314 GrowBucketCount(PowerOf2Floor(EltCount
));
317 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
318 /// return it. If not, return the insertion token that will make insertion
320 FoldingSetBase::Node
*
321 FoldingSetBase::FindNodeOrInsertPos(const FoldingSetNodeID
&ID
,
323 unsigned IDHash
= ID
.ComputeHash();
324 void **Bucket
= GetBucketFor(IDHash
, Buckets
, NumBuckets
);
325 void *Probe
= *Bucket
;
329 FoldingSetNodeID TempID
;
330 while (Node
*NodeInBucket
= GetNextPtr(Probe
)) {
331 if (NodeEquals(NodeInBucket
, ID
, IDHash
, TempID
))
335 Probe
= NodeInBucket
->getNextInBucket();
338 // Didn't find the node, return null with the bucket as the InsertPos.
343 /// InsertNode - Insert the specified node into the folding set, knowing that it
344 /// is not already in the map. InsertPos must be obtained from
345 /// FindNodeOrInsertPos.
346 void FoldingSetBase::InsertNode(Node
*N
, void *InsertPos
) {
347 assert(!N
->getNextInBucket());
348 // Do we need to grow the hashtable?
349 if (NumNodes
+1 > capacity()) {
351 FoldingSetNodeID TempID
;
352 InsertPos
= GetBucketFor(ComputeNodeHash(N
, TempID
), Buckets
, NumBuckets
);
357 /// The insert position is actually a bucket pointer.
358 void **Bucket
= static_cast<void**>(InsertPos
);
360 void *Next
= *Bucket
;
362 // If this is the first insertion into this bucket, its next pointer will be
363 // null. Pretend as if it pointed to itself, setting the low bit to indicate
364 // that it is a pointer to the bucket.
366 Next
= reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket
)|1);
368 // Set the node's next pointer, and make the bucket point to the node.
369 N
->SetNextInBucket(Next
);
373 /// RemoveNode - Remove a node from the folding set, returning true if one was
374 /// removed or false if the node was not in the folding set.
375 bool FoldingSetBase::RemoveNode(Node
*N
) {
376 // Because each bucket is a circular list, we don't need to compute N's hash
378 void *Ptr
= N
->getNextInBucket();
379 if (!Ptr
) return false; // Not in folding set.
382 N
->SetNextInBucket(nullptr);
384 // Remember what N originally pointed to, either a bucket or another node.
385 void *NodeNextPtr
= Ptr
;
387 // Chase around the list until we find the node (or bucket) which points to N.
389 if (Node
*NodeInBucket
= GetNextPtr(Ptr
)) {
391 Ptr
= NodeInBucket
->getNextInBucket();
393 // We found a node that points to N, change it to point to N's next node,
394 // removing N from the list.
396 NodeInBucket
->SetNextInBucket(NodeNextPtr
);
400 void **Bucket
= GetBucketPtr(Ptr
);
403 // If we found that the bucket points to N, update the bucket to point to
406 *Bucket
= NodeNextPtr
;
413 /// GetOrInsertNode - If there is an existing simple Node exactly
414 /// equal to the specified node, return it. Otherwise, insert 'N' and it
416 FoldingSetBase::Node
*FoldingSetBase::GetOrInsertNode(FoldingSetBase::Node
*N
) {
418 GetNodeProfile(N
, ID
);
420 if (Node
*E
= FindNodeOrInsertPos(ID
, IP
))
426 //===----------------------------------------------------------------------===//
427 // FoldingSetIteratorImpl Implementation
429 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket
) {
430 // Skip to the first non-null non-self-cycle bucket.
431 while (*Bucket
!= reinterpret_cast<void*>(-1) &&
432 (!*Bucket
|| !GetNextPtr(*Bucket
)))
435 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
438 void FoldingSetIteratorImpl::advance() {
439 // If there is another link within this bucket, go to it.
440 void *Probe
= NodePtr
->getNextInBucket();
442 if (FoldingSetNode
*NextNodeInBucket
= GetNextPtr(Probe
))
443 NodePtr
= NextNodeInBucket
;
445 // Otherwise, this is the last link in this bucket.
446 void **Bucket
= GetBucketPtr(Probe
);
448 // Skip to the next non-null non-self-cycle bucket.
451 } while (*Bucket
!= reinterpret_cast<void*>(-1) &&
452 (!*Bucket
|| !GetNextPtr(*Bucket
)));
454 NodePtr
= static_cast<FoldingSetNode
*>(*Bucket
);
458 //===----------------------------------------------------------------------===//
459 // FoldingSetBucketIteratorImpl Implementation
461 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket
) {
462 Ptr
= (!*Bucket
|| !GetNextPtr(*Bucket
)) ? (void*) Bucket
: *Bucket
;