LLVM 23.0.0git
FoldingSet.h
Go to the documentation of this file.
1//===- llvm/ADT/FoldingSet.h - Uniquing Hash Set ----------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines a hash set that can be used to remove duplication of nodes
11/// in a graph. This code was originally created by Chris Lattner for use with
12/// SelectionDAGCSEMap, but was isolated to provide use across the llvm code
13/// set.
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_FOLDINGSET_H
17#define LLVM_ADT_FOLDINGSET_H
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/Hashing.h"
23#include "llvm/ADT/iterator.h"
26#include "llvm/Support/xxhash.h"
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <type_traits>
31#include <utility>
32
33namespace llvm {
34
35/// This folding set used for two purposes:
36/// 1. Given information about a node we want to create, look up the unique
37/// instance of the node in the set. If the node already exists, return
38/// it, otherwise return the bucket it should be inserted into.
39/// 2. Given a node that has already been created, remove it from the set.
40///
41/// This class is implemented as a single-link chained hash table, where the
42/// "buckets" are actually the nodes themselves (the next pointer is in the
43/// node). The last node points back to the bucket to simplify node removal.
44///
45/// Any node that is to be included in the folding set must be a subclass of
46/// FoldingSetNode. The node class must also define a Profile method used to
47/// establish the unique bits of data for the node. The Profile method is
48/// passed a FoldingSetNodeID object which is used to gather the bits. Just
49/// call one of the Add* functions defined in the FoldingSetBase::NodeID class.
50/// NOTE: That the folding set does not own the nodes and it is the
51/// responsibility of the user to dispose of the nodes.
52///
53/// Eg.
54/// class MyNode : public FoldingSetNode {
55/// private:
56/// std::string Name;
57/// unsigned Value;
58/// public:
59/// MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
60/// ...
61/// void Profile(FoldingSetNodeID &ID) const {
62/// ID.AddString(Name);
63/// ID.AddInteger(Value);
64/// }
65/// ...
66/// };
67///
68/// To define the folding set itself use the FoldingSet template;
69///
70/// Eg.
71/// FoldingSet<MyNode> MyFoldingSet;
72///
73/// Four public methods are available to manipulate the folding set;
74///
75/// 1) If you have an existing node that you want add to the set but unsure
76/// that the node might already exist then call;
77///
78/// MyNode *M = MyFoldingSet.GetOrInsertNode(N);
79///
80/// If The result is equal to the input then the node has been inserted.
81/// Otherwise, the result is the node existing in the folding set, and the
82/// input can be discarded (use the result instead.)
83///
84/// 2) If you are ready to construct a node but want to check if it already
85/// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
86/// check;
87///
88/// FoldingSetNodeID ID;
89/// ID.AddString(Name);
90/// ID.AddInteger(Value);
91/// void *InsertPoint;
92///
93/// MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
94///
95/// If found then M will be non-NULL, else InsertPoint will point to where it
96/// should be inserted using InsertNode.
97///
98/// 3) If you get a NULL result from FindNodeOrInsertPos then you can insert a
99/// new node with InsertNode;
100///
101/// MyFoldingSet.InsertNode(M, InsertPoint);
102///
103/// 4) Finally, if you want to remove a node from the folding set call;
104///
105/// bool WasRemoved = MyFoldingSet.RemoveNode(M);
106///
107/// The result indicates whether the node existed in the folding set.
108
109class FoldingSetNodeID;
110class StringRef;
111
112//===----------------------------------------------------------------------===//
113
114/// DefaultFoldingSetTrait - This class provides default implementations
115/// for FoldingSetTrait implementations.
116template<typename T> struct DefaultFoldingSetTrait {
117 static void Profile(const T &X, FoldingSetNodeID &ID) {
118 X.Profile(ID);
119 }
120 static void Profile(T &X, FoldingSetNodeID &ID) {
121 X.Profile(ID);
122 }
123
124 // Equals - Test if the profile for X would match ID, using TempID
125 // to compute a temporary ID if necessary. The default implementation
126 // just calls Profile and does a regular comparison. Implementations
127 // can override this to provide more efficient implementations.
128 static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
129 FoldingSetNodeID &TempID);
130
131 // ComputeHash - Compute a hash value for X, using TempID to
132 // compute a temporary ID if necessary. The default implementation
133 // just calls Profile and does a regular hash computation.
134 // Implementations can override this to provide more efficient
135 // implementations.
136 static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
137};
138
139/// FoldingSetTrait - This trait class is used to define behavior of how
140/// to "profile" (in the FoldingSet parlance) an object of a given type.
141/// The default behavior is to invoke a 'Profile' method on an object, but
142/// through template specialization the behavior can be tailored for specific
143/// types. Combined with the FoldingSetNodeWrapper class, one can add objects
144/// to FoldingSets that were not originally designed to have that behavior.
145template <typename T, typename Enable = void>
147
148/// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
149/// for ContextualFoldingSets.
150template<typename T, typename Ctx>
152 static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
153 X.Profile(ID, Context);
154 }
155
156 static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
157 FoldingSetNodeID &TempID, Ctx Context);
158 static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
159 Ctx Context);
160};
161
162/// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
163/// ContextualFoldingSets.
164template<typename T, typename Ctx> struct ContextualFoldingSetTrait
165 : public DefaultContextualFoldingSetTrait<T, Ctx> {};
166
167//===--------------------------------------------------------------------===//
168/// FoldingSetNodeIDRef - This class describes a reference to an interned
169/// FoldingSetNodeID, which can be a useful to store node id data rather
170/// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
171/// is often much larger than necessary, and the possibility of heap
172/// allocation means it requires a non-trivial destructor call.
174 const unsigned *Data = nullptr;
175 size_t Size = 0;
176
177public:
179 FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
180
181 // Compute a strong hash value used to lookup the node in the FoldingSetBase.
182 // The hash value is not guaranteed to be deterministic across processes.
183 unsigned ComputeHash() const {
184 return static_cast<unsigned>(hash_combine_range(Data, Data + Size));
185 }
186
187 // Compute a deterministic hash value across processes that is suitable for
188 // on-disk serialization.
189 unsigned computeStableHash() const {
190 return static_cast<unsigned>(xxh3_64bits(ArrayRef(
191 reinterpret_cast<const uint8_t *>(Data), sizeof(unsigned) * Size)));
192 }
193
195
196 bool operator!=(FoldingSetNodeIDRef RHS) const { return !(*this == RHS); }
197
198 /// Used to compare the "ordering" of two nodes as defined by the
199 /// profiled bits and their ordering defined by memcmp().
201
202 const unsigned *getData() const { return Data; }
203 size_t getSize() const { return Size; }
204};
205
206//===--------------------------------------------------------------------===//
207/// FoldingSetNodeID - This class is used to gather all the unique data bits of
208/// a node. When all the bits are gathered this class is used to produce a
209/// hash value for the node.
211 /// Bits - Vector of all the data bits that make the node unique.
212 /// Use a SmallVector to avoid a heap allocation in the common case.
214
215 template <typename T> void AddIntegerImpl(T I) {
216 static_assert(std::is_integral_v<T> && sizeof(T) <= sizeof(unsigned) * 2,
217 "T must be an integer type no wider than 64 bits");
218 Bits.push_back(static_cast<unsigned>(I));
219 if constexpr (sizeof(unsigned) < sizeof(T))
220 Bits.push_back(static_cast<unsigned long long>(I) >> 32);
221 }
222
223public:
224 FoldingSetNodeID() = default;
225
227 : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
228
229 /// Add* - Add various data types to Bit data.
230 void AddPointer(const void *Ptr) {
231 // Note: this adds pointers to the hash using sizes and endianness that
232 // depend on the host. It doesn't matter, however, because hashing on
233 // pointer values is inherently unstable. Nothing should depend on the
234 // ordering of nodes in the folding set.
235 static_assert(sizeof(uintptr_t) <= sizeof(unsigned long long),
236 "unexpected pointer size");
237 AddInteger(reinterpret_cast<uintptr_t>(Ptr));
238 }
239 void AddInteger(signed I) { AddIntegerImpl(I); }
240 void AddInteger(unsigned I) { AddIntegerImpl(I); }
241 void AddInteger(long I) { AddIntegerImpl(I); }
242 void AddInteger(unsigned long I) { AddIntegerImpl(I); }
243 void AddInteger(long long I) { AddIntegerImpl(I); }
244 void AddInteger(unsigned long long I) { AddIntegerImpl(I); }
245 void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
248
249 template <typename T>
250 inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
251
252 /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
253 /// object to be used to compute a new profile.
254 inline void clear() { Bits.clear(); }
255
256 // Compute a strong hash value for this FoldingSetNodeID, used to lookup the
257 // node in the FoldingSetBase. The hash value is not guaranteed to be
258 // deterministic across processes.
259 unsigned ComputeHash() const {
260 return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
261 }
262
263 // Compute a deterministic hash value across processes that is suitable for
264 // on-disk serialization.
265 unsigned computeStableHash() const {
266 return FoldingSetNodeIDRef(Bits.data(), Bits.size()).computeStableHash();
267 }
268
269 /// operator== - Used to compare two nodes to each other.
270 LLVM_ABI bool operator==(const FoldingSetNodeID &RHS) const;
271 LLVM_ABI bool operator==(const FoldingSetNodeIDRef RHS) const;
272
273 bool operator!=(const FoldingSetNodeID &RHS) const { return !(*this == RHS); }
274 bool operator!=(const FoldingSetNodeIDRef RHS) const { return !(*this ==RHS);}
275
276 /// Used to compare the "ordering" of two nodes as defined by the
277 /// profiled bits and their ordering defined by memcmp().
278 LLVM_ABI bool operator<(const FoldingSetNodeID &RHS) const;
279 LLVM_ABI bool operator<(const FoldingSetNodeIDRef RHS) const;
280
281 /// Intern - Copy this node's data to a memory region allocated from the
282 /// given allocator and return a FoldingSetNodeIDRef describing the
283 /// interned data.
285};
286
287//===----------------------------------------------------------------------===//
288/// FoldingSetBase - Implements the folding set functionality. The main
289/// structure is an array of buckets. Each bucket is indexed by the hash of
290/// the nodes it contains. The bucket itself points to the nodes contained
291/// in the bucket via a singly linked list. The last node in the list points
292/// back to the bucket to facilitate node removal.
293///
295protected:
296 /// Buckets - Array of bucket chains.
297 void **Buckets;
298
299 /// NumBuckets - Length of the Buckets array. Always a power of 2.
300 unsigned NumBuckets;
301
302 /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
303 /// is greater than twice the number of buckets.
304 unsigned NumNodes;
305
306 LLVM_ABI explicit FoldingSetBase(unsigned Log2InitSize = 6);
310
311public:
312 //===--------------------------------------------------------------------===//
313 /// Node - This class is used to maintain the singly linked bucket list in
314 /// a folding set.
315 class Node {
316 private:
317 // NextInFoldingSetBucket - next link in the bucket list.
318 void *NextInFoldingSetBucket = nullptr;
319
320 public:
321 Node() = default;
322
323 // Accessors
324 void *getNextInBucket() const { return NextInFoldingSetBucket; }
325 void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
326 };
327
328 /// clear - Remove all nodes from the folding set.
329 LLVM_ABI void clear();
330
331 /// size - Returns the number of nodes in the folding set.
332 unsigned size() const { return NumNodes; }
333
334 /// empty - Returns true if there are no nodes in the folding set.
335 bool empty() const { return NumNodes == 0; }
336
337 /// capacity - Returns the number of nodes permitted in the folding set
338 /// before a rebucket operation is performed.
339 unsigned capacity() {
340 // We allow a load factor of up to 2.0,
341 // so that means our capacity is NumBuckets * 2
342 return NumBuckets * 2;
343 }
344
345protected:
346 /// Functions provided by the derived class to compute folding properties.
347 /// This is effectively a vtable for FoldingSetBase, except that we don't
348 /// actually store a pointer to it in the object.
350 /// GetNodeProfile - Instantiations of the FoldingSet template implement
351 /// this function to gather data bits for the given node.
352 void (*GetNodeProfile)(const FoldingSetBase *Self, Node *N,
354
355 /// NodeEquals - Instantiations of the FoldingSet template implement
356 /// this function to compare the given node with the given ID.
358 const FoldingSetNodeID &ID, unsigned IDHash,
359 FoldingSetNodeID &TempID);
360
361 /// ComputeNodeHash - Instantiations of the FoldingSet template implement
362 /// this function to compute a hash value for the given node.
364 FoldingSetNodeID &TempID);
365 };
366
367private:
368 /// GrowHashTable - Double the size of the hash table and rehash everything.
369 void GrowHashTable(const FoldingSetInfo &Info);
370
371 /// GrowBucketCount - resize the hash table and rehash everything.
372 /// NewBucketCount must be a power of two, and must be greater than the old
373 /// bucket count.
374 void GrowBucketCount(unsigned NewBucketCount, const FoldingSetInfo &Info);
375
376protected:
377 // The below methods are protected to encourage subclasses to provide a more
378 // type-safe API.
379
380 /// reserve - Increase the number of buckets such that adding the
381 /// EltCount-th node won't cause a rebucket operation. reserve is permitted
382 /// to allocate more space than requested by EltCount.
383 LLVM_ABI void reserve(unsigned EltCount, const FoldingSetInfo &Info);
384
385 /// RemoveNode - Remove a node from the folding set, returning true if one
386 /// was removed or false if the node was not in the folding set.
387 LLVM_ABI bool RemoveNode(Node *N);
388
389 /// GetOrInsertNode - If there is an existing simple Node exactly
390 /// equal to the specified node, return it. Otherwise, insert 'N' and return
391 /// it instead.
393
394 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
395 /// return it. If not, return the insertion token that will make insertion
396 /// faster.
398 void *&InsertPos,
399 const FoldingSetInfo &Info);
400
401 /// InsertNode - Insert the specified node into the folding set, knowing that
402 /// it is not already in the folding set. InsertPos must be obtained from
403 /// FindNodeOrInsertPos.
404 LLVM_ABI void InsertNode(Node *N, void *InsertPos,
405 const FoldingSetInfo &Info);
406};
407
408// Convenience type to hide the implementation of the folding set.
410template<class T> class FoldingSetIterator;
411template<class T> class FoldingSetBucketIterator;
412
413// Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
414// require the definition of FoldingSetNodeID.
415template<typename T>
416inline bool
418 unsigned /*IDHash*/,
419 FoldingSetNodeID &TempID) {
421 return TempID == ID;
422}
423template<typename T>
424inline unsigned
429template<typename T, typename Ctx>
430inline bool
432 const FoldingSetNodeID &ID,
433 unsigned /*IDHash*/,
434 FoldingSetNodeID &TempID,
435 Ctx Context) {
437 return TempID == ID;
438}
439template<typename T, typename Ctx>
440inline unsigned
442 FoldingSetNodeID &TempID,
443 Ctx Context) {
445 return TempID.ComputeHash();
446}
447
448//===----------------------------------------------------------------------===//
449/// FoldingSetImpl - An implementation detail that lets us share code between
450/// FoldingSet and ContextualFoldingSet.
451template <class Derived, class T> class FoldingSetImpl : public FoldingSetBase {
452protected:
453 explicit FoldingSetImpl(unsigned Log2InitSize)
454 : FoldingSetBase(Log2InitSize) {}
455
458 ~FoldingSetImpl() = default;
459
460public:
462
465
467
470
472
474 return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
475 }
476
478 return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
479 }
480
481 /// reserve - Increase the number of buckets such that adding the
482 /// EltCount-th node won't cause a rebucket operation. reserve is permitted
483 /// to allocate more space than requested by EltCount.
484 void reserve(unsigned EltCount) {
485 return FoldingSetBase::reserve(EltCount, Derived::getFoldingSetInfo());
486 }
487
488 /// RemoveNode - Remove a node from the folding set, returning true if one
489 /// was removed or false if the node was not in the folding set.
490 bool RemoveNode(T *N) {
492 }
493
494 /// GetOrInsertNode - If there is an existing simple Node exactly
495 /// equal to the specified node, return it. Otherwise, insert 'N' and
496 /// return it instead.
498 return static_cast<T *>(
499 FoldingSetBase::GetOrInsertNode(N, Derived::getFoldingSetInfo()));
500 }
501
502 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
503 /// return it. If not, return the insertion token that will make insertion
504 /// faster.
505 T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
506 return static_cast<T *>(FoldingSetBase::FindNodeOrInsertPos(
507 ID, InsertPos, Derived::getFoldingSetInfo()));
508 }
509
510 /// InsertNode - Insert the specified node into the folding set, knowing that
511 /// it is not already in the folding set. InsertPos must be obtained from
512 /// FindNodeOrInsertPos.
513 void InsertNode(T *N, void *InsertPos) {
514 FoldingSetBase::InsertNode(N, InsertPos, Derived::getFoldingSetInfo());
515 }
516
517 /// InsertNode - Insert the specified node into the folding set, knowing that
518 /// it is not already in the folding set.
519 void InsertNode(T *N) {
520 T *Inserted = GetOrInsertNode(N);
521 (void)Inserted;
522 assert(Inserted == N && "Node already inserted!");
523 }
524};
525
526//===----------------------------------------------------------------------===//
527/// FoldingSet - This template class is used to instantiate a specialized
528/// implementation of the folding set to the node class T. T must be a
529/// subclass of FoldingSetNode and implement a Profile function.
530///
531/// Note that this set type is movable and move-assignable. However, its
532/// moved-from state is not a valid state for anything other than
533/// move-assigning and destroying. This is primarily to enable movable APIs
534/// that incorporate these objects.
535template <class T>
536class FoldingSet : public FoldingSetImpl<FoldingSet<T>, T> {
537 using Super = FoldingSetImpl<FoldingSet, T>;
538 using Node = typename Super::Node;
539
540 /// GetNodeProfile - Each instantiation of the FoldingSet needs to provide a
541 /// way to convert nodes into a unique specifier.
542 static void GetNodeProfile(const FoldingSetBase *, Node *N,
544 T *TN = static_cast<T *>(N);
546 }
547
548 /// NodeEquals - Instantiations may optionally provide a way to compare a
549 /// node with a specified ID.
550 static bool NodeEquals(const FoldingSetBase *, Node *N,
551 const FoldingSetNodeID &ID, unsigned IDHash,
552 FoldingSetNodeID &TempID) {
553 T *TN = static_cast<T *>(N);
554 return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
555 }
556
557 /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
558 /// hash value directly from a node.
559 static unsigned ComputeNodeHash(const FoldingSetBase *, Node *N,
560 FoldingSetNodeID &TempID) {
561 T *TN = static_cast<T *>(N);
562 return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
563 }
564
565 static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
566 static constexpr FoldingSetBase::FoldingSetInfo Info = {
567 GetNodeProfile, NodeEquals, ComputeNodeHash};
568 return Info;
569 }
570 friend Super;
571
572public:
573 explicit FoldingSet(unsigned Log2InitSize = 6) : Super(Log2InitSize) {}
574 FoldingSet(FoldingSet &&Arg) = default;
576};
577
578//===----------------------------------------------------------------------===//
579/// ContextualFoldingSet - This template class is a further refinement
580/// of FoldingSet which provides a context argument when calling
581/// Profile on its nodes. Currently, that argument is fixed at
582/// initialization time.
583///
584/// T must be a subclass of FoldingSetNode and implement a Profile
585/// function with signature
586/// void Profile(FoldingSetNodeID &, Ctx);
587template <class T, class Ctx>
589 : public FoldingSetImpl<ContextualFoldingSet<T, Ctx>, T> {
590 // Unfortunately, this can't derive from FoldingSet<T> because the
591 // construction of the vtable for FoldingSet<T> requires
592 // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
593 // requires a single-argument T::Profile().
594
596 using Node = typename Super::Node;
597
598 Ctx Context;
599
600 static const Ctx &getContext(const FoldingSetBase *Base) {
601 return static_cast<const ContextualFoldingSet*>(Base)->Context;
602 }
603
604 /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
605 /// way to convert nodes into a unique specifier.
606 static void GetNodeProfile(const FoldingSetBase *Base, Node *N,
608 T *TN = static_cast<T *>(N);
610 }
611
612 static bool NodeEquals(const FoldingSetBase *Base, Node *N,
613 const FoldingSetNodeID &ID, unsigned IDHash,
614 FoldingSetNodeID &TempID) {
615 T *TN = static_cast<T *>(N);
616 return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
618 }
619
620 static unsigned ComputeNodeHash(const FoldingSetBase *Base, Node *N,
621 FoldingSetNodeID &TempID) {
622 T *TN = static_cast<T *>(N);
625 }
626
627 static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
628 static constexpr FoldingSetBase::FoldingSetInfo Info = {
629 GetNodeProfile, NodeEquals, ComputeNodeHash};
630 return Info;
631 }
632 friend Super;
633
634public:
635 explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
636 : Super(Log2InitSize), Context(Context) {}
637
638 Ctx getContext() const { return Context; }
639};
640
641//===----------------------------------------------------------------------===//
642/// FoldingSetVector - This template class combines a FoldingSet and a vector
643/// to provide the interface of FoldingSet but with deterministic iteration
644/// order based on the insertion order. T must be a subclass of FoldingSetNode
645/// and implement a Profile function.
646template <class T, class VectorT = SmallVector<T*, 8>>
648 FoldingSet<T> Set;
649 VectorT Vector;
650
651public:
652 explicit FoldingSetVector(unsigned Log2InitSize = 6) : Set(Log2InitSize) {}
653
655
656 iterator begin() { return Vector.begin(); }
657 iterator end() { return Vector.end(); }
658
660
661 const_iterator begin() const { return Vector.begin(); }
662 const_iterator end() const { return Vector.end(); }
663
664 /// clear - Remove all nodes from the folding set.
665 void clear() { Set.clear(); Vector.clear(); }
666
667 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
668 /// return it. If not, return the insertion token that will make insertion
669 /// faster.
670 T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
671 return Set.FindNodeOrInsertPos(ID, InsertPos);
672 }
673
674 /// GetOrInsertNode - If there is an existing simple Node exactly
675 /// equal to the specified node, return it. Otherwise, insert 'N' and
676 /// return it instead.
678 T *Result = Set.GetOrInsertNode(N);
679 if (Result == N) Vector.push_back(N);
680 return Result;
681 }
682
683 /// InsertNode - Insert the specified node into the folding set, knowing that
684 /// it is not already in the folding set. InsertPos must be obtained from
685 /// FindNodeOrInsertPos.
686 void InsertNode(T *N, void *InsertPos) {
687 Set.InsertNode(N, InsertPos);
688 Vector.push_back(N);
689 }
690
691 /// InsertNode - Insert the specified node into the folding set, knowing that
692 /// it is not already in the folding set.
693 void InsertNode(T *N) {
694 Set.InsertNode(N);
695 Vector.push_back(N);
696 }
697
698 /// size - Returns the number of nodes in the folding set.
699 unsigned size() const { return Set.size(); }
700
701 /// empty - Returns true if there are no nodes in the folding set.
702 bool empty() const { return Set.empty(); }
703};
704
705//===----------------------------------------------------------------------===//
706/// FoldingSetIteratorImpl - This is the common iterator support shared by all
707/// folding sets, which knows how to walk the folding set hash table.
709protected:
711
712 LLVM_ABI FoldingSetIteratorImpl(void **Bucket);
713
714 LLVM_ABI void advance();
715
716public:
718 return NodePtr == RHS.NodePtr;
719 }
721 return NodePtr != RHS.NodePtr;
722 }
723};
724
725template <class T> class FoldingSetIterator : public FoldingSetIteratorImpl {
726public:
727 explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
728
729 T &operator*() const {
730 return *static_cast<T*>(NodePtr);
731 }
732
733 T *operator->() const {
734 return static_cast<T*>(NodePtr);
735 }
736
737 inline FoldingSetIterator &operator++() { // Preincrement
738 advance();
739 return *this;
740 }
741 FoldingSetIterator operator++(int) { // Postincrement
742 FoldingSetIterator tmp = *this; ++*this; return tmp;
743 }
744};
745
746//===----------------------------------------------------------------------===//
747/// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
748/// shared by all folding sets, which knows how to walk a particular bucket
749/// of a folding set hash table.
751protected:
752 void *Ptr;
753
754 LLVM_ABI explicit FoldingSetBucketIteratorImpl(void **Bucket);
755
756 FoldingSetBucketIteratorImpl(void **Bucket, bool) : Ptr(Bucket) {}
757
758 void advance() {
759 void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
760 uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
761 Ptr = reinterpret_cast<void*>(x);
762 }
763
764public:
766 return Ptr == RHS.Ptr;
767 }
769 return Ptr != RHS.Ptr;
770 }
771};
772
773template <class T>
775public:
776 explicit FoldingSetBucketIterator(void **Bucket) :
778
779 FoldingSetBucketIterator(void **Bucket, bool) :
781
782 T &operator*() const { return *static_cast<T*>(Ptr); }
783 T *operator->() const { return static_cast<T*>(Ptr); }
784
785 inline FoldingSetBucketIterator &operator++() { // Preincrement
786 advance();
787 return *this;
788 }
789 FoldingSetBucketIterator operator++(int) { // Postincrement
790 FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
791 }
792};
793
794//===----------------------------------------------------------------------===//
795/// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
796/// types in an enclosing object so that they can be inserted into FoldingSets.
797template <typename T>
799 T data;
800
801public:
802 template <typename... Ts>
803 explicit FoldingSetNodeWrapper(Ts &&... Args)
804 : data(std::forward<Ts>(Args)...) {}
805
807
808 T &getValue() { return data; }
809 const T &getValue() const { return data; }
810
811 operator T&() { return data; }
812 operator const T&() const { return data; }
813};
814
815//===----------------------------------------------------------------------===//
816/// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
817/// a FoldingSetNodeID value rather than requiring the node to recompute it
818/// each time it is needed. This trades space for speed (which can be
819/// significant if the ID is long), and it also permits nodes to drop
820/// information that would otherwise only be required for recomputing an ID.
822 FoldingSetNodeID FastID;
823
824protected:
825 explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
826
827public:
828 void Profile(FoldingSetNodeID &ID) const { ID.AddNodeID(FastID); }
829};
830
831//===----------------------------------------------------------------------===//
832// Partial specializations of FoldingSetTrait.
833
834template<typename T> struct FoldingSetTrait<T*> {
835 static inline void Profile(T *X, FoldingSetNodeID &ID) {
836 ID.AddPointer(X);
837 }
838};
839template <typename T1, typename T2>
840struct FoldingSetTrait<std::pair<T1, T2>> {
841 static inline void Profile(const std::pair<T1, T2> &P,
843 ID.Add(P.first);
844 ID.Add(P.second);
845 }
846};
847
848template <typename T>
849struct FoldingSetTrait<T, std::enable_if_t<std::is_enum<T>::value>> {
850 static void Profile(const T &X, FoldingSetNodeID &ID) {
851 ID.AddInteger(llvm::to_underlying(X));
852 }
853};
854
855} // end namespace llvm
856
857#endif // LLVM_ADT_FOLDINGSET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
Basic Register Allocator
This file contains library features backported from future STL versions.
This file defines the SmallVector class.
Value * RHS
static unsigned getSize(unsigned Kind)
ContextualFoldingSet(Ctx Context, unsigned Log2InitSize=6)
Definition FoldingSet.h:635
FastFoldingSetNode(const FoldingSetNodeID &ID)
Definition FoldingSet.h:825
void Profile(FoldingSetNodeID &ID) const
Definition FoldingSet.h:828
Node - This class is used to maintain the singly linked bucket list in a folding set.
Definition FoldingSet.h:315
void * getNextInBucket() const
Definition FoldingSet.h:324
void SetNextInBucket(void *N)
Definition FoldingSet.h:325
FoldingSetBase - Implements the folding set functionality.
Definition FoldingSet.h:294
LLVM_ABI FoldingSetBase(unsigned Log2InitSize=6)
void ** Buckets
Buckets - Array of bucket chains.
Definition FoldingSet.h:297
unsigned size() const
size - Returns the number of nodes in the folding set.
Definition FoldingSet.h:332
LLVM_ABI void reserve(unsigned EltCount, const FoldingSetInfo &Info)
reserve - Increase the number of buckets such that adding the EltCount-th node won't cause a rebucket...
LLVM_ABI bool RemoveNode(Node *N)
RemoveNode - Remove a node from the folding set, returning true if one was removed or false if the no...
LLVM_ABI FoldingSetBase & operator=(FoldingSetBase &&RHS)
LLVM_ABI ~FoldingSetBase()
unsigned NumBuckets
NumBuckets - Length of the Buckets array. Always a power of 2.
Definition FoldingSet.h:300
unsigned NumNodes
NumNodes - Number of nodes in the folding set.
Definition FoldingSet.h:304
unsigned capacity()
capacity - Returns the number of nodes permitted in the folding set before a rebucket operation is pe...
Definition FoldingSet.h:339
LLVM_ABI Node * GetOrInsertNode(Node *N, const FoldingSetInfo &Info)
GetOrInsertNode - If there is an existing simple Node exactly equal to the specified node,...
bool empty() const
empty - Returns true if there are no nodes in the folding set.
Definition FoldingSet.h:335
LLVM_ABI void InsertNode(Node *N, void *InsertPos, const FoldingSetInfo &Info)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
LLVM_ABI void clear()
clear - Remove all nodes from the folding set.
LLVM_ABI Node * FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos, const FoldingSetInfo &Info)
FindNodeOrInsertPos - Look up the node specified by ID.
LLVM_ABI FoldingSetBucketIteratorImpl(void **Bucket)
FoldingSetBucketIteratorImpl(void **Bucket, bool)
Definition FoldingSet.h:756
bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const
Definition FoldingSet.h:768
bool operator==(const FoldingSetBucketIteratorImpl &RHS) const
Definition FoldingSet.h:765
FoldingSetBucketIterator(void **Bucket, bool)
Definition FoldingSet.h:779
FoldingSetBucketIterator(void **Bucket)
Definition FoldingSet.h:776
FoldingSetBucketIterator operator++(int)
Definition FoldingSet.h:789
FoldingSetBucketIterator & operator++()
Definition FoldingSet.h:785
void reserve(unsigned EltCount)
reserve - Increase the number of buckets such that adding the EltCount-th node won't cause a rebucket...
Definition FoldingSet.h:484
FoldingSetIterator< T > iterator
Definition FoldingSet.h:461
const_iterator end() const
Definition FoldingSet.h:469
bucket_iterator bucket_begin(unsigned hash)
Definition FoldingSet.h:473
bool RemoveNode(T *N)
RemoveNode - Remove a node from the folding set, returning true if one was removed or false if the no...
Definition FoldingSet.h:490
~FoldingSetImpl()=default
FoldingSetImpl(FoldingSetImpl &&Arg)=default
FoldingSetBucketIterator< T > bucket_iterator
Definition FoldingSet.h:471
void InsertNode(T *N)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
Definition FoldingSet.h:519
void InsertNode(T *N, void *InsertPos)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
Definition FoldingSet.h:513
T * FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos)
FindNodeOrInsertPos - Look up the node specified by ID.
Definition FoldingSet.h:505
const_iterator begin() const
Definition FoldingSet.h:468
FoldingSetIterator< const T > const_iterator
Definition FoldingSet.h:466
FoldingSetImpl & operator=(FoldingSetImpl &&RHS)=default
T * GetOrInsertNode(T *N)
GetOrInsertNode - If there is an existing simple Node exactly equal to the specified node,...
Definition FoldingSet.h:497
FoldingSetImpl(unsigned Log2InitSize)
Definition FoldingSet.h:453
bucket_iterator bucket_end(unsigned hash)
Definition FoldingSet.h:477
LLVM_ABI FoldingSetIteratorImpl(void **Bucket)
bool operator==(const FoldingSetIteratorImpl &RHS) const
Definition FoldingSet.h:717
bool operator!=(const FoldingSetIteratorImpl &RHS) const
Definition FoldingSet.h:720
FoldingSetIterator(void **Bucket)
Definition FoldingSet.h:727
FoldingSetIterator operator++(int)
Definition FoldingSet.h:741
FoldingSetIterator & operator++()
Definition FoldingSet.h:737
FoldingSetNodeIDRef - This class describes a reference to an interned FoldingSetNodeID,...
Definition FoldingSet.h:173
unsigned computeStableHash() const
Definition FoldingSet.h:189
LLVM_ABI bool operator==(FoldingSetNodeIDRef) const
FoldingSetNodeIDRef(const unsigned *D, size_t S)
Definition FoldingSet.h:179
LLVM_ABI bool operator<(FoldingSetNodeIDRef) const
Used to compare the "ordering" of two nodes as defined by the profiled bits and their ordering define...
bool operator!=(FoldingSetNodeIDRef RHS) const
Definition FoldingSet.h:196
unsigned ComputeHash() const
Definition FoldingSet.h:183
const unsigned * getData() const
Definition FoldingSet.h:202
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:210
LLVM_ABI FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const
Intern - Copy this node's data to a memory region allocated from the given allocator and return a Fol...
void AddInteger(signed I)
Definition FoldingSet.h:239
void AddInteger(unsigned long I)
Definition FoldingSet.h:242
FoldingSetNodeID(FoldingSetNodeIDRef Ref)
Definition FoldingSet.h:226
unsigned computeStableHash() const
Definition FoldingSet.h:265
void AddPointer(const void *Ptr)
Add* - Add various data types to Bit data.
Definition FoldingSet.h:230
bool operator!=(const FoldingSetNodeIDRef RHS) const
Definition FoldingSet.h:274
void clear()
clear - Clear the accumulated profile, allowing this FoldingSetNodeID object to be used to compute a ...
Definition FoldingSet.h:254
void AddInteger(unsigned I)
Definition FoldingSet.h:240
void AddInteger(long I)
Definition FoldingSet.h:241
void AddBoolean(bool B)
Definition FoldingSet.h:245
LLVM_ABI bool operator==(const FoldingSetNodeID &RHS) const
operator== - Used to compare two nodes to each other.
bool operator!=(const FoldingSetNodeID &RHS) const
Definition FoldingSet.h:273
void AddInteger(unsigned long long I)
Definition FoldingSet.h:244
void AddInteger(long long I)
Definition FoldingSet.h:243
unsigned ComputeHash() const
Definition FoldingSet.h:259
LLVM_ABI bool operator<(const FoldingSetNodeID &RHS) const
Used to compare the "ordering" of two nodes as defined by the profiled bits and their ordering define...
LLVM_ABI void AddNodeID(const FoldingSetNodeID &ID)
void Add(const T &x)
Definition FoldingSet.h:250
LLVM_ABI void AddString(StringRef String)
Add* - Add various data types to Bit data.
FoldingSetNodeWrapper(Ts &&... Args)
Definition FoldingSet.h:803
const T & getValue() const
Definition FoldingSet.h:809
void Profile(FoldingSetNodeID &ID)
Definition FoldingSet.h:806
T * GetOrInsertNode(T *N)
GetOrInsertNode - If there is an existing simple Node exactly equal to the specified node,...
Definition FoldingSet.h:677
const_iterator end() const
Definition FoldingSet.h:662
void InsertNode(T *N)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
Definition FoldingSet.h:693
T * FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos)
FindNodeOrInsertPos - Look up the node specified by ID.
Definition FoldingSet.h:670
unsigned size() const
size - Returns the number of nodes in the folding set.
Definition FoldingSet.h:699
pointee_iterator< typename VectorT::const_iterator > const_iterator
Definition FoldingSet.h:659
pointee_iterator< typename VectorT::iterator > iterator
Definition FoldingSet.h:654
void clear()
clear - Remove all nodes from the folding set.
Definition FoldingSet.h:665
bool empty() const
empty - Returns true if there are no nodes in the folding set.
Definition FoldingSet.h:702
FoldingSetVector(unsigned Log2InitSize=6)
Definition FoldingSet.h:652
void InsertNode(T *N, void *InsertPos)
InsertNode - Insert the specified node into the folding set, knowing that it is not already in the fo...
Definition FoldingSet.h:686
const_iterator begin() const
Definition FoldingSet.h:661
FoldingSet - This template class is used to instantiate a specialized implementation of the folding s...
Definition FoldingSet.h:536
FoldingSet(FoldingSet &&Arg)=default
FoldingSet(unsigned Log2InitSize=6)
Definition FoldingSet.h:573
FoldingSet & operator=(FoldingSet &&RHS)=default
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI uint64_t xxh3_64bits(ArrayRef< uint8_t > data)
Definition xxhash.cpp:553
FoldingSetBase::Node FoldingSetNode
Definition FoldingSet.h:409
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
ArrayRef(const T &OneElt) -> ArrayRef< T >
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
ContextualFoldingSetTrait - Like FoldingSetTrait, but for ContextualFoldingSets.
Definition FoldingSet.h:165
DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but for ContextualFoldingSets.
Definition FoldingSet.h:151
static bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID, Ctx Context)
Definition FoldingSet.h:431
static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context)
Definition FoldingSet.h:152
static unsigned ComputeHash(T &X, FoldingSetNodeID &TempID, Ctx Context)
Definition FoldingSet.h:441
DefaultFoldingSetTrait - This class provides default implementations for FoldingSetTrait implementati...
Definition FoldingSet.h:116
static void Profile(const T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:117
static unsigned ComputeHash(T &X, FoldingSetNodeID &TempID)
Definition FoldingSet.h:425
static bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
Definition FoldingSet.h:417
static void Profile(T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:120
Functions provided by the derived class to compute folding properties.
Definition FoldingSet.h:349
unsigned(* ComputeNodeHash)(const FoldingSetBase *Self, Node *N, FoldingSetNodeID &TempID)
ComputeNodeHash - Instantiations of the FoldingSet template implement this function to compute a hash...
Definition FoldingSet.h:363
bool(* NodeEquals)(const FoldingSetBase *Self, Node *N, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
NodeEquals - Instantiations of the FoldingSet template implement this function to compare the given n...
Definition FoldingSet.h:357
void(* GetNodeProfile)(const FoldingSetBase *Self, Node *N, FoldingSetNodeID &ID)
GetNodeProfile - Instantiations of the FoldingSet template implement this function to gather data bit...
Definition FoldingSet.h:352
static void Profile(T *X, FoldingSetNodeID &ID)
Definition FoldingSet.h:835
static void Profile(const std::pair< T1, T2 > &P, FoldingSetNodeID &ID)
Definition FoldingSet.h:841
FoldingSetTrait - This trait class is used to define behavior of how to "profile" (in the FoldingSet ...
Definition FoldingSet.h:146
An iterator type that allows iterating over the pointees via some other iterator.
Definition iterator.h:329