Skip to content

Commit 15b8327

Browse files
committed
Simplify multikey_qsort function.
This function implements the three-way radix quicksort algorithm. This patch simplifies the implementation by using MutableArrayRef. llvm-svn: 314858
1 parent e0c4315 commit 15b8327

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

llvm/lib/MC/StringTableBuilder.cpp

+20-24
Original file line numberDiff line numberDiff line change
@@ -82,33 +82,34 @@ static int charTailAt(StringPair *P, size_t Pos) {
8282

8383
// Three-way radix quicksort. This is much faster than std::sort with strcmp
8484
// because it does not compare characters that we already know the same.
85-
static void multikey_qsort(std::vector<StringPair *> &Vec, size_t Begin,
86-
size_t End, int Pos) {
85+
static void multikeySort(MutableArrayRef<StringPair *> Vec, int Pos) {
8786
tailcall:
88-
if (End - Begin <= 1)
87+
if (Vec.size() <= 1)
8988
return;
9089

91-
// Partition items so that items in [Begin, P) are greater than the pivot,
92-
// [P, Q) are the same as the pivot, and [Q, End) are less than the pivot.
93-
int Pivot = charTailAt(Vec[Begin], Pos);
94-
size_t P = Begin;
95-
size_t Q = End;
96-
for (size_t R = Begin + 1; R < Q;) {
97-
int C = charTailAt(Vec[R], Pos);
90+
// Partition items so that items in [0, I) are greater than the pivot,
91+
// [I, J) are the same as the pivot, and [J, Vec.size()) are less than
92+
// the pivot.
93+
int Pivot = charTailAt(Vec[0], Pos);
94+
size_t I = 0;
95+
size_t J = Vec.size();
96+
for (size_t K = 1; K < J;) {
97+
int C = charTailAt(Vec[K], Pos);
9898
if (C > Pivot)
99-
std::swap(Vec[P++], Vec[R++]);
99+
std::swap(Vec[I++], Vec[K++]);
100100
else if (C < Pivot)
101-
std::swap(Vec[--Q], Vec[R]);
101+
std::swap(Vec[--J], Vec[K]);
102102
else
103-
R++;
103+
K++;
104104
}
105105

106-
multikey_qsort(Vec, Begin, P, Pos);
107-
multikey_qsort(Vec, Q, End, Pos);
106+
multikeySort(Vec.slice(0, I), Pos);
107+
multikeySort(Vec.slice(J), Pos);
108+
109+
// multikeySort(Vec.slice(I, J - I), Pos + 1), but with
110+
// tail call optimization.
108111
if (Pivot != -1) {
109-
// qsort(P, Q, Pos + 1), but with tail call optimization.
110-
Begin = P;
111-
End = Q;
112+
Vec = Vec.slice(I, J - I);
112113
++Pos;
113114
goto tailcall;
114115
}
@@ -131,12 +132,7 @@ void StringTableBuilder::finalizeStringTable(bool Optimize) {
131132
for (StringPair &P : StringIndexMap)
132133
Strings.push_back(&P);
133134

134-
if (!Strings.empty()) {
135-
// If we're optimizing, sort by name. If not, sort by previously assigned
136-
// offset.
137-
multikey_qsort(Strings, 0, Strings.size(), 0);
138-
}
139-
135+
multikeySort(Strings, 0);
140136
initSize();
141137

142138
StringRef Previous;

0 commit comments

Comments
 (0)