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/SmallVector.h"
12 #include "llvm/Support/COFF.h"
13 #include "llvm/Support/Endian.h"
17 static bool compareBySuffix(StringRef a, StringRef b) {
18 size_t sizeA = a.size();
19 size_t sizeB = b.size();
20 size_t len = std::min(sizeA, sizeB);
21 for (size_t i = 0; i < len; ++i) {
22 char ca = a[sizeA - i - 1];
23 char cb = b[sizeB - i - 1];
30 void StringTableBuilder::finalize(Kind kind) {
31 SmallVector<StringRef, 8> Strings;
32 Strings.reserve(StringIndexMap.size());
34 for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i)
35 Strings.push_back(i->getKey());
37 std::sort(Strings.begin(), Strings.end(), compareBySuffix);
42 // Start the table with a NUL byte.
43 StringTable += '\x00';
46 // Make room to write the table size later.
47 StringTable.append(4, '\x00');
52 for (StringRef s : Strings) {
54 assert(s.size() > COFF::NameSize && "Short string in COFF string table!");
56 if (Previous.endswith(s)) {
57 StringIndexMap[s] = StringTable.size() - 1 - s.size();
61 StringIndexMap[s] = StringTable.size();
63 StringTable += '\x00';
71 // Pad to multiple of 4.
72 while (StringTable.size() % 4)
73 StringTable += '\x00';
76 // Write the table size in the first word.
77 assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
78 uint32_t size = static_cast<uint32_t>(StringTable.size());
79 support::endian::write<uint32_t, support::little, support::unaligned>(
80 StringTable.data(), size);
85 void StringTableBuilder::clear() {
87 StringIndexMap.clear();