LLVM 24.0.0git
StringTableBuilder.cpp
Go to the documentation of this file.
1//===- StringTableBuilder.cpp - String table building utility -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/Endian.h"
18#include <cassert>
19#include <cstddef>
20#include <cstdint>
21#include <cstring>
22#include <utility>
23#include <vector>
24
25using namespace llvm;
26
28
29void StringTableBuilder::initSize() {
30 // Account for leading bytes in table so that offsets returned from add are
31 // correct.
32 switch (K) {
33 case RAW:
34 case DWARF:
35 Size = 0;
36 break;
37 case MachOLinked:
38 case MachO64Linked:
39 Size = 2;
40 break;
41 case MachO:
42 case MachO64:
43 case ELF:
44 case DXContainer:
45 // Start the table with a NUL byte.
46 Size = 1;
47 break;
48 case XCOFF:
49 case WinCOFF:
50 // Make room to write the table size later.
51 Size = 4;
52 break;
53 }
54}
55
57 : K(K), Alignment(Alignment) {
58 initSize();
59}
60
64 Data.resize(getSize());
65 write((uint8_t *)Data.data());
66 OS << Data;
67}
68
70
73 for (const StringPair &P : StringIndexMap) {
74 StringRef Data = P.first.val();
75 if (!Data.empty())
76 memcpy(Buf + P.second, Data.data(), Data.size());
77 }
78 // The COFF formats store the size of the string table in the first 4 bytes.
79 // For Windows, the format is little-endian; for AIX, it is big-endian.
80 if (K == WinCOFF)
82 else if (K == XCOFF)
84}
85
86namespace {
87// A string being sorted. Key caches tailKey at the current sort depth.
88struct TailEntry {
89 uint64_t Key;
90 const char *Data;
91 uint32_t Len;
92 uint32_t Idx;
93};
94} // namespace
95
96// Return the 8 characters ending Pos characters from the end of a string as a
97// little-endian integer, so comparing keys compares the reversed strings.
98// Missing characters are 0.
99static uint64_t tailKey(const char *Data, size_t Len, size_t Pos) {
100 if (Pos >= Len)
101 return 0;
102 size_t R = Len - Pos;
103 if (R >= 8)
104 return support::endian::read64le(Data + R - 8);
105 uint64_t Key = 0;
106 for (size_t I = 0; I != R; ++I)
107 Key |= uint64_t((unsigned char)Data[I]) << (8 * (8 - R + I));
108 return Key;
109}
110
111// Return true if A reversed is greater than B reversed, given that their last
112// Pos characters are equal.
113static bool tailGreater(const TailEntry &A, const TailEntry &B, size_t Pos) {
114 const char *EA = A.Data + A.Len, *EB = B.Data + B.Len;
115 size_t N = std::min(A.Len, B.Len), I = Pos;
116 for (; I + 8 <= N; I += 8)
117 if (memcmp(EA - I - 8, EB - I - 8, 8))
118 break;
119 for (; I < N; ++I) {
120 unsigned char CA = *(EA - I - 1), CB = *(EB - I - 1);
121 if (CA != CB)
122 return CA > CB;
123 }
124 return A.Len > B.Len;
125}
126
127// Sort strings in descending order of their reversed strings, so that a string
128// that is a suffix of others immediately follows one of them. Their last `Pos`
129// characters are equal. Sort by the keys at `Pos`, then recurse into each run
130// of equal keys at Pos + 8.
131static void multikeySort(MutableArrayRef<TailEntry> Vec, size_t Pos) {
132tailcall:
133 if (Vec.size() <= 1)
134 return;
135 for (TailEntry &E : Vec)
136 E.Key = tailKey(E.Data, E.Len, Pos);
137 if (Vec.size() > 8) {
138 llvm::sort(Vec, [](const TailEntry &A, const TailEntry &B) {
139 return A.Key > B.Key;
140 });
141 // A zero maximum key means every key is 0: the strings have run out of
142 // characters or have only NULs left, so recursing would not terminate.
143 if (Vec[0].Key) {
144 size_t I = 0;
145 for (size_t J = 1; J != Vec.size(); ++J) {
146 if (Vec[J].Key != Vec[I].Key) {
147 multikeySort(Vec.slice(I, J - I), Pos + 8);
148 I = J;
149 }
150 }
151 // multikeySort(Vec.slice(I), Pos + 8), but with tail call optimization.
152 Vec = Vec.slice(I);
153 Pos += 8;
154 goto tailcall;
155 }
156 }
157 llvm::sort(Vec, [Pos](const TailEntry &A, const TailEntry &B) {
158 if (A.Key != B.Key)
159 return A.Key > B.Key;
160 return tailGreater(A, B, Pos);
161 });
162}
163
165 assert(K != DWARF);
166 finalizeStringTable(/*Optimize=*/true);
167}
168
170 finalizeStringTable(/*Optimize=*/false);
171}
172
173void StringTableBuilder::finalizeStringTable(bool Optimize) {
174 Finalized = true;
175
176 if (Optimize && StringIndexMap.size()) {
177 std::vector<StringPair *> Strings;
178 Strings.reserve(StringIndexMap.size());
179 for (StringPair &P : StringIndexMap)
180 Strings.push_back(&P);
181
182 if (StringPriorityMap.size()) {
183 llvm::sort(Strings,
184 [&](const StringPair *LHS, const StringPair *RHS) -> bool {
185 return StringPriorityMap.lookup(LHS->first) >
186 StringPriorityMap.lookup(RHS->first);
187 });
188 }
189 std::vector<TailEntry> Entries(Strings.size());
190 for (auto [Idx, P] : enumerate(Strings)) {
191 StringRef S = P->first.val();
192 assert(S.size() <= UINT32_MAX);
193 Entries[Idx] = {0, S.data(), uint32_t(S.size()), uint32_t(Idx)};
194 }
195
196 size_t RangeBegin = 0;
197 MutableArrayRef<TailEntry> EntriesRef(Entries);
198 if (StringPriorityMap.size()) {
199 uint8_t RangePriority = StringPriorityMap.lookup(Strings[0]->first);
200 for (size_t I = 1, E = Strings.size(); I != E && RangePriority; ++I) {
201 uint8_t Priority = StringPriorityMap.lookup(Strings[I]->first);
202 if (Priority != RangePriority) {
203 multikeySort(EntriesRef.slice(RangeBegin, I - RangeBegin), 0);
204 RangePriority = Priority;
205 RangeBegin = I;
206 }
207 }
208 }
209 multikeySort(EntriesRef.slice(RangeBegin), 0);
210 initSize();
211
212 StringRef Previous;
213 for (const TailEntry &E : Entries) {
214 StringPair *P = Strings[E.Idx];
215 StringRef S = P->first.val();
216 if (Previous.ends_with(S)) {
217 size_t Pos = Size - S.size() - (K != RAW);
218 if (isAligned(Alignment, Pos)) {
219 P->second = Pos;
220 continue;
221 }
222 }
223
224 Size = alignTo(Size, Alignment);
225 P->second = Size;
226
227 Size += S.size();
228 if (K != RAW)
229 ++Size;
230 Previous = S;
231 }
232 }
233
234 if (K == MachO || K == MachOLinked || K == DXContainer)
235 Size = alignTo(Size, 4); // Pad to multiple of 4.
236 if (K == MachO64 || K == MachO64Linked)
237 Size = alignTo(Size, 8); // Pad to multiple of 8.
238
239 // According to ld64 the string table of a final linked Mach-O binary starts
240 // with " ", i.e. the first byte is ' ' and the second byte is zero. In
241 // 'initSize()' we reserved the first two bytes for holding this string.
242 if (K == MachOLinked || K == MachO64Linked)
243 StringIndexMap[CachedHashStringRef(" ")] = 0;
244
245 // The first byte in an ELF string table must be null, according to the ELF
246 // specification. In 'initSize()' we reserved the first byte to hold null for
247 // this purpose and here we actually add the string to allow 'getOffset()' to
248 // be called on an empty string.
249 if (K == ELF || K == DXContainer)
250 StringIndexMap[CachedHashStringRef("")] = 0;
251}
252
254 Finalized = false;
255 StringIndexMap.clear();
256}
257
260 auto I = StringIndexMap.find(S);
261 assert(I != StringIndexMap.end() && "String is not in table!");
262 return I->second;
263}
264
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines CachedHashString and CachedHashStringRef.
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallString class.
static bool tailGreater(const TailEntry &A, const TailEntry &B, size_t Pos)
static void multikeySort(MutableArrayRef< TailEntry > Vec, size_t Pos)
static uint64_t tailKey(const char *Data, size_t Len, size_t Pos)
DenseMap< CachedHashStringRef, size_t >::value_type StringPair
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A container which contains a StringRef plus a precomputed hash.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
MutableArrayRef< T > slice(size_t N, size_t M) const
Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:372
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
LLVM_ABI void finalizeInOrder()
Finalize the string table without reording it.
LLVM_ABI size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
LLVM_ABI ~StringTableBuilder()
LLVM_ABI void write(raw_ostream &OS) const
LLVM_ABI void finalize()
Analyze the strings and build the final table.
LLVM_ABI StringTableBuilder(Kind K, Align Alignment=Align(1))
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
uint64_t read64le(const void *P)
Definition Endian.h:415
void write32le(void *P, uint32_t V)
Definition Endian.h:455
void write32be(void *P, uint32_t V)
Definition Endian.h:464
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39