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