1 //===- llvm/ADT/EquivalenceClasses.h - Generic Equiv. Classes ---*- 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 // Generic implementation of equivalence classes through the use Tarjan's 10 // efficient union-find algorithm. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_ADT_EQUIVALENCECLASSES_H 15 #define LLVM_ADT_EQUIVALENCECLASSES_H 16 17 #include <cassert> 18 #include <cstddef> 19 #include <cstdint> 20 #include <iterator> 21 #include <set> 22 23 namespace llvm { 24 25 /// EquivalenceClasses - This represents a collection of equivalence classes and 26 /// supports three efficient operations: insert an element into a class of its 27 /// own, union two classes, and find the class for a given element. In 28 /// addition to these modification methods, it is possible to iterate over all 29 /// of the equivalence classes and all of the elements in a class. 30 /// 31 /// This implementation is an efficient implementation that only stores one copy 32 /// of the element being indexed per entry in the set, and allows any arbitrary 33 /// type to be indexed (as long as it can be ordered with operator< or a 34 /// comparator is provided). 35 /// 36 /// Here is a simple example using integers: 37 /// 38 /// \code 39 /// EquivalenceClasses<int> EC; 40 /// EC.unionSets(1, 2); // insert 1, 2 into the same set 41 /// EC.insert(4); EC.insert(5); // insert 4, 5 into own sets 42 /// EC.unionSets(5, 1); // merge the set for 1 with 5's set. 43 /// 44 /// for (EquivalenceClasses<int>::iterator I = EC.begin(), E = EC.end(); 45 /// I != E; ++I) { // Iterate over all of the equivalence sets. 46 /// if (!I->isLeader()) continue; // Ignore non-leader sets. 47 /// for (EquivalenceClasses<int>::member_iterator MI = EC.member_begin(I); 48 /// MI != EC.member_end(); ++MI) // Loop over members in this set. 49 /// cerr << *MI << " "; // Print member. 50 /// cerr << "\n"; // Finish set. 51 /// } 52 /// \endcode 53 /// 54 /// This example prints: 55 /// 4 56 /// 5 1 2 57 /// 58 template <class ElemTy, class Compare = std::less<ElemTy>> 59 class EquivalenceClasses { 60 /// ECValue - The EquivalenceClasses data structure is just a set of these. 61 /// Each of these represents a relation for a value. First it stores the 62 /// value itself, which provides the ordering that the set queries. Next, it 63 /// provides a "next pointer", which is used to enumerate all of the elements 64 /// in the unioned set. Finally, it defines either a "end of list pointer" or 65 /// "leader pointer" depending on whether the value itself is a leader. A 66 /// "leader pointer" points to the node that is the leader for this element, 67 /// if the node is not a leader. A "end of list pointer" points to the last 68 /// node in the list of members of this list. Whether or not a node is a 69 /// leader is determined by a bit stolen from one of the pointers. 70 class ECValue { 71 friend class EquivalenceClasses; 72 73 mutable const ECValue *Leader, *Next; 74 ElemTy Data; 75 76 // ECValue ctor - Start out with EndOfList pointing to this node, Next is 77 // Null, isLeader = true. 78 ECValue(const ElemTy &Elt) 79 : Leader(this), Next((ECValue*)(intptr_t)1), Data(Elt) {} 80 81 const ECValue *getLeader() const { 82 if (isLeader()) return this; 83 if (Leader->isLeader()) return Leader; 84 // Path compression. 85 return Leader = Leader->getLeader(); 86 } 87 88 const ECValue *getEndOfList() const { 89 assert(isLeader() && "Cannot get the end of a list for a non-leader!"); 90 return Leader; 91 } 92 93 void setNext(const ECValue *NewNext) const { 94 assert(getNext() == nullptr && "Already has a next pointer!"); 95 Next = (const ECValue*)((intptr_t)NewNext | (intptr_t)isLeader()); 96 } 97 98 public: 99 ECValue(const ECValue &RHS) : Leader(this), Next((ECValue*)(intptr_t)1), 100 Data(RHS.Data) { 101 // Only support copying of singleton nodes. 102 assert(RHS.isLeader() && RHS.getNext() == nullptr && "Not a singleton!"); 103 } 104 105 bool isLeader() const { return (intptr_t)Next & 1; } 106 const ElemTy &getData() const { return Data; } 107 108 const ECValue *getNext() const { 109 return (ECValue*)((intptr_t)Next & ~(intptr_t)1); 110 } 111 }; 112 113 /// A wrapper of the comparator, to be passed to the set. 114 struct ECValueComparator { 115 using is_transparent = void; 116 117 ECValueComparator() : compare(Compare()) {} 118 119 bool operator()(const ECValue &lhs, const ECValue &rhs) const { 120 return compare(lhs.Data, rhs.Data); 121 } 122 123 template <typename T> 124 bool operator()(const T &lhs, const ECValue &rhs) const { 125 return compare(lhs, rhs.Data); 126 } 127 128 template <typename T> 129 bool operator()(const ECValue &lhs, const T &rhs) const { 130 return compare(lhs.Data, rhs); 131 } 132 133 const Compare compare; 134 }; 135 136 /// TheMapping - This implicitly provides a mapping from ElemTy values to the 137 /// ECValues, it just keeps the key as part of the value. 138 std::set<ECValue, ECValueComparator> TheMapping; 139 140 public: 141 EquivalenceClasses() = default; 142 EquivalenceClasses(const EquivalenceClasses &RHS) { 143 operator=(RHS); 144 } 145 146 const EquivalenceClasses &operator=(const EquivalenceClasses &RHS) { 147 TheMapping.clear(); 148 for (iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) 149 if (I->isLeader()) { 150 member_iterator MI = RHS.member_begin(I); 151 member_iterator LeaderIt = member_begin(insert(*MI)); 152 for (++MI; MI != member_end(); ++MI) 153 unionSets(LeaderIt, member_begin(insert(*MI))); 154 } 155 return *this; 156 } 157 158 //===--------------------------------------------------------------------===// 159 // Inspection methods 160 // 161 162 /// iterator* - Provides a way to iterate over all values in the set. 163 using iterator = typename std::set<ECValue>::const_iterator; 164 165 iterator begin() const { return TheMapping.begin(); } 166 iterator end() const { return TheMapping.end(); } 167 168 bool empty() const { return TheMapping.empty(); } 169 170 /// member_* Iterate over the members of an equivalence class. 171 class member_iterator; 172 member_iterator member_begin(iterator I) const { 173 // Only leaders provide anything to iterate over. 174 return member_iterator(I->isLeader() ? &*I : nullptr); 175 } 176 member_iterator member_end() const { 177 return member_iterator(nullptr); 178 } 179 180 /// findValue - Return an iterator to the specified value. If it does not 181 /// exist, end() is returned. 182 iterator findValue(const ElemTy &V) const { 183 return TheMapping.find(V); 184 } 185 186 /// getLeaderValue - Return the leader for the specified value that is in the 187 /// set. It is an error to call this method for a value that is not yet in 188 /// the set. For that, call getOrInsertLeaderValue(V). 189 const ElemTy &getLeaderValue(const ElemTy &V) const { 190 member_iterator MI = findLeader(V); 191 assert(MI != member_end() && "Value is not in the set!"); 192 return *MI; 193 } 194 195 /// getOrInsertLeaderValue - Return the leader for the specified value that is 196 /// in the set. If the member is not in the set, it is inserted, then 197 /// returned. 198 const ElemTy &getOrInsertLeaderValue(const ElemTy &V) { 199 member_iterator MI = findLeader(insert(V)); 200 assert(MI != member_end() && "Value is not in the set!"); 201 return *MI; 202 } 203 204 /// getNumClasses - Return the number of equivalence classes in this set. 205 /// Note that this is a linear time operation. 206 unsigned getNumClasses() const { 207 unsigned NC = 0; 208 for (iterator I = begin(), E = end(); I != E; ++I) 209 if (I->isLeader()) ++NC; 210 return NC; 211 } 212 213 //===--------------------------------------------------------------------===// 214 // Mutation methods 215 216 /// insert - Insert a new value into the union/find set, ignoring the request 217 /// if the value already exists. 218 iterator insert(const ElemTy &Data) { 219 return TheMapping.insert(ECValue(Data)).first; 220 } 221 222 /// findLeader - Given a value in the set, return a member iterator for the 223 /// equivalence class it is in. This does the path-compression part that 224 /// makes union-find "union findy". This returns an end iterator if the value 225 /// is not in the equivalence class. 226 member_iterator findLeader(iterator I) const { 227 if (I == TheMapping.end()) return member_end(); 228 return member_iterator(I->getLeader()); 229 } 230 member_iterator findLeader(const ElemTy &V) const { 231 return findLeader(TheMapping.find(V)); 232 } 233 234 /// union - Merge the two equivalence sets for the specified values, inserting 235 /// them if they do not already exist in the equivalence set. 236 member_iterator unionSets(const ElemTy &V1, const ElemTy &V2) { 237 iterator V1I = insert(V1), V2I = insert(V2); 238 return unionSets(findLeader(V1I), findLeader(V2I)); 239 } 240 member_iterator unionSets(member_iterator L1, member_iterator L2) { 241 assert(L1 != member_end() && L2 != member_end() && "Illegal inputs!"); 242 if (L1 == L2) return L1; // Unifying the same two sets, noop. 243 244 // Otherwise, this is a real union operation. Set the end of the L1 list to 245 // point to the L2 leader node. 246 const ECValue &L1LV = *L1.Node, &L2LV = *L2.Node; 247 L1LV.getEndOfList()->setNext(&L2LV); 248 249 // Update L1LV's end of list pointer. 250 L1LV.Leader = L2LV.getEndOfList(); 251 252 // Clear L2's leader flag: 253 L2LV.Next = L2LV.getNext(); 254 255 // L2's leader is now L1. 256 L2LV.Leader = &L1LV; 257 return L1; 258 } 259 260 // isEquivalent - Return true if V1 is equivalent to V2. This can happen if 261 // V1 is equal to V2 or if they belong to one equivalence class. 262 bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const { 263 // Fast path: any element is equivalent to itself. 264 if (V1 == V2) 265 return true; 266 auto It = findLeader(V1); 267 return It != member_end() && It == findLeader(V2); 268 } 269 270 class member_iterator { 271 friend class EquivalenceClasses; 272 273 const ECValue *Node; 274 275 public: 276 using iterator_category = std::forward_iterator_tag; 277 using value_type = const ElemTy; 278 using size_type = std::size_t; 279 using difference_type = std::ptrdiff_t; 280 using pointer = value_type *; 281 using reference = value_type &; 282 283 explicit member_iterator() = default; 284 explicit member_iterator(const ECValue *N) : Node(N) {} 285 286 reference operator*() const { 287 assert(Node != nullptr && "Dereferencing end()!"); 288 return Node->getData(); 289 } 290 pointer operator->() const { return &operator*(); } 291 292 member_iterator &operator++() { 293 assert(Node != nullptr && "++'d off the end of the list!"); 294 Node = Node->getNext(); 295 return *this; 296 } 297 298 member_iterator operator++(int) { // postincrement operators. 299 member_iterator tmp = *this; 300 ++*this; 301 return tmp; 302 } 303 304 bool operator==(const member_iterator &RHS) const { 305 return Node == RHS.Node; 306 } 307 bool operator!=(const member_iterator &RHS) const { 308 return Node != RHS.Node; 309 } 310 }; 311 }; 312 313 } // end namespace llvm 314 315 #endif // LLVM_ADT_EQUIVALENCECLASSES_H 316