xref: /freebsd/contrib/llvm-project/llvm/include/llvm/ADT/EquivalenceClasses.h (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===- llvm/ADT/EquivalenceClasses.h - Generic Equiv. Classes ---*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
81fd87a68SDimitry Andric ///
91fd87a68SDimitry Andric /// \file
101fd87a68SDimitry Andric /// Generic implementation of equivalence classes through the use Tarjan's
111fd87a68SDimitry Andric /// efficient union-find algorithm.
121fd87a68SDimitry Andric ///
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #ifndef LLVM_ADT_EQUIVALENCECLASSES_H
160b57cec5SDimitry Andric #define LLVM_ADT_EQUIVALENCECLASSES_H
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include <cassert>
190b57cec5SDimitry Andric #include <cstddef>
200b57cec5SDimitry Andric #include <cstdint>
210b57cec5SDimitry Andric #include <iterator>
220b57cec5SDimitry Andric #include <set>
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric namespace llvm {
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric /// EquivalenceClasses - This represents a collection of equivalence classes and
270b57cec5SDimitry Andric /// supports three efficient operations: insert an element into a class of its
280b57cec5SDimitry Andric /// own, union two classes, and find the class for a given element.  In
290b57cec5SDimitry Andric /// addition to these modification methods, it is possible to iterate over all
300b57cec5SDimitry Andric /// of the equivalence classes and all of the elements in a class.
310b57cec5SDimitry Andric ///
320b57cec5SDimitry Andric /// This implementation is an efficient implementation that only stores one copy
330b57cec5SDimitry Andric /// of the element being indexed per entry in the set, and allows any arbitrary
34349cc55cSDimitry Andric /// type to be indexed (as long as it can be ordered with operator< or a
35349cc55cSDimitry Andric /// comparator is provided).
360b57cec5SDimitry Andric ///
370b57cec5SDimitry Andric /// Here is a simple example using integers:
380b57cec5SDimitry Andric ///
390b57cec5SDimitry Andric /// \code
400b57cec5SDimitry Andric ///  EquivalenceClasses<int> EC;
410b57cec5SDimitry Andric ///  EC.unionSets(1, 2);                // insert 1, 2 into the same set
420b57cec5SDimitry Andric ///  EC.insert(4); EC.insert(5);        // insert 4, 5 into own sets
430b57cec5SDimitry Andric ///  EC.unionSets(5, 1);                // merge the set for 1 with 5's set.
440b57cec5SDimitry Andric ///
450b57cec5SDimitry Andric ///  for (EquivalenceClasses<int>::iterator I = EC.begin(), E = EC.end();
460b57cec5SDimitry Andric ///       I != E; ++I) {           // Iterate over all of the equivalence sets.
470b57cec5SDimitry Andric ///    if (!I->isLeader()) continue;   // Ignore non-leader sets.
480b57cec5SDimitry Andric ///    for (EquivalenceClasses<int>::member_iterator MI = EC.member_begin(I);
490b57cec5SDimitry Andric ///         MI != EC.member_end(); ++MI)   // Loop over members in this set.
500b57cec5SDimitry Andric ///      cerr << *MI << " ";  // Print member.
510b57cec5SDimitry Andric ///    cerr << "\n";   // Finish set.
520b57cec5SDimitry Andric ///  }
530b57cec5SDimitry Andric /// \endcode
540b57cec5SDimitry Andric ///
550b57cec5SDimitry Andric /// This example prints:
560b57cec5SDimitry Andric ///   4
570b57cec5SDimitry Andric ///   5 1 2
580b57cec5SDimitry Andric ///
59349cc55cSDimitry Andric template <class ElemTy, class Compare = std::less<ElemTy>>
600b57cec5SDimitry Andric class EquivalenceClasses {
610b57cec5SDimitry Andric   /// ECValue - The EquivalenceClasses data structure is just a set of these.
620b57cec5SDimitry Andric   /// Each of these represents a relation for a value.  First it stores the
630b57cec5SDimitry Andric   /// value itself, which provides the ordering that the set queries.  Next, it
640b57cec5SDimitry Andric   /// provides a "next pointer", which is used to enumerate all of the elements
650b57cec5SDimitry Andric   /// in the unioned set.  Finally, it defines either a "end of list pointer" or
660b57cec5SDimitry Andric   /// "leader pointer" depending on whether the value itself is a leader.  A
670b57cec5SDimitry Andric   /// "leader pointer" points to the node that is the leader for this element,
680b57cec5SDimitry Andric   /// if the node is not a leader.  A "end of list pointer" points to the last
690b57cec5SDimitry Andric   /// node in the list of members of this list.  Whether or not a node is a
700b57cec5SDimitry Andric   /// leader is determined by a bit stolen from one of the pointers.
710b57cec5SDimitry Andric   class ECValue {
720b57cec5SDimitry Andric     friend class EquivalenceClasses;
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric     mutable const ECValue *Leader, *Next;
750b57cec5SDimitry Andric     ElemTy Data;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric     // ECValue ctor - Start out with EndOfList pointing to this node, Next is
780b57cec5SDimitry Andric     // Null, isLeader = true.
ECValue(const ElemTy & Elt)790b57cec5SDimitry Andric     ECValue(const ElemTy &Elt)
800b57cec5SDimitry Andric       : Leader(this), Next((ECValue*)(intptr_t)1), Data(Elt) {}
810b57cec5SDimitry Andric 
getLeader()820b57cec5SDimitry Andric     const ECValue *getLeader() const {
830b57cec5SDimitry Andric       if (isLeader()) return this;
840b57cec5SDimitry Andric       if (Leader->isLeader()) return Leader;
850b57cec5SDimitry Andric       // Path compression.
860b57cec5SDimitry Andric       return Leader = Leader->getLeader();
870b57cec5SDimitry Andric     }
880b57cec5SDimitry Andric 
getEndOfList()890b57cec5SDimitry Andric     const ECValue *getEndOfList() const {
900b57cec5SDimitry Andric       assert(isLeader() && "Cannot get the end of a list for a non-leader!");
910b57cec5SDimitry Andric       return Leader;
920b57cec5SDimitry Andric     }
930b57cec5SDimitry Andric 
setNext(const ECValue * NewNext)940b57cec5SDimitry Andric     void setNext(const ECValue *NewNext) const {
950b57cec5SDimitry Andric       assert(getNext() == nullptr && "Already has a next pointer!");
960b57cec5SDimitry Andric       Next = (const ECValue*)((intptr_t)NewNext | (intptr_t)isLeader());
970b57cec5SDimitry Andric     }
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   public:
ECValue(const ECValue & RHS)1000b57cec5SDimitry Andric     ECValue(const ECValue &RHS) : Leader(this), Next((ECValue*)(intptr_t)1),
1010b57cec5SDimitry Andric                                   Data(RHS.Data) {
1020b57cec5SDimitry Andric       // Only support copying of singleton nodes.
1030b57cec5SDimitry Andric       assert(RHS.isLeader() && RHS.getNext() == nullptr && "Not a singleton!");
1040b57cec5SDimitry Andric     }
1050b57cec5SDimitry Andric 
isLeader()1060b57cec5SDimitry Andric     bool isLeader() const { return (intptr_t)Next & 1; }
getData()1070b57cec5SDimitry Andric     const ElemTy &getData() const { return Data; }
1080b57cec5SDimitry Andric 
getNext()1090b57cec5SDimitry Andric     const ECValue *getNext() const {
1100b57cec5SDimitry Andric       return (ECValue*)((intptr_t)Next & ~(intptr_t)1);
1110b57cec5SDimitry Andric     }
112349cc55cSDimitry Andric   };
113349cc55cSDimitry Andric 
114349cc55cSDimitry Andric   /// A wrapper of the comparator, to be passed to the set.
115349cc55cSDimitry Andric   struct ECValueComparator {
116349cc55cSDimitry Andric     using is_transparent = void;
117349cc55cSDimitry Andric 
ECValueComparatorECValueComparator118349cc55cSDimitry Andric     ECValueComparator() : compare(Compare()) {}
119349cc55cSDimitry Andric 
operatorECValueComparator120349cc55cSDimitry Andric     bool operator()(const ECValue &lhs, const ECValue &rhs) const {
121349cc55cSDimitry Andric       return compare(lhs.Data, rhs.Data);
122349cc55cSDimitry Andric     }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric     template <typename T>
operatorECValueComparator125349cc55cSDimitry Andric     bool operator()(const T &lhs, const ECValue &rhs) const {
126349cc55cSDimitry Andric       return compare(lhs, rhs.Data);
127349cc55cSDimitry Andric     }
128349cc55cSDimitry Andric 
129349cc55cSDimitry Andric     template <typename T>
operatorECValueComparator130349cc55cSDimitry Andric     bool operator()(const ECValue &lhs, const T &rhs) const {
131349cc55cSDimitry Andric       return compare(lhs.Data, rhs);
132349cc55cSDimitry Andric     }
133349cc55cSDimitry Andric 
134349cc55cSDimitry Andric     const Compare compare;
1350b57cec5SDimitry Andric   };
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   /// TheMapping - This implicitly provides a mapping from ElemTy values to the
1380b57cec5SDimitry Andric   /// ECValues, it just keeps the key as part of the value.
139349cc55cSDimitry Andric   std::set<ECValue, ECValueComparator> TheMapping;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric public:
1420b57cec5SDimitry Andric   EquivalenceClasses() = default;
EquivalenceClasses(const EquivalenceClasses & RHS)1430b57cec5SDimitry Andric   EquivalenceClasses(const EquivalenceClasses &RHS) {
1440b57cec5SDimitry Andric     operator=(RHS);
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   const EquivalenceClasses &operator=(const EquivalenceClasses &RHS) {
1480b57cec5SDimitry Andric     TheMapping.clear();
1490b57cec5SDimitry Andric     for (iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
1500b57cec5SDimitry Andric       if (I->isLeader()) {
1510b57cec5SDimitry Andric         member_iterator MI = RHS.member_begin(I);
1520b57cec5SDimitry Andric         member_iterator LeaderIt = member_begin(insert(*MI));
1530b57cec5SDimitry Andric         for (++MI; MI != member_end(); ++MI)
1540b57cec5SDimitry Andric           unionSets(LeaderIt, member_begin(insert(*MI)));
1550b57cec5SDimitry Andric       }
1560b57cec5SDimitry Andric     return *this;
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
1600b57cec5SDimitry Andric   // Inspection methods
1610b57cec5SDimitry Andric   //
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   /// iterator* - Provides a way to iterate over all values in the set.
164*81ad6265SDimitry Andric   using iterator =
165*81ad6265SDimitry Andric       typename std::set<ECValue, ECValueComparator>::const_iterator;
1660b57cec5SDimitry Andric 
begin()1670b57cec5SDimitry Andric   iterator begin() const { return TheMapping.begin(); }
end()1680b57cec5SDimitry Andric   iterator end() const { return TheMapping.end(); }
1690b57cec5SDimitry Andric 
empty()1700b57cec5SDimitry Andric   bool empty() const { return TheMapping.empty(); }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   /// member_* Iterate over the members of an equivalence class.
1730b57cec5SDimitry Andric   class member_iterator;
member_begin(iterator I)1740b57cec5SDimitry Andric   member_iterator member_begin(iterator I) const {
1750b57cec5SDimitry Andric     // Only leaders provide anything to iterate over.
1760b57cec5SDimitry Andric     return member_iterator(I->isLeader() ? &*I : nullptr);
1770b57cec5SDimitry Andric   }
member_end()1780b57cec5SDimitry Andric   member_iterator member_end() const {
1790b57cec5SDimitry Andric     return member_iterator(nullptr);
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   /// findValue - Return an iterator to the specified value.  If it does not
1830b57cec5SDimitry Andric   /// exist, end() is returned.
findValue(const ElemTy & V)1840b57cec5SDimitry Andric   iterator findValue(const ElemTy &V) const {
1850b57cec5SDimitry Andric     return TheMapping.find(V);
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   /// getLeaderValue - Return the leader for the specified value that is in the
1890b57cec5SDimitry Andric   /// set.  It is an error to call this method for a value that is not yet in
1900b57cec5SDimitry Andric   /// the set.  For that, call getOrInsertLeaderValue(V).
getLeaderValue(const ElemTy & V)1910b57cec5SDimitry Andric   const ElemTy &getLeaderValue(const ElemTy &V) const {
1920b57cec5SDimitry Andric     member_iterator MI = findLeader(V);
1930b57cec5SDimitry Andric     assert(MI != member_end() && "Value is not in the set!");
1940b57cec5SDimitry Andric     return *MI;
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   /// getOrInsertLeaderValue - Return the leader for the specified value that is
1980b57cec5SDimitry Andric   /// in the set.  If the member is not in the set, it is inserted, then
1990b57cec5SDimitry Andric   /// returned.
getOrInsertLeaderValue(const ElemTy & V)2000b57cec5SDimitry Andric   const ElemTy &getOrInsertLeaderValue(const ElemTy &V) {
2010b57cec5SDimitry Andric     member_iterator MI = findLeader(insert(V));
2020b57cec5SDimitry Andric     assert(MI != member_end() && "Value is not in the set!");
2030b57cec5SDimitry Andric     return *MI;
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   /// getNumClasses - Return the number of equivalence classes in this set.
2070b57cec5SDimitry Andric   /// Note that this is a linear time operation.
getNumClasses()2080b57cec5SDimitry Andric   unsigned getNumClasses() const {
2090b57cec5SDimitry Andric     unsigned NC = 0;
2100b57cec5SDimitry Andric     for (iterator I = begin(), E = end(); I != E; ++I)
2110b57cec5SDimitry Andric       if (I->isLeader()) ++NC;
2120b57cec5SDimitry Andric     return NC;
2130b57cec5SDimitry Andric   }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
2160b57cec5SDimitry Andric   // Mutation methods
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   /// insert - Insert a new value into the union/find set, ignoring the request
2190b57cec5SDimitry Andric   /// if the value already exists.
insert(const ElemTy & Data)2200b57cec5SDimitry Andric   iterator insert(const ElemTy &Data) {
2210b57cec5SDimitry Andric     return TheMapping.insert(ECValue(Data)).first;
2220b57cec5SDimitry Andric   }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   /// findLeader - Given a value in the set, return a member iterator for the
2250b57cec5SDimitry Andric   /// equivalence class it is in.  This does the path-compression part that
2260b57cec5SDimitry Andric   /// makes union-find "union findy".  This returns an end iterator if the value
2270b57cec5SDimitry Andric   /// is not in the equivalence class.
findLeader(iterator I)2280b57cec5SDimitry Andric   member_iterator findLeader(iterator I) const {
2290b57cec5SDimitry Andric     if (I == TheMapping.end()) return member_end();
2300b57cec5SDimitry Andric     return member_iterator(I->getLeader());
2310b57cec5SDimitry Andric   }
findLeader(const ElemTy & V)2320b57cec5SDimitry Andric   member_iterator findLeader(const ElemTy &V) const {
2330b57cec5SDimitry Andric     return findLeader(TheMapping.find(V));
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   /// union - Merge the two equivalence sets for the specified values, inserting
2370b57cec5SDimitry Andric   /// them if they do not already exist in the equivalence set.
unionSets(const ElemTy & V1,const ElemTy & V2)2380b57cec5SDimitry Andric   member_iterator unionSets(const ElemTy &V1, const ElemTy &V2) {
2390b57cec5SDimitry Andric     iterator V1I = insert(V1), V2I = insert(V2);
2400b57cec5SDimitry Andric     return unionSets(findLeader(V1I), findLeader(V2I));
2410b57cec5SDimitry Andric   }
unionSets(member_iterator L1,member_iterator L2)2420b57cec5SDimitry Andric   member_iterator unionSets(member_iterator L1, member_iterator L2) {
2430b57cec5SDimitry Andric     assert(L1 != member_end() && L2 != member_end() && "Illegal inputs!");
2440b57cec5SDimitry Andric     if (L1 == L2) return L1;   // Unifying the same two sets, noop.
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     // Otherwise, this is a real union operation.  Set the end of the L1 list to
2470b57cec5SDimitry Andric     // point to the L2 leader node.
2480b57cec5SDimitry Andric     const ECValue &L1LV = *L1.Node, &L2LV = *L2.Node;
2490b57cec5SDimitry Andric     L1LV.getEndOfList()->setNext(&L2LV);
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric     // Update L1LV's end of list pointer.
2520b57cec5SDimitry Andric     L1LV.Leader = L2LV.getEndOfList();
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     // Clear L2's leader flag:
2550b57cec5SDimitry Andric     L2LV.Next = L2LV.getNext();
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     // L2's leader is now L1.
2580b57cec5SDimitry Andric     L2LV.Leader = &L1LV;
2590b57cec5SDimitry Andric     return L1;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   // isEquivalent - Return true if V1 is equivalent to V2. This can happen if
2630b57cec5SDimitry Andric   // V1 is equal to V2 or if they belong to one equivalence class.
isEquivalent(const ElemTy & V1,const ElemTy & V2)2640b57cec5SDimitry Andric   bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const {
2650b57cec5SDimitry Andric     // Fast path: any element is equivalent to itself.
2660b57cec5SDimitry Andric     if (V1 == V2)
2670b57cec5SDimitry Andric       return true;
2680b57cec5SDimitry Andric     auto It = findLeader(V1);
2690b57cec5SDimitry Andric     return It != member_end() && It == findLeader(V2);
2700b57cec5SDimitry Andric   }
2710b57cec5SDimitry Andric 
272fe6060f1SDimitry Andric   class member_iterator {
2730b57cec5SDimitry Andric     friend class EquivalenceClasses;
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric     const ECValue *Node;
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   public:
278fe6060f1SDimitry Andric     using iterator_category = std::forward_iterator_tag;
279fe6060f1SDimitry Andric     using value_type = const ElemTy;
280fe6060f1SDimitry Andric     using size_type = std::size_t;
281fe6060f1SDimitry Andric     using difference_type = std::ptrdiff_t;
282fe6060f1SDimitry Andric     using pointer = value_type *;
283fe6060f1SDimitry Andric     using reference = value_type &;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric     explicit member_iterator() = default;
member_iterator(const ECValue * N)2860b57cec5SDimitry Andric     explicit member_iterator(const ECValue *N) : Node(N) {}
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     reference operator*() const {
2890b57cec5SDimitry Andric       assert(Node != nullptr && "Dereferencing end()!");
2900b57cec5SDimitry Andric       return Node->getData();
2910b57cec5SDimitry Andric     }
2920b57cec5SDimitry Andric     pointer operator->() const { return &operator*(); }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     member_iterator &operator++() {
2950b57cec5SDimitry Andric       assert(Node != nullptr && "++'d off the end of the list!");
2960b57cec5SDimitry Andric       Node = Node->getNext();
2970b57cec5SDimitry Andric       return *this;
2980b57cec5SDimitry Andric     }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric     member_iterator operator++(int) {    // postincrement operators.
3010b57cec5SDimitry Andric       member_iterator tmp = *this;
3020b57cec5SDimitry Andric       ++*this;
3030b57cec5SDimitry Andric       return tmp;
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric     bool operator==(const member_iterator &RHS) const {
3070b57cec5SDimitry Andric       return Node == RHS.Node;
3080b57cec5SDimitry Andric     }
3090b57cec5SDimitry Andric     bool operator!=(const member_iterator &RHS) const {
3100b57cec5SDimitry Andric       return Node != RHS.Node;
3110b57cec5SDimitry Andric     }
3120b57cec5SDimitry Andric   };
3130b57cec5SDimitry Andric };
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric } // end namespace llvm
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric #endif // LLVM_ADT_EQUIVALENCECLASSES_H
318