blob: a14a26d442f7277353063e0212de49ab60916258 [file] [log] [blame]
Jakob Stoklund Olesen2a6899c2010-12-21 00:04:46 +00001//===-- llvm/ADT/IntEqClasses.cpp - Equivalence Classes of Integers -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Equivalence classes for small integers. This is a mapping of the integers
11// 0 .. N-1 into M equivalence classes numbered 0 .. M-1.
12//
13// Initially each integer has its own equivalence class. Classes are joined by
14// passing a representative member of each class to join().
15//
16// Once the classes are built, compress() will number them 0 .. M-1 and prevent
17// further changes.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/ADT/IntEqClasses.h"
22
23using namespace llvm;
24
25void IntEqClasses::grow(unsigned N) {
26 assert(NumClasses == 0 && "grow() called after compress().");
27 while (EC.size() < N)
28 EC.push_back(EC.size());
29}
30
31void IntEqClasses::join(unsigned a, unsigned b) {
32 assert(NumClasses == 0 && "join() called after compress().");
33 unsigned eca = EC[a];
34 unsigned ecb = EC[b];
35 // Update pointers while searching for the leaders, compressing the paths
36 // incrementally. The larger leader will eventually be updated, joining the
37 // classes.
38 while (eca != ecb)
39 if (eca < ecb)
40 EC[b] = eca, b = ecb, ecb = EC[b];
41 else
42 EC[a] = ecb, a = eca, eca = EC[a];
43}
44
45unsigned IntEqClasses::findLeader(unsigned a) const {
46 assert(NumClasses == 0 && "findLeader() called after compress().");
47 while (a != EC[a])
48 a = EC[a];
49 return a;
50}
51
52void IntEqClasses::compress() {
53 if (NumClasses)
54 return;
55 for (unsigned i = 0, e = EC.size(); i != e; ++i)
56 EC[i] = (EC[i] == i) ? NumClasses++ : EC[EC[i]];
57}
58
59void IntEqClasses::uncompress() {
60 if (!NumClasses)
61 return;
62 SmallVector<unsigned, 8> Leader;
63 for (unsigned i = 0, e = EC.size(); i != e; ++i)
64 if (EC[i] < Leader.size())
65 EC[i] = Leader[EC[i]];
66 else
67 Leader.push_back(EC[i] = i);
68 NumClasses = 0;
69}