LLVM API Documentation

EquivalenceClasses.h
Go to the documentation of this file.
00001 //===-- llvm/ADT/EquivalenceClasses.h - Generic Equiv. Classes --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Generic implementation of equivalence classes through the use Tarjan's
00011 // efficient union-find algorithm.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ADT_EQUIVALENCECLASSES_H
00016 #define LLVM_ADT_EQUIVALENCECLASSES_H
00017 
00018 #include "llvm/Support/DataTypes.h"
00019 #include <cassert>
00020 #include <set>
00021 
00022 namespace llvm {
00023 
00024 /// EquivalenceClasses - This represents a collection of equivalence classes and
00025 /// supports three efficient operations: insert an element into a class of its
00026 /// own, union two classes, and find the class for a given element.  In
00027 /// addition to these modification methods, it is possible to iterate over all
00028 /// of the equivalence classes and all of the elements in a class.
00029 ///
00030 /// This implementation is an efficient implementation that only stores one copy
00031 /// of the element being indexed per entry in the set, and allows any arbitrary
00032 /// type to be indexed (as long as it can be ordered with operator<).
00033 ///
00034 /// Here is a simple example using integers:
00035 ///
00036 /// \code
00037 ///  EquivalenceClasses<int> EC;
00038 ///  EC.unionSets(1, 2);                // insert 1, 2 into the same set
00039 ///  EC.insert(4); EC.insert(5);        // insert 4, 5 into own sets
00040 ///  EC.unionSets(5, 1);                // merge the set for 1 with 5's set.
00041 ///
00042 ///  for (EquivalenceClasses<int>::iterator I = EC.begin(), E = EC.end();
00043 ///       I != E; ++I) {           // Iterate over all of the equivalence sets.
00044 ///    if (!I->isLeader()) continue;   // Ignore non-leader sets.
00045 ///    for (EquivalenceClasses<int>::member_iterator MI = EC.member_begin(I);
00046 ///         MI != EC.member_end(); ++MI)   // Loop over members in this set.
00047 ///      cerr << *MI << " ";  // Print member.
00048 ///    cerr << "\n";   // Finish set.
00049 ///  }
00050 /// \endcode
00051 ///
00052 /// This example prints:
00053 ///   4
00054 ///   5 1 2
00055 ///
00056 template <class ElemTy>
00057 class EquivalenceClasses {
00058   /// ECValue - The EquivalenceClasses data structure is just a set of these.
00059   /// Each of these represents a relation for a value.  First it stores the
00060   /// value itself, which provides the ordering that the set queries.  Next, it
00061   /// provides a "next pointer", which is used to enumerate all of the elements
00062   /// in the unioned set.  Finally, it defines either a "end of list pointer" or
00063   /// "leader pointer" depending on whether the value itself is a leader.  A
00064   /// "leader pointer" points to the node that is the leader for this element,
00065   /// if the node is not a leader.  A "end of list pointer" points to the last
00066   /// node in the list of members of this list.  Whether or not a node is a
00067   /// leader is determined by a bit stolen from one of the pointers.
00068   class ECValue {
00069     friend class EquivalenceClasses;
00070     mutable const ECValue *Leader, *Next;
00071     ElemTy Data;
00072     // ECValue ctor - Start out with EndOfList pointing to this node, Next is
00073     // Null, isLeader = true.
00074     ECValue(const ElemTy &Elt)
00075       : Leader(this), Next((ECValue*)(intptr_t)1), Data(Elt) {}
00076 
00077     const ECValue *getLeader() const {
00078       if (isLeader()) return this;
00079       if (Leader->isLeader()) return Leader;
00080       // Path compression.
00081       return Leader = Leader->getLeader();
00082     }
00083     const ECValue *getEndOfList() const {
00084       assert(isLeader() && "Cannot get the end of a list for a non-leader!");
00085       return Leader;
00086     }
00087 
00088     void setNext(const ECValue *NewNext) const {
00089       assert(getNext() == nullptr && "Already has a next pointer!");
00090       Next = (const ECValue*)((intptr_t)NewNext | (intptr_t)isLeader());
00091     }
00092   public:
00093     ECValue(const ECValue &RHS) : Leader(this), Next((ECValue*)(intptr_t)1),
00094                                   Data(RHS.Data) {
00095       // Only support copying of singleton nodes.
00096       assert(RHS.isLeader() && RHS.getNext() == nullptr && "Not a singleton!");
00097     }
00098 
00099     bool operator<(const ECValue &UFN) const { return Data < UFN.Data; }
00100 
00101     bool isLeader() const { return (intptr_t)Next & 1; }
00102     const ElemTy &getData() const { return Data; }
00103 
00104     const ECValue *getNext() const {
00105       return (ECValue*)((intptr_t)Next & ~(intptr_t)1);
00106     }
00107 
00108     template<typename T>
00109     bool operator<(const T &Val) const { return Data < Val; }
00110   };
00111 
00112   /// TheMapping - This implicitly provides a mapping from ElemTy values to the
00113   /// ECValues, it just keeps the key as part of the value.
00114   std::set<ECValue> TheMapping;
00115 
00116 public:
00117   EquivalenceClasses() {}
00118   EquivalenceClasses(const EquivalenceClasses &RHS) {
00119     operator=(RHS);
00120   }
00121 
00122   const EquivalenceClasses &operator=(const EquivalenceClasses &RHS) {
00123     TheMapping.clear();
00124     for (iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
00125       if (I->isLeader()) {
00126         member_iterator MI = RHS.member_begin(I);
00127         member_iterator LeaderIt = member_begin(insert(*MI));
00128         for (++MI; MI != member_end(); ++MI)
00129           unionSets(LeaderIt, member_begin(insert(*MI)));
00130       }
00131     return *this;
00132   }
00133 
00134   //===--------------------------------------------------------------------===//
00135   // Inspection methods
00136   //
00137 
00138   /// iterator* - Provides a way to iterate over all values in the set.
00139   typedef typename std::set<ECValue>::const_iterator iterator;
00140   iterator begin() const { return TheMapping.begin(); }
00141   iterator end() const { return TheMapping.end(); }
00142 
00143   bool empty() const { return TheMapping.empty(); }
00144 
00145   /// member_* Iterate over the members of an equivalence class.
00146   ///
00147   class member_iterator;
00148   member_iterator member_begin(iterator I) const {
00149     // Only leaders provide anything to iterate over.
00150     return member_iterator(I->isLeader() ? &*I : nullptr);
00151   }
00152   member_iterator member_end() const {
00153     return member_iterator(nullptr);
00154   }
00155 
00156   /// findValue - Return an iterator to the specified value.  If it does not
00157   /// exist, end() is returned.
00158   iterator findValue(const ElemTy &V) const {
00159     return TheMapping.find(V);
00160   }
00161 
00162   /// getLeaderValue - Return the leader for the specified value that is in the
00163   /// set.  It is an error to call this method for a value that is not yet in
00164   /// the set.  For that, call getOrInsertLeaderValue(V).
00165   const ElemTy &getLeaderValue(const ElemTy &V) const {
00166     member_iterator MI = findLeader(V);
00167     assert(MI != member_end() && "Value is not in the set!");
00168     return *MI;
00169   }
00170 
00171   /// getOrInsertLeaderValue - Return the leader for the specified value that is
00172   /// in the set.  If the member is not in the set, it is inserted, then
00173   /// returned.
00174   const ElemTy &getOrInsertLeaderValue(const ElemTy &V) {
00175     member_iterator MI = findLeader(insert(V));
00176     assert(MI != member_end() && "Value is not in the set!");
00177     return *MI;
00178   }
00179 
00180   /// getNumClasses - Return the number of equivalence classes in this set.
00181   /// Note that this is a linear time operation.
00182   unsigned getNumClasses() const {
00183     unsigned NC = 0;
00184     for (iterator I = begin(), E = end(); I != E; ++I)
00185       if (I->isLeader()) ++NC;
00186     return NC;
00187   }
00188 
00189 
00190   //===--------------------------------------------------------------------===//
00191   // Mutation methods
00192 
00193   /// insert - Insert a new value into the union/find set, ignoring the request
00194   /// if the value already exists.
00195   iterator insert(const ElemTy &Data) {
00196     return TheMapping.insert(ECValue(Data)).first;
00197   }
00198 
00199   /// findLeader - Given a value in the set, return a member iterator for the
00200   /// equivalence class it is in.  This does the path-compression part that
00201   /// makes union-find "union findy".  This returns an end iterator if the value
00202   /// is not in the equivalence class.
00203   ///
00204   member_iterator findLeader(iterator I) const {
00205     if (I == TheMapping.end()) return member_end();
00206     return member_iterator(I->getLeader());
00207   }
00208   member_iterator findLeader(const ElemTy &V) const {
00209     return findLeader(TheMapping.find(V));
00210   }
00211 
00212 
00213   /// union - Merge the two equivalence sets for the specified values, inserting
00214   /// them if they do not already exist in the equivalence set.
00215   member_iterator unionSets(const ElemTy &V1, const ElemTy &V2) {
00216     iterator V1I = insert(V1), V2I = insert(V2);
00217     return unionSets(findLeader(V1I), findLeader(V2I));
00218   }
00219   member_iterator unionSets(member_iterator L1, member_iterator L2) {
00220     assert(L1 != member_end() && L2 != member_end() && "Illegal inputs!");
00221     if (L1 == L2) return L1;   // Unifying the same two sets, noop.
00222 
00223     // Otherwise, this is a real union operation.  Set the end of the L1 list to
00224     // point to the L2 leader node.
00225     const ECValue &L1LV = *L1.Node, &L2LV = *L2.Node;
00226     L1LV.getEndOfList()->setNext(&L2LV);
00227 
00228     // Update L1LV's end of list pointer.
00229     L1LV.Leader = L2LV.getEndOfList();
00230 
00231     // Clear L2's leader flag:
00232     L2LV.Next = L2LV.getNext();
00233 
00234     // L2's leader is now L1.
00235     L2LV.Leader = &L1LV;
00236     return L1;
00237   }
00238 
00239   class member_iterator : public std::iterator<std::forward_iterator_tag,
00240                                                const ElemTy, ptrdiff_t> {
00241     typedef std::iterator<std::forward_iterator_tag,
00242                           const ElemTy, ptrdiff_t> super;
00243     const ECValue *Node;
00244     friend class EquivalenceClasses;
00245   public:
00246     typedef size_t size_type;
00247     typedef typename super::pointer pointer;
00248     typedef typename super::reference reference;
00249 
00250     explicit member_iterator() {}
00251     explicit member_iterator(const ECValue *N) : Node(N) {}
00252 
00253     reference operator*() const {
00254       assert(Node != nullptr && "Dereferencing end()!");
00255       return Node->getData();
00256     }
00257     reference operator->() const { return operator*(); }
00258 
00259     member_iterator &operator++() {
00260       assert(Node != nullptr && "++'d off the end of the list!");
00261       Node = Node->getNext();
00262       return *this;
00263     }
00264 
00265     member_iterator operator++(int) {    // postincrement operators.
00266       member_iterator tmp = *this;
00267       ++*this;
00268       return tmp;
00269     }
00270 
00271     bool operator==(const member_iterator &RHS) const {
00272       return Node == RHS.Node;
00273     }
00274     bool operator!=(const member_iterator &RHS) const {
00275       return Node != RHS.Node;
00276     }
00277   };
00278 };
00279 
00280 } // End llvm namespace
00281 
00282 #endif