1 //===-- StringTableBuilder.cpp - String table building utility ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/StringTableBuilder.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Support/COFF.h"
13 #include "llvm/Support/Endian.h"
19 StringTableBuilder::StringTableBuilder(Kind K) : K(K) {}
21 static int compareBySuffix(std::pair<StringRef, size_t> *const *AP,
22 std::pair<StringRef, size_t> *const *BP) {
23 StringRef A = (*AP)->first;
24 StringRef B = (*BP)->first;
25 size_t SizeA = A.size();
26 size_t SizeB = B.size();
27 size_t Len = std::min(SizeA, SizeB);
28 for (size_t I = 0; I < Len; ++I) {
29 char CA = A[SizeA - I - 1];
30 char CB = B[SizeB - I - 1];
37 void StringTableBuilder::finalize() {
38 std::vector<std::pair<StringRef, size_t> *> Strings;
39 Strings.reserve(StringIndexMap.size());
40 for (std::pair<StringRef, size_t> &P : StringIndexMap)
41 Strings.push_back(&P);
43 array_pod_sort(Strings.begin(), Strings.end(), compareBySuffix);
50 // Start the table with a NUL byte.
51 StringTable += '\x00';
54 // Make room to write the table size later.
55 StringTable.append(4, '\x00');
60 for (std::pair<StringRef, size_t> *P : Strings) {
61 StringRef S = P->first;
63 assert(S.size() > COFF::NameSize && "Short string in COFF string table!");
65 if (Previous.endswith(S)) {
66 P->second = StringTable.size() - S.size() - (K != RAW);
70 P->second = StringTable.size();
73 StringTable += '\x00';
82 // Pad to multiple of 4.
83 while (StringTable.size() % 4)
84 StringTable += '\x00';
87 // Write the table size in the first word.
88 assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
89 uint32_t Size = static_cast<uint32_t>(StringTable.size());
90 support::endian::write<uint32_t, support::little, support::unaligned>(
91 StringTable.data(), Size);
95 Size = StringTable.size();
98 void StringTableBuilder::clear() {
100 StringIndexMap.clear();
103 size_t StringTableBuilder::getOffset(StringRef S) const {
104 assert(isFinalized());
105 auto I = StringIndexMap.find(S);
106 assert(I != StringIndexMap.end() && "String is not in table!");
110 size_t StringTableBuilder::add(StringRef S) {
111 assert(!isFinalized());
112 auto P = StringIndexMap.insert(std::make_pair(S, Size));
114 Size += S.size() + (K != RAW);
115 return P.first->second;