forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReorderData.cpp
539 lines (457 loc) · 17.1 KB
/
ReorderData.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//===- bolt/Passes/ReorderSection.cpp - Reordering of section data --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements ReorderData class.
//
//===----------------------------------------------------------------------===//
// TODO:
// - make sure writeable data isn't put on same cache line unless temporally
// local
// - estimate temporal locality by looking at CFG?
#include "bolt/Passes/ReorderData.h"
#include <algorithm>
#undef DEBUG_TYPE
#define DEBUG_TYPE "reorder-data"
using namespace llvm;
using namespace bolt;
namespace opts {
extern cl::OptionCategory BoltCategory;
extern cl::OptionCategory BoltOptCategory;
extern cl::opt<JumpTableSupportLevel> JumpTables;
static cl::opt<bool>
PrintReorderedData("print-reordered-data",
cl::desc("print section contents after reordering"),
cl::ZeroOrMore,
cl::Hidden,
cl::cat(BoltCategory));
cl::list<std::string>
ReorderData("reorder-data",
cl::CommaSeparated,
cl::desc("list of sections to reorder"),
cl::value_desc("section1,section2,section3,..."),
cl::cat(BoltOptCategory));
enum ReorderAlgo : char {
REORDER_COUNT = 0,
REORDER_FUNCS = 1
};
static cl::opt<ReorderAlgo>
ReorderAlgorithm("reorder-data-algo",
cl::desc("algorithm used to reorder data sections"),
cl::init(REORDER_COUNT),
cl::values(
clEnumValN(REORDER_COUNT,
"count",
"sort hot data by read counts"),
clEnumValN(REORDER_FUNCS,
"funcs",
"sort hot data by hot function usage and count")),
cl::ZeroOrMore,
cl::cat(BoltOptCategory));
static cl::opt<unsigned>
ReorderDataMaxSymbols("reorder-data-max-symbols",
cl::desc("maximum number of symbols to reorder"),
cl::ZeroOrMore,
cl::init(std::numeric_limits<unsigned>::max()),
cl::cat(BoltOptCategory));
static cl::opt<unsigned>
ReorderDataMaxBytes("reorder-data-max-bytes",
cl::desc("maximum number of bytes to reorder"),
cl::ZeroOrMore,
cl::init(std::numeric_limits<unsigned>::max()),
cl::cat(BoltOptCategory));
static cl::list<std::string>
ReorderSymbols("reorder-symbols",
cl::CommaSeparated,
cl::desc("list of symbol names that can be reordered"),
cl::value_desc("symbol1,symbol2,symbol3,..."),
cl::Hidden,
cl::cat(BoltCategory));
static cl::list<std::string>
SkipSymbols("reorder-skip-symbols",
cl::CommaSeparated,
cl::desc("list of symbol names that cannot be reordered"),
cl::value_desc("symbol1,symbol2,symbol3,..."),
cl::Hidden,
cl::cat(BoltCategory));
static cl::opt<bool>
ReorderInplace("reorder-data-inplace",
cl::desc("reorder data sections in place"),
cl::init(false),
cl::ZeroOrMore,
cl::cat(BoltOptCategory));
}
namespace llvm {
namespace bolt {
namespace {
static constexpr uint16_t MinAlignment = 16;
bool isSupported(const BinarySection &BS) { return BS.isData() && !BS.isTLS(); }
bool filterSymbol(const BinaryData *BD) {
if (!BD->isAtomic() || BD->isJumpTable() || !BD->isMoveable())
return false;
bool IsValid = true;
if (!opts::ReorderSymbols.empty()) {
IsValid = false;
for (const std::string &Name : opts::ReorderSymbols) {
if (BD->hasName(Name)) {
IsValid = true;
break;
}
}
}
if (!IsValid)
return false;
if (!opts::SkipSymbols.empty()) {
for (const std::string &Name : opts::SkipSymbols) {
if (BD->hasName(Name)) {
IsValid = false;
break;
}
}
}
return IsValid;
}
} // namespace
using DataOrder = ReorderData::DataOrder;
void ReorderData::printOrder(const BinarySection &Section,
DataOrder::const_iterator Begin,
DataOrder::const_iterator End) const {
uint64_t TotalSize = 0;
bool PrintHeader = false;
while (Begin != End) {
const BinaryData *BD = Begin->first;
if (!PrintHeader) {
outs() << "BOLT-INFO: Hot global symbols for " << Section.getName()
<< ":\n";
PrintHeader = true;
}
outs() << "BOLT-INFO: " << *BD << ", moveable=" << BD->isMoveable()
<< format(", weight=%.5f\n", double(Begin->second) / BD->getSize());
TotalSize += BD->getSize();
++Begin;
}
if (TotalSize)
outs() << "BOLT-INFO: Total hot symbol size = " << TotalSize << "\n";
}
DataOrder ReorderData::baseOrder(BinaryContext &BC,
const BinarySection &Section) const {
DataOrder Order;
for (auto &Entry : BC.getBinaryDataForSection(Section)) {
BinaryData *BD = Entry.second;
if (!BD->isAtomic()) // skip sub-symbols
continue;
auto BDCI = BinaryDataCounts.find(BD);
uint64_t BDCount = BDCI == BinaryDataCounts.end() ? 0 : BDCI->second;
Order.emplace_back(BD, BDCount);
}
return Order;
}
void ReorderData::assignMemData(BinaryContext &BC) {
// Map of sections (or heap/stack) to count/size.
StringMap<uint64_t> Counts;
StringMap<uint64_t> JumpTableCounts;
uint64_t TotalCount = 0;
for (auto &BFI : BC.getBinaryFunctions()) {
const BinaryFunction &BF = BFI.second;
if (!BF.hasMemoryProfile())
continue;
for (const BinaryBasicBlock &BB : BF) {
for (const MCInst &Inst : BB) {
auto ErrorOrMemAccesssProfile =
BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(
Inst, "MemoryAccessProfile");
if (!ErrorOrMemAccesssProfile)
continue;
const MemoryAccessProfile &MemAccessProfile =
ErrorOrMemAccesssProfile.get();
for (const AddressAccess &AccessInfo :
MemAccessProfile.AddressAccessInfo) {
if (BinaryData *BD = AccessInfo.MemoryObject) {
BinaryDataCounts[BD->getAtomicRoot()] += AccessInfo.Count;
Counts[BD->getSectionName()] += AccessInfo.Count;
if (BD->getAtomicRoot()->isJumpTable())
JumpTableCounts[BD->getSectionName()] += AccessInfo.Count;
} else {
Counts["Heap/stack"] += AccessInfo.Count;
}
TotalCount += AccessInfo.Count;
}
}
}
}
if (!Counts.empty()) {
outs() << "BOLT-INFO: Memory stats breakdown:\n";
for (StringMapEntry<uint64_t> &Entry : Counts) {
StringRef Section = Entry.first();
const uint64_t Count = Entry.second;
outs() << "BOLT-INFO: " << Section << " = " << Count
<< format(" (%.1f%%)\n", 100.0 * Count / TotalCount);
if (JumpTableCounts.count(Section) != 0) {
const uint64_t JTCount = JumpTableCounts[Section];
outs() << "BOLT-INFO: jump tables = " << JTCount
<< format(" (%.1f%%)\n", 100.0 * JTCount / Count);
}
}
outs() << "BOLT-INFO: Total memory events: " << TotalCount << "\n";
}
}
/// Only consider moving data that is used by the hottest functions with
/// valid profiles.
std::pair<DataOrder, unsigned>
ReorderData::sortedByFunc(BinaryContext &BC, const BinarySection &Section,
std::map<uint64_t, BinaryFunction> &BFs) const {
std::map<BinaryData *, std::set<BinaryFunction *>> BDtoFunc;
std::map<BinaryData *, uint64_t> BDtoFuncCount;
auto dataUses = [&BC](const BinaryFunction &BF, bool OnlyHot) {
std::set<BinaryData *> Uses;
for (const BinaryBasicBlock &BB : BF) {
if (OnlyHot && BB.isCold())
continue;
for (const MCInst &Inst : BB) {
auto ErrorOrMemAccesssProfile =
BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(
Inst, "MemoryAccessProfile");
if (!ErrorOrMemAccesssProfile)
continue;
const MemoryAccessProfile &MemAccessProfile =
ErrorOrMemAccesssProfile.get();
for (const AddressAccess &AccessInfo :
MemAccessProfile.AddressAccessInfo) {
if (AccessInfo.MemoryObject)
Uses.insert(AccessInfo.MemoryObject);
}
}
}
return Uses;
};
for (auto &Entry : BFs) {
BinaryFunction &BF = Entry.second;
if (BF.hasValidProfile()) {
for (BinaryData *BD : dataUses(BF, true)) {
if (!BC.getFunctionForSymbol(BD->getSymbol())) {
BDtoFunc[BD->getAtomicRoot()].insert(&BF);
BDtoFuncCount[BD->getAtomicRoot()] += BF.getKnownExecutionCount();
}
}
}
}
DataOrder Order = baseOrder(BC, Section);
unsigned SplitPoint = Order.size();
std::sort(
Order.begin(), Order.end(),
[&](const DataOrder::value_type &A, const DataOrder::value_type &B) {
// Total execution counts of functions referencing BD.
const uint64_t ACount = BDtoFuncCount[A.first];
const uint64_t BCount = BDtoFuncCount[B.first];
// Weight by number of loads/data size.
const double AWeight = double(A.second) / A.first->getSize();
const double BWeight = double(B.second) / B.first->getSize();
return (ACount > BCount ||
(ACount == BCount &&
(AWeight > BWeight ||
(AWeight == BWeight &&
A.first->getAddress() < B.first->getAddress()))));
});
for (unsigned Idx = 0; Idx < Order.size(); ++Idx) {
if (!BDtoFuncCount[Order[Idx].first]) {
SplitPoint = Idx;
break;
}
}
return std::make_pair(Order, SplitPoint);
}
std::pair<DataOrder, unsigned>
ReorderData::sortedByCount(BinaryContext &BC,
const BinarySection &Section) const {
DataOrder Order = baseOrder(BC, Section);
unsigned SplitPoint = Order.size();
std::sort(Order.begin(), Order.end(),
[](const DataOrder::value_type &A, const DataOrder::value_type &B) {
// Weight by number of loads/data size.
const double AWeight = double(A.second) / A.first->getSize();
const double BWeight = double(B.second) / B.first->getSize();
return (AWeight > BWeight ||
(AWeight == BWeight &&
(A.first->getSize() < B.first->getSize() ||
(A.first->getSize() == B.first->getSize() &&
A.first->getAddress() < B.first->getAddress()))));
});
for (unsigned Idx = 0; Idx < Order.size(); ++Idx) {
if (!Order[Idx].second) {
SplitPoint = Idx;
break;
}
}
return std::make_pair(Order, SplitPoint);
}
// TODO
// add option for cache-line alignment (or just use cache-line when section
// is writeable)?
void ReorderData::setSectionOrder(BinaryContext &BC,
BinarySection &OutputSection,
DataOrder::iterator Begin,
DataOrder::iterator End) {
std::vector<BinaryData *> NewOrder;
unsigned NumReordered = 0;
uint64_t Offset = 0;
uint64_t Count = 0;
// Get the total count just for stats
uint64_t TotalCount = 0;
for (auto Itr = Begin; Itr != End; ++Itr)
TotalCount += Itr->second;
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: setSectionOrder for "
<< OutputSection.getName() << "\n");
for (; Begin != End; ++Begin) {
BinaryData *BD = Begin->first;
// We can't move certain symbols.
if (!filterSymbol(BD))
continue;
++NumReordered;
if (NumReordered > opts::ReorderDataMaxSymbols) {
if (!NewOrder.empty())
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: processing ending on symbol "
<< *NewOrder.back() << "\n");
break;
}
uint16_t Alignment = std::max(BD->getAlignment(), MinAlignment);
Offset = alignTo(Offset, Alignment);
if ((Offset + BD->getSize()) > opts::ReorderDataMaxBytes) {
if (!NewOrder.empty())
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: processing ending on symbol "
<< *NewOrder.back() << "\n");
break;
}
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: " << BD->getName() << " @ 0x"
<< Twine::utohexstr(Offset) << "\n");
BD->setOutputLocation(OutputSection, Offset);
// reorder sub-symbols
for (std::pair<const uint64_t, BinaryData *> &SubBD :
BC.getSubBinaryData(BD)) {
if (!SubBD.second->isJumpTable()) {
uint64_t SubOffset =
Offset + SubBD.second->getAddress() - BD->getAddress();
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: SubBD " << SubBD.second->getName()
<< " @ " << SubOffset << "\n");
SubBD.second->setOutputLocation(OutputSection, SubOffset);
}
}
Offset += BD->getSize();
Count += Begin->second;
NewOrder.push_back(BD);
}
OutputSection.reorderContents(NewOrder, opts::ReorderInplace);
outs() << "BOLT-INFO: reorder-data: " << Count << "/" << TotalCount
<< format(" (%.1f%%)", 100.0 * Count / TotalCount) << " events, "
<< Offset << " hot bytes\n";
}
bool ReorderData::markUnmoveableSymbols(BinaryContext &BC,
BinarySection &Section) const {
// Private symbols currently can't be moved because data can "leak" across
// the boundary of one symbol to the next, e.g. a string that has a common
// suffix might start in one private symbol and end with the common
// suffix in another.
auto isPrivate = [&](const BinaryData *BD) {
auto Prefix = std::string("PG") + BC.AsmInfo->getPrivateGlobalPrefix();
return BD->getName().startswith(Prefix.str());
};
auto Range = BC.getBinaryDataForSection(Section);
bool FoundUnmoveable = false;
for (auto Itr = Range.begin(); Itr != Range.end(); ++Itr) {
if (Itr->second->getName().startswith("PG.")) {
BinaryData *Prev =
Itr != Range.begin() ? std::prev(Itr)->second : nullptr;
BinaryData *Next = Itr != Range.end() ? std::next(Itr)->second : nullptr;
bool PrevIsPrivate = Prev && isPrivate(Prev);
bool NextIsPrivate = Next && isPrivate(Next);
if (isPrivate(Itr->second) && (PrevIsPrivate || NextIsPrivate))
Itr->second->setIsMoveable(false);
} else {
// check for overlapping symbols.
BinaryData *Next = Itr != Range.end() ? std::next(Itr)->second : nullptr;
if (Next && Itr->second->getEndAddress() != Next->getAddress() &&
Next->containsAddress(Itr->second->getEndAddress())) {
Itr->second->setIsMoveable(false);
Next->setIsMoveable(false);
}
}
FoundUnmoveable |= !Itr->second->isMoveable();
}
return FoundUnmoveable;
}
void ReorderData::runOnFunctions(BinaryContext &BC) {
static const char *DefaultSections[] = {".rodata", ".data", ".bss", nullptr};
if (!BC.HasRelocations || opts::ReorderData.empty())
return;
// For now
if (opts::JumpTables > JTS_BASIC) {
outs() << "BOLT-WARNING: jump table support must be basic for "
<< "data reordering to work.\n";
return;
}
assignMemData(BC);
std::vector<BinarySection *> Sections;
for (const std::string &SectionName : opts::ReorderData) {
if (SectionName == "default") {
for (unsigned I = 0; DefaultSections[I]; ++I)
if (ErrorOr<BinarySection &> Section =
BC.getUniqueSectionByName(DefaultSections[I]))
Sections.push_back(&*Section);
continue;
}
ErrorOr<BinarySection &> Section = BC.getUniqueSectionByName(SectionName);
if (!Section) {
outs() << "BOLT-WARNING: Section " << SectionName
<< " not found, skipping.\n";
continue;
}
if (!isSupported(*Section)) {
outs() << "BOLT-ERROR: Section " << SectionName << " not supported.\n";
exit(1);
}
Sections.push_back(&*Section);
}
for (BinarySection *Section : Sections) {
const bool FoundUnmoveable = markUnmoveableSymbols(BC, *Section);
DataOrder Order;
unsigned SplitPointIdx;
if (opts::ReorderAlgorithm == opts::ReorderAlgo::REORDER_COUNT) {
outs() << "BOLT-INFO: reorder-sections: ordering data by count\n";
std::tie(Order, SplitPointIdx) = sortedByCount(BC, *Section);
} else {
outs() << "BOLT-INFO: reorder-sections: ordering data by funcs\n";
std::tie(Order, SplitPointIdx) =
sortedByFunc(BC, *Section, BC.getBinaryFunctions());
}
auto SplitPoint = Order.begin() + SplitPointIdx;
if (opts::PrintReorderedData)
printOrder(*Section, Order.begin(), SplitPoint);
if (!opts::ReorderInplace || FoundUnmoveable) {
if (opts::ReorderInplace && FoundUnmoveable)
outs() << "BOLT-INFO: Found unmoveable symbols in "
<< Section->getName() << " falling back to splitting "
<< "instead of in-place reordering.\n";
// Copy original section to <section name>.cold.
BinarySection &Cold = BC.registerSection(
std::string(Section->getName()) + ".cold", *Section);
// Reorder contents of original section.
setSectionOrder(BC, *Section, Order.begin(), SplitPoint);
// This keeps the original data from thinking it has been moved.
for (std::pair<const uint64_t, BinaryData *> &Entry :
BC.getBinaryDataForSection(*Section)) {
if (!Entry.second->isMoved()) {
Entry.second->setSection(Cold);
Entry.second->setOutputSection(Cold);
}
}
} else {
outs() << "BOLT-WARNING: Inplace section reordering not supported yet.\n";
setSectionOrder(BC, *Section, Order.begin(), Order.end());
}
}
}
} // namespace bolt
} // namespace llvm