e4c3aa22717ff5f9578da87ddb64b56d845b7bfd
[oota-llvm.git] / lib / MC / StringTableBuilder.cpp
1 //===-- StringTableBuilder.cpp - String table building utility ------------===//
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 #include "llvm/MC/StringTableBuilder.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/Support/COFF.h"
14 #include "llvm/Support/Endian.h"
15
16 using namespace llvm;
17
18 static int compareBySuffix(StringMapEntry<size_t> *const *AP,
19                            StringMapEntry<size_t> *const *BP) {
20   StringRef a = (*AP)->first();
21   StringRef b = (*BP)->first();
22   size_t sizeA = a.size();
23   size_t sizeB = b.size();
24   size_t len = std::min(sizeA, sizeB);
25   for (size_t i = 0; i < len; ++i) {
26     char ca = a[sizeA - i - 1];
27     char cb = b[sizeB - i - 1];
28     if (ca != cb)
29       return cb - ca;
30   }
31   return sizeB - sizeA;
32 }
33
34 void StringTableBuilder::finalize(Kind kind) {
35   std::vector<StringMapEntry<size_t> *> Strings;
36   Strings.reserve(StringIndexMap.size());
37   for (StringMapEntry<size_t> &P : StringIndexMap)
38     Strings.push_back(&P);
39
40   array_pod_sort(Strings.begin(), Strings.end(), compareBySuffix);
41
42   switch (kind) {
43   case ELF:
44   case MachO:
45     // Start the table with a NUL byte.
46     StringTable += '\x00';
47     break;
48   case WinCOFF:
49     // Make room to write the table size later.
50     StringTable.append(4, '\x00');
51     break;
52   }
53
54   StringRef Previous;
55   for (StringMapEntry<size_t> *P : Strings) {
56     StringRef s = P->first();
57     if (kind == WinCOFF)
58       assert(s.size() > COFF::NameSize && "Short string in COFF string table!");
59
60     if (Previous.endswith(s)) {
61       P->second = StringTable.size() - 1 - s.size();
62       continue;
63     }
64
65     P->second = StringTable.size();
66     StringTable += s;
67     StringTable += '\x00';
68     Previous = s;
69   }
70
71   switch (kind) {
72   case ELF:
73     break;
74   case MachO:
75     // Pad to multiple of 4.
76     while (StringTable.size() % 4)
77       StringTable += '\x00';
78     break;
79   case WinCOFF:
80     // Write the table size in the first word.
81     assert(StringTable.size() <= std::numeric_limits<uint32_t>::max());
82     uint32_t size = static_cast<uint32_t>(StringTable.size());
83     support::endian::write<uint32_t, support::little, support::unaligned>(
84         StringTable.data(), size);
85     break;
86   }
87 }
88
89 void StringTableBuilder::clear() {
90   StringTable.clear();
91   StringIndexMap.clear();
92 }