1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
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 //
9 // This file implements the BinaryFunction class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "bolt/Core/BinaryFunction.h"
14 #include "bolt/Core/BinaryBasicBlock.h"
15 #include "bolt/Core/BinaryDomTree.h"
16 #include "bolt/Core/DynoStats.h"
17 #include "bolt/Core/MCPlusBuilder.h"
18 #include "bolt/Utils/NameResolver.h"
19 #include "bolt/Utils/NameShortener.h"
20 #include "bolt/Utils/Utils.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Demangle/Demangle.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCAsmLayout.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/Object/ObjectFile.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GraphWriter.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/Regex.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <functional>
43 #include <limits>
44 #include <numeric>
45 #include <string>
46
47 #define DEBUG_TYPE "bolt"
48
49 using namespace llvm;
50 using namespace bolt;
51
52 namespace opts {
53
54 extern cl::OptionCategory BoltCategory;
55 extern cl::OptionCategory BoltOptCategory;
56 extern cl::OptionCategory BoltRelocCategory;
57
58 extern cl::opt<bool> EnableBAT;
59 extern cl::opt<bool> Instrument;
60 extern cl::opt<bool> StrictMode;
61 extern cl::opt<bool> UpdateDebugSections;
62 extern cl::opt<unsigned> Verbosity;
63
64 extern bool processAllFunctions();
65
66 cl::opt<bool> CheckEncoding(
67 "check-encoding",
68 cl::desc("perform verification of LLVM instruction encoding/decoding. "
69 "Every instruction in the input is decoded and re-encoded. "
70 "If the resulting bytes do not match the input, a warning message "
71 "is printed."),
72 cl::Hidden, cl::cat(BoltCategory));
73
74 static cl::opt<bool> DotToolTipCode(
75 "dot-tooltip-code",
76 cl::desc("add basic block instructions as tool tips on nodes"), cl::Hidden,
77 cl::cat(BoltCategory));
78
79 cl::opt<JumpTableSupportLevel>
80 JumpTables("jump-tables",
81 cl::desc("jump tables support (default=basic)"),
82 cl::init(JTS_BASIC),
83 cl::values(
84 clEnumValN(JTS_NONE, "none",
85 "do not optimize functions with jump tables"),
86 clEnumValN(JTS_BASIC, "basic",
87 "optimize functions with jump tables"),
88 clEnumValN(JTS_MOVE, "move",
89 "move jump tables to a separate section"),
90 clEnumValN(JTS_SPLIT, "split",
91 "split jump tables section into hot and cold based on "
92 "function execution frequency"),
93 clEnumValN(JTS_AGGRESSIVE, "aggressive",
94 "aggressively split jump tables section based on usage "
95 "of the tables")),
96 cl::ZeroOrMore,
97 cl::cat(BoltOptCategory));
98
99 static cl::opt<bool> NoScan(
100 "no-scan",
101 cl::desc(
102 "do not scan cold functions for external references (may result in "
103 "slower binary)"),
104 cl::Hidden, cl::cat(BoltOptCategory));
105
106 cl::opt<bool>
107 PreserveBlocksAlignment("preserve-blocks-alignment",
108 cl::desc("try to preserve basic block alignment"),
109 cl::cat(BoltOptCategory));
110
111 cl::opt<bool>
112 PrintDynoStats("dyno-stats",
113 cl::desc("print execution info based on profile"),
114 cl::cat(BoltCategory));
115
116 static cl::opt<bool>
117 PrintDynoStatsOnly("print-dyno-stats-only",
118 cl::desc("while printing functions output dyno-stats and skip instructions"),
119 cl::init(false),
120 cl::Hidden,
121 cl::cat(BoltCategory));
122
123 static cl::list<std::string>
124 PrintOnly("print-only",
125 cl::CommaSeparated,
126 cl::desc("list of functions to print"),
127 cl::value_desc("func1,func2,func3,..."),
128 cl::Hidden,
129 cl::cat(BoltCategory));
130
131 cl::opt<bool>
132 TimeBuild("time-build",
133 cl::desc("print time spent constructing binary functions"),
134 cl::Hidden, cl::cat(BoltCategory));
135
136 cl::opt<bool>
137 TrapOnAVX512("trap-avx512",
138 cl::desc("in relocation mode trap upon entry to any function that uses "
139 "AVX-512 instructions"),
140 cl::init(false),
141 cl::ZeroOrMore,
142 cl::Hidden,
143 cl::cat(BoltCategory));
144
shouldPrint(const BinaryFunction & Function)145 bool shouldPrint(const BinaryFunction &Function) {
146 if (Function.isIgnored())
147 return false;
148
149 if (PrintOnly.empty())
150 return true;
151
152 for (std::string &Name : opts::PrintOnly) {
153 if (Function.hasNameRegex(Name)) {
154 return true;
155 }
156 }
157
158 return false;
159 }
160
161 } // namespace opts
162
163 namespace llvm {
164 namespace bolt {
165
166 constexpr unsigned BinaryFunction::MinAlign;
167
168 namespace {
169
emptyRange(const R & Range)170 template <typename R> bool emptyRange(const R &Range) {
171 return Range.begin() == Range.end();
172 }
173
174 /// Gets debug line information for the instruction located at the given
175 /// address in the original binary. The SMLoc's pointer is used
176 /// to point to this information, which is represented by a
177 /// DebugLineTableRowRef. The returned pointer is null if no debug line
178 /// information for this instruction was found.
findDebugLineInformationForInstructionAt(uint64_t Address,DWARFUnit * Unit,const DWARFDebugLine::LineTable * LineTable)179 SMLoc findDebugLineInformationForInstructionAt(
180 uint64_t Address, DWARFUnit *Unit,
181 const DWARFDebugLine::LineTable *LineTable) {
182 // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef,
183 // which occupies 64 bits. Thus, we can only proceed if the struct fits into
184 // the pointer itself.
185 assert(sizeof(decltype(SMLoc().getPointer())) >=
186 sizeof(DebugLineTableRowRef) &&
187 "Cannot fit instruction debug line information into SMLoc's pointer");
188
189 SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc();
190 uint32_t RowIndex = LineTable->lookupAddress(
191 {Address, object::SectionedAddress::UndefSection});
192 if (RowIndex == LineTable->UnknownRowIndex)
193 return NullResult;
194
195 assert(RowIndex < LineTable->Rows.size() &&
196 "Line Table lookup returned invalid index.");
197
198 decltype(SMLoc().getPointer()) Ptr;
199 DebugLineTableRowRef *InstructionLocation =
200 reinterpret_cast<DebugLineTableRowRef *>(&Ptr);
201
202 InstructionLocation->DwCompileUnitIndex = Unit->getOffset();
203 InstructionLocation->RowIndex = RowIndex + 1;
204
205 return SMLoc::getFromPointer(Ptr);
206 }
207
buildSectionName(StringRef Prefix,StringRef Name,const BinaryContext & BC)208 std::string buildSectionName(StringRef Prefix, StringRef Name,
209 const BinaryContext &BC) {
210 if (BC.isELF())
211 return (Prefix + Name).str();
212 static NameShortener NS;
213 return (Prefix + Twine(NS.getID(Name))).str();
214 }
215
operator <<(raw_ostream & OS,const BinaryFunction::State State)216 raw_ostream &operator<<(raw_ostream &OS, const BinaryFunction::State State) {
217 switch (State) {
218 case BinaryFunction::State::Empty: OS << "empty"; break;
219 case BinaryFunction::State::Disassembled: OS << "disassembled"; break;
220 case BinaryFunction::State::CFG: OS << "CFG constructed"; break;
221 case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break;
222 case BinaryFunction::State::EmittedCFG: OS << "emitted with CFG"; break;
223 case BinaryFunction::State::Emitted: OS << "emitted"; break;
224 }
225
226 return OS;
227 }
228
229 } // namespace
230
buildCodeSectionName(StringRef Name,const BinaryContext & BC)231 std::string BinaryFunction::buildCodeSectionName(StringRef Name,
232 const BinaryContext &BC) {
233 return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC);
234 }
235
buildColdCodeSectionName(StringRef Name,const BinaryContext & BC)236 std::string BinaryFunction::buildColdCodeSectionName(StringRef Name,
237 const BinaryContext &BC) {
238 return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name,
239 BC);
240 }
241
242 uint64_t BinaryFunction::Count = 0;
243
hasNameRegex(const StringRef Name) const244 Optional<StringRef> BinaryFunction::hasNameRegex(const StringRef Name) const {
245 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
246 Regex MatchName(RegexName);
247 Optional<StringRef> Match = forEachName(
248 [&MatchName](StringRef Name) { return MatchName.match(Name); });
249
250 return Match;
251 }
252
253 Optional<StringRef>
hasRestoredNameRegex(const StringRef Name) const254 BinaryFunction::hasRestoredNameRegex(const StringRef Name) const {
255 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
256 Regex MatchName(RegexName);
257 Optional<StringRef> Match = forEachName([&MatchName](StringRef Name) {
258 return MatchName.match(NameResolver::restore(Name));
259 });
260
261 return Match;
262 }
263
getDemangledName() const264 std::string BinaryFunction::getDemangledName() const {
265 StringRef MangledName = NameResolver::restore(getOneName());
266 return demangle(MangledName.str());
267 }
268
269 BinaryBasicBlock *
getBasicBlockContainingOffset(uint64_t Offset)270 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) {
271 if (Offset > Size)
272 return nullptr;
273
274 if (BasicBlockOffsets.empty())
275 return nullptr;
276
277 /*
278 * This is commented out because it makes BOLT too slow.
279 * assert(std::is_sorted(BasicBlockOffsets.begin(),
280 * BasicBlockOffsets.end(),
281 * CompareBasicBlockOffsets())));
282 */
283 auto I =
284 llvm::upper_bound(BasicBlockOffsets, BasicBlockOffset(Offset, nullptr),
285 CompareBasicBlockOffsets());
286 assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0");
287 --I;
288 BinaryBasicBlock *BB = I->second;
289 return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr;
290 }
291
markUnreachableBlocks()292 void BinaryFunction::markUnreachableBlocks() {
293 std::stack<BinaryBasicBlock *> Stack;
294
295 for (BinaryBasicBlock &BB : blocks())
296 BB.markValid(false);
297
298 // Add all entries and landing pads as roots.
299 for (BinaryBasicBlock *BB : BasicBlocks) {
300 if (isEntryPoint(*BB) || BB->isLandingPad()) {
301 Stack.push(BB);
302 BB->markValid(true);
303 continue;
304 }
305 // FIXME:
306 // Also mark BBs with indirect jumps as reachable, since we do not
307 // support removing unused jump tables yet (GH-issue20).
308 for (const MCInst &Inst : *BB) {
309 if (BC.MIB->getJumpTable(Inst)) {
310 Stack.push(BB);
311 BB->markValid(true);
312 break;
313 }
314 }
315 }
316
317 // Determine reachable BBs from the entry point
318 while (!Stack.empty()) {
319 BinaryBasicBlock *BB = Stack.top();
320 Stack.pop();
321 for (BinaryBasicBlock *Succ : BB->successors()) {
322 if (Succ->isValid())
323 continue;
324 Succ->markValid(true);
325 Stack.push(Succ);
326 }
327 }
328 }
329
330 // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs
331 // will be cleaned up by fixBranches().
eraseInvalidBBs()332 std::pair<unsigned, uint64_t> BinaryFunction::eraseInvalidBBs() {
333 DenseSet<const BinaryBasicBlock *> InvalidBBs;
334 unsigned Count = 0;
335 uint64_t Bytes = 0;
336 for (BinaryBasicBlock *const BB : BasicBlocks) {
337 if (!BB->isValid()) {
338 assert(!isEntryPoint(*BB) && "all entry blocks must be valid");
339 InvalidBBs.insert(BB);
340 ++Count;
341 Bytes += BC.computeCodeSize(BB->begin(), BB->end());
342 }
343 }
344
345 Layout.eraseBasicBlocks(InvalidBBs);
346
347 BasicBlockListType NewBasicBlocks;
348 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
349 BinaryBasicBlock *BB = *I;
350 if (InvalidBBs.contains(BB)) {
351 // Make sure the block is removed from the list of predecessors.
352 BB->removeAllSuccessors();
353 DeletedBasicBlocks.push_back(BB);
354 } else {
355 NewBasicBlocks.push_back(BB);
356 }
357 }
358 BasicBlocks = std::move(NewBasicBlocks);
359
360 assert(BasicBlocks.size() == Layout.block_size());
361
362 // Update CFG state if needed
363 if (Count > 0)
364 recomputeLandingPads();
365
366 return std::make_pair(Count, Bytes);
367 }
368
isForwardCall(const MCSymbol * CalleeSymbol) const369 bool BinaryFunction::isForwardCall(const MCSymbol *CalleeSymbol) const {
370 // This function should work properly before and after function reordering.
371 // In order to accomplish this, we use the function index (if it is valid).
372 // If the function indices are not valid, we fall back to the original
373 // addresses. This should be ok because the functions without valid indices
374 // should have been ordered with a stable sort.
375 const BinaryFunction *CalleeBF = BC.getFunctionForSymbol(CalleeSymbol);
376 if (CalleeBF) {
377 if (CalleeBF->isInjected())
378 return true;
379
380 if (hasValidIndex() && CalleeBF->hasValidIndex()) {
381 return getIndex() < CalleeBF->getIndex();
382 } else if (hasValidIndex() && !CalleeBF->hasValidIndex()) {
383 return true;
384 } else if (!hasValidIndex() && CalleeBF->hasValidIndex()) {
385 return false;
386 } else {
387 return getAddress() < CalleeBF->getAddress();
388 }
389 } else {
390 // Absolute symbol.
391 ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol);
392 assert(CalleeAddressOrError && "unregistered symbol found");
393 return *CalleeAddressOrError > getAddress();
394 }
395 }
396
dump(bool PrintInstructions) const397 void BinaryFunction::dump(bool PrintInstructions) const {
398 print(dbgs(), "", PrintInstructions);
399 }
400
print(raw_ostream & OS,std::string Annotation,bool PrintInstructions) const401 void BinaryFunction::print(raw_ostream &OS, std::string Annotation,
402 bool PrintInstructions) const {
403 if (!opts::shouldPrint(*this))
404 return;
405
406 StringRef SectionName =
407 OriginSection ? OriginSection->getName() : "<no origin section>";
408 OS << "Binary Function \"" << *this << "\" " << Annotation << " {";
409 std::vector<StringRef> AllNames = getNames();
410 if (AllNames.size() > 1) {
411 OS << "\n All names : ";
412 const char *Sep = "";
413 for (const StringRef &Name : AllNames) {
414 OS << Sep << Name;
415 Sep = "\n ";
416 }
417 }
418 OS << "\n Number : " << FunctionNumber
419 << "\n State : " << CurrentState
420 << "\n Address : 0x" << Twine::utohexstr(Address)
421 << "\n Size : 0x" << Twine::utohexstr(Size)
422 << "\n MaxSize : 0x" << Twine::utohexstr(MaxSize)
423 << "\n Offset : 0x" << Twine::utohexstr(FileOffset)
424 << "\n Section : " << SectionName
425 << "\n Orc Section : " << getCodeSectionName()
426 << "\n LSDA : 0x" << Twine::utohexstr(getLSDAAddress())
427 << "\n IsSimple : " << IsSimple
428 << "\n IsMultiEntry: " << isMultiEntry()
429 << "\n IsSplit : " << isSplit()
430 << "\n BB Count : " << size();
431
432 if (HasFixedIndirectBranch)
433 OS << "\n HasFixedIndirectBranch : true";
434 if (HasUnknownControlFlow)
435 OS << "\n Unknown CF : true";
436 if (getPersonalityFunction())
437 OS << "\n Personality : " << getPersonalityFunction()->getName();
438 if (IsFragment)
439 OS << "\n IsFragment : true";
440 if (isFolded())
441 OS << "\n FoldedInto : " << *getFoldedIntoFunction();
442 for (BinaryFunction *ParentFragment : ParentFragments)
443 OS << "\n Parent : " << *ParentFragment;
444 if (!Fragments.empty()) {
445 OS << "\n Fragments : ";
446 ListSeparator LS;
447 for (BinaryFunction *Frag : Fragments)
448 OS << LS << *Frag;
449 }
450 if (hasCFG())
451 OS << "\n Hash : " << Twine::utohexstr(computeHash());
452 if (isMultiEntry()) {
453 OS << "\n Secondary Entry Points : ";
454 ListSeparator LS;
455 for (const auto &KV : SecondaryEntryPoints)
456 OS << LS << KV.second->getName();
457 }
458 if (FrameInstructions.size())
459 OS << "\n CFI Instrs : " << FrameInstructions.size();
460 if (!Layout.block_empty()) {
461 OS << "\n BB Layout : ";
462 ListSeparator LS;
463 for (const BinaryBasicBlock *BB : Layout.blocks())
464 OS << LS << BB->getName();
465 }
466 if (ImageAddress)
467 OS << "\n Image : 0x" << Twine::utohexstr(ImageAddress);
468 if (ExecutionCount != COUNT_NO_PROFILE) {
469 OS << "\n Exec Count : " << ExecutionCount;
470 OS << "\n Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f);
471 }
472
473 if (opts::PrintDynoStats && !getLayout().block_empty()) {
474 OS << '\n';
475 DynoStats dynoStats = getDynoStats(*this);
476 OS << dynoStats;
477 }
478
479 OS << "\n}\n";
480
481 if (opts::PrintDynoStatsOnly || !PrintInstructions || !BC.InstPrinter)
482 return;
483
484 // Offset of the instruction in function.
485 uint64_t Offset = 0;
486
487 if (BasicBlocks.empty() && !Instructions.empty()) {
488 // Print before CFG was built.
489 for (const std::pair<const uint32_t, MCInst> &II : Instructions) {
490 Offset = II.first;
491
492 // Print label if exists at this offset.
493 auto LI = Labels.find(Offset);
494 if (LI != Labels.end()) {
495 if (const MCSymbol *EntrySymbol =
496 getSecondaryEntryPointSymbol(LI->second))
497 OS << EntrySymbol->getName() << " (Entry Point):\n";
498 OS << LI->second->getName() << ":\n";
499 }
500
501 BC.printInstruction(OS, II.second, Offset, this);
502 }
503 }
504
505 StringRef SplitPointMsg = "";
506 for (const FunctionFragment F : Layout) {
507 OS << SplitPointMsg;
508 SplitPointMsg = "------- HOT-COLD SPLIT POINT -------\n\n";
509 for (const BinaryBasicBlock *BB : F) {
510 OS << BB->getName() << " (" << BB->size()
511 << " instructions, align : " << BB->getAlignment() << ")\n";
512
513 if (isEntryPoint(*BB)) {
514 if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB))
515 OS << " Secondary Entry Point: " << EntrySymbol->getName() << '\n';
516 else
517 OS << " Entry Point\n";
518 }
519
520 if (BB->isLandingPad())
521 OS << " Landing Pad\n";
522
523 uint64_t BBExecCount = BB->getExecutionCount();
524 if (hasValidProfile()) {
525 OS << " Exec Count : ";
526 if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE)
527 OS << BBExecCount << '\n';
528 else
529 OS << "<unknown>\n";
530 }
531 if (BB->getCFIState() >= 0)
532 OS << " CFI State : " << BB->getCFIState() << '\n';
533 if (opts::EnableBAT) {
534 OS << " Input offset: " << Twine::utohexstr(BB->getInputOffset())
535 << "\n";
536 }
537 if (!BB->pred_empty()) {
538 OS << " Predecessors: ";
539 ListSeparator LS;
540 for (BinaryBasicBlock *Pred : BB->predecessors())
541 OS << LS << Pred->getName();
542 OS << '\n';
543 }
544 if (!BB->throw_empty()) {
545 OS << " Throwers: ";
546 ListSeparator LS;
547 for (BinaryBasicBlock *Throw : BB->throwers())
548 OS << LS << Throw->getName();
549 OS << '\n';
550 }
551
552 Offset = alignTo(Offset, BB->getAlignment());
553
554 // Note: offsets are imprecise since this is happening prior to
555 // relaxation.
556 Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this);
557
558 if (!BB->succ_empty()) {
559 OS << " Successors: ";
560 // For more than 2 successors, sort them based on frequency.
561 std::vector<uint64_t> Indices(BB->succ_size());
562 std::iota(Indices.begin(), Indices.end(), 0);
563 if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) {
564 llvm::stable_sort(Indices, [&](const uint64_t A, const uint64_t B) {
565 return BB->BranchInfo[B] < BB->BranchInfo[A];
566 });
567 }
568 ListSeparator LS;
569 for (unsigned I = 0; I < Indices.size(); ++I) {
570 BinaryBasicBlock *Succ = BB->Successors[Indices[I]];
571 const BinaryBasicBlock::BinaryBranchInfo &BI =
572 BB->BranchInfo[Indices[I]];
573 OS << LS << Succ->getName();
574 if (ExecutionCount != COUNT_NO_PROFILE &&
575 BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
576 OS << " (mispreds: " << BI.MispredictedCount
577 << ", count: " << BI.Count << ")";
578 } else if (ExecutionCount != COUNT_NO_PROFILE &&
579 BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
580 OS << " (inferred count: " << BI.Count << ")";
581 }
582 }
583 OS << '\n';
584 }
585
586 if (!BB->lp_empty()) {
587 OS << " Landing Pads: ";
588 ListSeparator LS;
589 for (BinaryBasicBlock *LP : BB->landing_pads()) {
590 OS << LS << LP->getName();
591 if (ExecutionCount != COUNT_NO_PROFILE) {
592 OS << " (count: " << LP->getExecutionCount() << ")";
593 }
594 }
595 OS << '\n';
596 }
597
598 // In CFG_Finalized state we can miscalculate CFI state at exit.
599 if (CurrentState == State::CFG) {
600 const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
601 if (CFIStateAtExit >= 0)
602 OS << " CFI State: " << CFIStateAtExit << '\n';
603 }
604
605 OS << '\n';
606 }
607 }
608
609 // Dump new exception ranges for the function.
610 if (!CallSites.empty()) {
611 OS << "EH table:\n";
612 for (const CallSite &CSI : CallSites) {
613 OS << " [" << *CSI.Start << ", " << *CSI.End << ") landing pad : ";
614 if (CSI.LP)
615 OS << *CSI.LP;
616 else
617 OS << "0";
618 OS << ", action : " << CSI.Action << '\n';
619 }
620 OS << '\n';
621 }
622
623 // Print all jump tables.
624 for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables)
625 JTI.second->print(OS);
626
627 OS << "DWARF CFI Instructions:\n";
628 if (OffsetToCFI.size()) {
629 // Pre-buildCFG information
630 for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) {
631 OS << format(" %08x:\t", Elmt.first);
632 assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset");
633 BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]);
634 OS << "\n";
635 }
636 } else {
637 // Post-buildCFG information
638 for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) {
639 const MCCFIInstruction &CFI = FrameInstructions[I];
640 OS << format(" %d:\t", I);
641 BinaryContext::printCFI(OS, CFI);
642 OS << "\n";
643 }
644 }
645 if (FrameInstructions.empty())
646 OS << " <empty>\n";
647
648 OS << "End of Function \"" << *this << "\"\n\n";
649 }
650
printRelocations(raw_ostream & OS,uint64_t Offset,uint64_t Size) const651 void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset,
652 uint64_t Size) const {
653 const char *Sep = " # Relocs: ";
654
655 auto RI = Relocations.lower_bound(Offset);
656 while (RI != Relocations.end() && RI->first < Offset + Size) {
657 OS << Sep << "(R: " << RI->second << ")";
658 Sep = ", ";
659 ++RI;
660 }
661 }
662
663 namespace {
mutateDWARFExpressionTargetReg(const MCCFIInstruction & Instr,MCPhysReg NewReg)664 std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr,
665 MCPhysReg NewReg) {
666 StringRef ExprBytes = Instr.getValues();
667 assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short");
668 uint8_t Opcode = ExprBytes[0];
669 assert((Opcode == dwarf::DW_CFA_expression ||
670 Opcode == dwarf::DW_CFA_val_expression) &&
671 "invalid DWARF expression CFI");
672 (void)Opcode;
673 const uint8_t *const Start =
674 reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data());
675 const uint8_t *const End =
676 reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1);
677 unsigned Size = 0;
678 decodeULEB128(Start, &Size, End);
679 assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI");
680 SmallString<8> Tmp;
681 raw_svector_ostream OSE(Tmp);
682 encodeULEB128(NewReg, OSE);
683 return Twine(ExprBytes.slice(0, 1))
684 .concat(OSE.str())
685 .concat(ExprBytes.drop_front(1 + Size))
686 .str();
687 }
688 } // namespace
689
mutateCFIRegisterFor(const MCInst & Instr,MCPhysReg NewReg)690 void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr,
691 MCPhysReg NewReg) {
692 const MCCFIInstruction *OldCFI = getCFIFor(Instr);
693 assert(OldCFI && "invalid CFI instr");
694 switch (OldCFI->getOperation()) {
695 default:
696 llvm_unreachable("Unexpected instruction");
697 case MCCFIInstruction::OpDefCfa:
698 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg,
699 OldCFI->getOffset()));
700 break;
701 case MCCFIInstruction::OpDefCfaRegister:
702 setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg));
703 break;
704 case MCCFIInstruction::OpOffset:
705 setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg,
706 OldCFI->getOffset()));
707 break;
708 case MCCFIInstruction::OpRegister:
709 setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg,
710 OldCFI->getRegister2()));
711 break;
712 case MCCFIInstruction::OpSameValue:
713 setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg));
714 break;
715 case MCCFIInstruction::OpEscape:
716 setCFIFor(Instr,
717 MCCFIInstruction::createEscape(
718 nullptr,
719 StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg))));
720 break;
721 case MCCFIInstruction::OpRestore:
722 setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg));
723 break;
724 case MCCFIInstruction::OpUndefined:
725 setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg));
726 break;
727 }
728 }
729
mutateCFIOffsetFor(const MCInst & Instr,int64_t NewOffset)730 const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr,
731 int64_t NewOffset) {
732 const MCCFIInstruction *OldCFI = getCFIFor(Instr);
733 assert(OldCFI && "invalid CFI instr");
734 switch (OldCFI->getOperation()) {
735 default:
736 llvm_unreachable("Unexpected instruction");
737 case MCCFIInstruction::OpDefCfaOffset:
738 setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset));
739 break;
740 case MCCFIInstruction::OpAdjustCfaOffset:
741 setCFIFor(Instr,
742 MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset));
743 break;
744 case MCCFIInstruction::OpDefCfa:
745 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(),
746 NewOffset));
747 break;
748 case MCCFIInstruction::OpOffset:
749 setCFIFor(Instr, MCCFIInstruction::createOffset(
750 nullptr, OldCFI->getRegister(), NewOffset));
751 break;
752 }
753 return getCFIFor(Instr);
754 }
755
756 IndirectBranchType
processIndirectBranch(MCInst & Instruction,unsigned Size,uint64_t Offset,uint64_t & TargetAddress)757 BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size,
758 uint64_t Offset,
759 uint64_t &TargetAddress) {
760 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
761
762 // The instruction referencing memory used by the branch instruction.
763 // It could be the branch instruction itself or one of the instructions
764 // setting the value of the register used by the branch.
765 MCInst *MemLocInstr;
766
767 // Address of the table referenced by MemLocInstr. Could be either an
768 // array of function pointers, or a jump table.
769 uint64_t ArrayStart = 0;
770
771 unsigned BaseRegNum, IndexRegNum;
772 int64_t DispValue;
773 const MCExpr *DispExpr;
774
775 // In AArch, identify the instruction adding the PC-relative offset to
776 // jump table entries to correctly decode it.
777 MCInst *PCRelBaseInstr;
778 uint64_t PCRelAddr = 0;
779
780 auto Begin = Instructions.begin();
781 if (BC.isAArch64()) {
782 PreserveNops = BC.HasRelocations;
783 // Start at the last label as an approximation of the current basic block.
784 // This is a heuristic, since the full set of labels have yet to be
785 // determined
786 for (auto LI = Labels.rbegin(); LI != Labels.rend(); ++LI) {
787 auto II = Instructions.find(LI->first);
788 if (II != Instructions.end()) {
789 Begin = II;
790 break;
791 }
792 }
793 }
794
795 IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch(
796 Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum,
797 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
798
799 if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr)
800 return BranchType;
801
802 if (MemLocInstr != &Instruction)
803 IndexRegNum = BC.MIB->getNoRegister();
804
805 if (BC.isAArch64()) {
806 const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1);
807 assert(Sym && "Symbol extraction failed");
808 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym);
809 if (SymValueOrError) {
810 PCRelAddr = *SymValueOrError;
811 } else {
812 for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) {
813 if (Elmt.second == Sym) {
814 PCRelAddr = Elmt.first + getAddress();
815 break;
816 }
817 }
818 }
819 uint64_t InstrAddr = 0;
820 for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) {
821 if (&II->second == PCRelBaseInstr) {
822 InstrAddr = II->first + getAddress();
823 break;
824 }
825 }
826 assert(InstrAddr != 0 && "instruction not found");
827 // We do this to avoid spurious references to code locations outside this
828 // function (for example, if the indirect jump lives in the last basic
829 // block of the function, it will create a reference to the next function).
830 // This replaces a symbol reference with an immediate.
831 BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr,
832 MCOperand::createImm(PCRelAddr - InstrAddr));
833 // FIXME: Disable full jump table processing for AArch64 until we have a
834 // proper way of determining the jump table limits.
835 return IndirectBranchType::UNKNOWN;
836 }
837
838 // RIP-relative addressing should be converted to symbol form by now
839 // in processed instructions (but not in jump).
840 if (DispExpr) {
841 const MCSymbol *TargetSym;
842 uint64_t TargetOffset;
843 std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(DispExpr);
844 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym);
845 assert(SymValueOrError && "global symbol needs a value");
846 ArrayStart = *SymValueOrError + TargetOffset;
847 BaseRegNum = BC.MIB->getNoRegister();
848 if (BC.isAArch64()) {
849 ArrayStart &= ~0xFFFULL;
850 ArrayStart += DispValue & 0xFFFULL;
851 }
852 } else {
853 ArrayStart = static_cast<uint64_t>(DispValue);
854 }
855
856 if (BaseRegNum == BC.MRI->getProgramCounter())
857 ArrayStart += getAddress() + Offset + Size;
858
859 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x"
860 << Twine::utohexstr(ArrayStart) << '\n');
861
862 ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart);
863 if (!Section) {
864 // No section - possibly an absolute address. Since we don't allow
865 // internal function addresses to escape the function scope - we
866 // consider it a tail call.
867 if (opts::Verbosity >= 1) {
868 errs() << "BOLT-WARNING: no section for address 0x"
869 << Twine::utohexstr(ArrayStart) << " referenced from function "
870 << *this << '\n';
871 }
872 return IndirectBranchType::POSSIBLE_TAIL_CALL;
873 }
874 if (Section->isVirtual()) {
875 // The contents are filled at runtime.
876 return IndirectBranchType::POSSIBLE_TAIL_CALL;
877 }
878
879 if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) {
880 ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart);
881 if (!Value)
882 return IndirectBranchType::UNKNOWN;
883
884 if (!BC.getSectionForAddress(ArrayStart)->isReadOnly())
885 return IndirectBranchType::UNKNOWN;
886
887 outs() << "BOLT-INFO: fixed indirect branch detected in " << *this
888 << " at 0x" << Twine::utohexstr(getAddress() + Offset)
889 << " referencing data at 0x" << Twine::utohexstr(ArrayStart)
890 << " the destination value is 0x" << Twine::utohexstr(*Value)
891 << '\n';
892
893 TargetAddress = *Value;
894 return BranchType;
895 }
896
897 // Check if there's already a jump table registered at this address.
898 MemoryContentsType MemType;
899 if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) {
900 switch (JT->Type) {
901 case JumpTable::JTT_NORMAL:
902 MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE;
903 break;
904 case JumpTable::JTT_PIC:
905 MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
906 break;
907 }
908 } else {
909 MemType = BC.analyzeMemoryAt(ArrayStart, *this);
910 }
911
912 // Check that jump table type in instruction pattern matches memory contents.
913 JumpTable::JumpTableType JTType;
914 if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) {
915 if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
916 return IndirectBranchType::UNKNOWN;
917 JTType = JumpTable::JTT_PIC;
918 } else {
919 if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
920 return IndirectBranchType::UNKNOWN;
921
922 if (MemType == MemoryContentsType::UNKNOWN)
923 return IndirectBranchType::POSSIBLE_TAIL_CALL;
924
925 BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE;
926 JTType = JumpTable::JTT_NORMAL;
927 }
928
929 // Convert the instruction into jump table branch.
930 const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType);
931 BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get());
932 BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum);
933
934 JTSites.emplace_back(Offset, ArrayStart);
935
936 return BranchType;
937 }
938
getOrCreateLocalLabel(uint64_t Address,bool CreatePastEnd)939 MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address,
940 bool CreatePastEnd) {
941 const uint64_t Offset = Address - getAddress();
942
943 if ((Offset == getSize()) && CreatePastEnd)
944 return getFunctionEndLabel();
945
946 auto LI = Labels.find(Offset);
947 if (LI != Labels.end())
948 return LI->second;
949
950 // For AArch64, check if this address is part of a constant island.
951 if (BC.isAArch64()) {
952 if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address))
953 return IslandSym;
954 }
955
956 MCSymbol *Label = BC.Ctx->createNamedTempSymbol();
957 Labels[Offset] = Label;
958
959 return Label;
960 }
961
getData() const962 ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const {
963 BinarySection &Section = *getOriginSection();
964 assert(Section.containsRange(getAddress(), getMaxSize()) &&
965 "wrong section for function");
966
967 if (!Section.isText() || Section.isVirtual() || !Section.getSize())
968 return std::make_error_code(std::errc::bad_address);
969
970 StringRef SectionContents = Section.getContents();
971
972 assert(SectionContents.size() == Section.getSize() &&
973 "section size mismatch");
974
975 // Function offset from the section start.
976 uint64_t Offset = getAddress() - Section.getAddress();
977 auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data());
978 return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize());
979 }
980
getSizeOfDataInCodeAt(uint64_t Offset) const981 size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const {
982 if (!Islands)
983 return 0;
984
985 if (Islands->DataOffsets.find(Offset) == Islands->DataOffsets.end())
986 return 0;
987
988 auto Iter = Islands->CodeOffsets.upper_bound(Offset);
989 if (Iter != Islands->CodeOffsets.end())
990 return *Iter - Offset;
991 return getSize() - Offset;
992 }
993
isZeroPaddingAt(uint64_t Offset) const994 bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const {
995 ArrayRef<uint8_t> FunctionData = *getData();
996 uint64_t EndOfCode = getSize();
997 if (Islands) {
998 auto Iter = Islands->DataOffsets.upper_bound(Offset);
999 if (Iter != Islands->DataOffsets.end())
1000 EndOfCode = *Iter;
1001 }
1002 for (uint64_t I = Offset; I < EndOfCode; ++I)
1003 if (FunctionData[I] != 0)
1004 return false;
1005
1006 return true;
1007 }
1008
disassemble()1009 bool BinaryFunction::disassemble() {
1010 NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs",
1011 "Build Binary Functions", opts::TimeBuild);
1012 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1013 assert(ErrorOrFunctionData && "function data is not available");
1014 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1015 assert(FunctionData.size() == getMaxSize() &&
1016 "function size does not match raw data size");
1017
1018 auto &Ctx = BC.Ctx;
1019 auto &MIB = BC.MIB;
1020
1021 BC.SymbolicDisAsm->setSymbolizer(MIB->createTargetSymbolizer(*this));
1022
1023 // Insert a label at the beginning of the function. This will be our first
1024 // basic block.
1025 Labels[0] = Ctx->createNamedTempSymbol("BB0");
1026
1027 auto handlePCRelOperand = [&](MCInst &Instruction, uint64_t Address,
1028 uint64_t Size) {
1029 uint64_t TargetAddress = 0;
1030 if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address,
1031 Size)) {
1032 errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1033 BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, errs());
1034 errs() << '\n';
1035 Instruction.dump_pretty(errs(), BC.InstPrinter.get());
1036 errs() << '\n';
1037 errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1038 << Twine::utohexstr(Address) << ". Skipping function " << *this
1039 << ".\n";
1040 if (BC.HasRelocations)
1041 exit(1);
1042 IsSimple = false;
1043 return;
1044 }
1045 if (TargetAddress == 0 && opts::Verbosity >= 1) {
1046 outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
1047 << '\n';
1048 }
1049
1050 const MCSymbol *TargetSymbol;
1051 uint64_t TargetOffset;
1052 std::tie(TargetSymbol, TargetOffset) =
1053 BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true);
1054 const MCExpr *Expr = MCSymbolRefExpr::create(
1055 TargetSymbol, MCSymbolRefExpr::VK_None, *BC.Ctx);
1056 if (TargetOffset) {
1057 const MCConstantExpr *Offset =
1058 MCConstantExpr::create(TargetOffset, *BC.Ctx);
1059 Expr = MCBinaryExpr::createAdd(Expr, Offset, *BC.Ctx);
1060 }
1061 MIB->replaceMemOperandDisp(Instruction,
1062 MCOperand::createExpr(BC.MIB->getTargetExprFor(
1063 Instruction, Expr, *BC.Ctx, 0)));
1064 };
1065
1066 auto handleExternalReference = [&](MCInst &Instruction, uint64_t Size,
1067 uint64_t Offset, uint64_t TargetAddress,
1068 bool &IsCall) -> MCSymbol * {
1069 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1070 MCSymbol *TargetSymbol = nullptr;
1071 BC.addInterproceduralReference(this, TargetAddress);
1072 if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) {
1073 errs() << "BOLT-WARNING: relaxed tail call detected at 0x"
1074 << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this
1075 << ". Code size will be increased.\n";
1076 }
1077
1078 assert(!MIB->isTailCall(Instruction) &&
1079 "synthetic tail call instruction found");
1080
1081 // This is a call regardless of the opcode.
1082 // Assign proper opcode for tail calls, so that they could be
1083 // treated as calls.
1084 if (!IsCall) {
1085 if (!MIB->convertJmpToTailCall(Instruction)) {
1086 assert(MIB->isConditionalBranch(Instruction) &&
1087 "unknown tail call instruction");
1088 if (opts::Verbosity >= 2) {
1089 errs() << "BOLT-WARNING: conditional tail call detected in "
1090 << "function " << *this << " at 0x"
1091 << Twine::utohexstr(AbsoluteInstrAddr) << ".\n";
1092 }
1093 }
1094 IsCall = true;
1095 }
1096
1097 TargetSymbol = BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat");
1098 if (opts::Verbosity >= 2 && TargetAddress == 0) {
1099 // We actually see calls to address 0 in presence of weak
1100 // symbols originating from libraries. This code is never meant
1101 // to be executed.
1102 outs() << "BOLT-INFO: Function " << *this
1103 << " has a call to address zero.\n";
1104 }
1105
1106 return TargetSymbol;
1107 };
1108
1109 auto handleIndirectBranch = [&](MCInst &Instruction, uint64_t Size,
1110 uint64_t Offset) {
1111 uint64_t IndirectTarget = 0;
1112 IndirectBranchType Result =
1113 processIndirectBranch(Instruction, Size, Offset, IndirectTarget);
1114 switch (Result) {
1115 default:
1116 llvm_unreachable("unexpected result");
1117 case IndirectBranchType::POSSIBLE_TAIL_CALL: {
1118 bool Result = MIB->convertJmpToTailCall(Instruction);
1119 (void)Result;
1120 assert(Result);
1121 break;
1122 }
1123 case IndirectBranchType::POSSIBLE_JUMP_TABLE:
1124 case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE:
1125 if (opts::JumpTables == JTS_NONE)
1126 IsSimple = false;
1127 break;
1128 case IndirectBranchType::POSSIBLE_FIXED_BRANCH: {
1129 if (containsAddress(IndirectTarget)) {
1130 const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget);
1131 Instruction.clear();
1132 MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get());
1133 TakenBranches.emplace_back(Offset, IndirectTarget - getAddress());
1134 HasFixedIndirectBranch = true;
1135 } else {
1136 MIB->convertJmpToTailCall(Instruction);
1137 BC.addInterproceduralReference(this, IndirectTarget);
1138 }
1139 break;
1140 }
1141 case IndirectBranchType::UNKNOWN:
1142 // Keep processing. We'll do more checks and fixes in
1143 // postProcessIndirectBranches().
1144 UnknownIndirectBranchOffsets.emplace(Offset);
1145 break;
1146 }
1147 };
1148
1149 // Check for linker veneers, which lack relocations and need manual
1150 // adjustments.
1151 auto handleAArch64IndirectCall = [&](MCInst &Instruction, uint64_t Offset) {
1152 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1153 MCInst *TargetHiBits, *TargetLowBits;
1154 uint64_t TargetAddress, Count;
1155 Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1156 AbsoluteInstrAddr, Instruction, TargetHiBits,
1157 TargetLowBits, TargetAddress);
1158 if (Count) {
1159 MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1160 --Count;
1161 for (auto It = std::prev(Instructions.end()); Count != 0;
1162 It = std::prev(It), --Count) {
1163 MIB->addAnnotation(It->second, "AArch64Veneer", true);
1164 }
1165
1166 BC.addAdrpAddRelocAArch64(*this, *TargetLowBits, *TargetHiBits,
1167 TargetAddress);
1168 }
1169 };
1170
1171 uint64_t Size = 0; // instruction size
1172 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1173 MCInst Instruction;
1174 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1175
1176 // Check for data inside code and ignore it
1177 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1178 Size = DataInCodeSize;
1179 continue;
1180 }
1181
1182 if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1183 FunctionData.slice(Offset),
1184 AbsoluteInstrAddr, nulls())) {
1185 // Functions with "soft" boundaries, e.g. coming from assembly source,
1186 // can have 0-byte padding at the end.
1187 if (isZeroPaddingAt(Offset))
1188 break;
1189
1190 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1191 << Twine::utohexstr(Offset) << " (address 0x"
1192 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
1193 << '\n';
1194 // Some AVX-512 instructions could not be disassembled at all.
1195 if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) {
1196 setTrapOnEntry();
1197 BC.TrappedFunctions.push_back(this);
1198 } else {
1199 setIgnored();
1200 }
1201
1202 break;
1203 }
1204
1205 // Check integrity of LLVM assembler/disassembler.
1206 if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) &&
1207 !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) {
1208 if (!BC.validateEncoding(Instruction, FunctionData.slice(Offset, Size))) {
1209 errs() << "BOLT-WARNING: mismatching LLVM encoding detected in "
1210 << "function " << *this << " for instruction :\n";
1211 BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1212 errs() << '\n';
1213 }
1214 }
1215
1216 // Special handling for AVX-512 instructions.
1217 if (MIB->hasEVEXEncoding(Instruction)) {
1218 if (BC.HasRelocations && opts::TrapOnAVX512) {
1219 setTrapOnEntry();
1220 BC.TrappedFunctions.push_back(this);
1221 break;
1222 }
1223
1224 // Disassemble again without the symbolizer and check that the disassembly
1225 // matches the assembler output.
1226 MCInst TempInst;
1227 BC.DisAsm->getInstruction(TempInst, Size, FunctionData.slice(Offset),
1228 AbsoluteInstrAddr, nulls());
1229 if (!BC.validateEncoding(TempInst, FunctionData.slice(Offset, Size))) {
1230 if (opts::Verbosity >= 0) {
1231 errs() << "BOLT-WARNING: internal assembler/disassembler error "
1232 "detected for AVX512 instruction:\n";
1233 BC.printInstruction(errs(), TempInst, AbsoluteInstrAddr);
1234 errs() << " in function " << *this << '\n';
1235 }
1236
1237 setIgnored();
1238 break;
1239 }
1240 }
1241
1242 if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1243 uint64_t TargetAddress = 0;
1244 if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1245 TargetAddress)) {
1246 // Check if the target is within the same function. Otherwise it's
1247 // a call, possibly a tail call.
1248 //
1249 // If the target *is* the function address it could be either a branch
1250 // or a recursive call.
1251 bool IsCall = MIB->isCall(Instruction);
1252 const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1253 MCSymbol *TargetSymbol = nullptr;
1254
1255 if (BC.MIB->isUnsupportedBranch(Instruction.getOpcode())) {
1256 setIgnored();
1257 if (BinaryFunction *TargetFunc =
1258 BC.getBinaryFunctionContainingAddress(TargetAddress))
1259 TargetFunc->setIgnored();
1260 }
1261
1262 if (IsCall && containsAddress(TargetAddress)) {
1263 if (TargetAddress == getAddress()) {
1264 // Recursive call.
1265 TargetSymbol = getSymbol();
1266 } else {
1267 if (BC.isX86()) {
1268 // Dangerous old-style x86 PIC code. We may need to freeze this
1269 // function, so preserve the function as is for now.
1270 PreserveNops = true;
1271 } else {
1272 errs() << "BOLT-WARNING: internal call detected at 0x"
1273 << Twine::utohexstr(AbsoluteInstrAddr) << " in function "
1274 << *this << ". Skipping.\n";
1275 IsSimple = false;
1276 }
1277 }
1278 }
1279
1280 if (!TargetSymbol) {
1281 // Create either local label or external symbol.
1282 if (containsAddress(TargetAddress)) {
1283 TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1284 } else {
1285 if (TargetAddress == getAddress() + getSize() &&
1286 TargetAddress < getAddress() + getMaxSize() &&
1287 !(BC.isAArch64() &&
1288 BC.handleAArch64Veneer(TargetAddress, /*MatchOnly*/ true))) {
1289 // Result of __builtin_unreachable().
1290 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1291 << Twine::utohexstr(AbsoluteInstrAddr)
1292 << " in function " << *this
1293 << " : replacing with nop.\n");
1294 BC.MIB->createNoop(Instruction);
1295 if (IsCondBranch) {
1296 // Register branch offset for profile validation.
1297 IgnoredBranches.emplace_back(Offset, Offset + Size);
1298 }
1299 goto add_instruction;
1300 }
1301 // May update Instruction and IsCall
1302 TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1303 TargetAddress, IsCall);
1304 }
1305 }
1306
1307 if (!IsCall) {
1308 // Add taken branch info.
1309 TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1310 }
1311 BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1312
1313 // Mark CTC.
1314 if (IsCondBranch && IsCall)
1315 MIB->setConditionalTailCall(Instruction, TargetAddress);
1316 } else {
1317 // Could not evaluate branch. Should be an indirect call or an
1318 // indirect branch. Bail out on the latter case.
1319 if (MIB->isIndirectBranch(Instruction))
1320 handleIndirectBranch(Instruction, Size, Offset);
1321 // Indirect call. We only need to fix it if the operand is RIP-relative.
1322 if (IsSimple && MIB->hasPCRelOperand(Instruction))
1323 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1324
1325 if (BC.isAArch64())
1326 handleAArch64IndirectCall(Instruction, Offset);
1327 }
1328 } else if (BC.isAArch64()) {
1329 // Check if there's a relocation associated with this instruction.
1330 bool UsedReloc = false;
1331 for (auto Itr = Relocations.lower_bound(Offset),
1332 ItrE = Relocations.lower_bound(Offset + Size);
1333 Itr != ItrE; ++Itr) {
1334 const Relocation &Relocation = Itr->second;
1335 int64_t Value = Relocation.Value;
1336 const bool Result = BC.MIB->replaceImmWithSymbolRef(
1337 Instruction, Relocation.Symbol, Relocation.Addend, Ctx.get(), Value,
1338 Relocation.Type);
1339 (void)Result;
1340 assert(Result && "cannot replace immediate with relocation");
1341
1342 // For aarch64, if we replaced an immediate with a symbol from a
1343 // relocation, we mark it so we do not try to further process a
1344 // pc-relative operand. All we need is the symbol.
1345 UsedReloc = true;
1346 }
1347
1348 if (MIB->hasPCRelOperand(Instruction) && !UsedReloc)
1349 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1350 }
1351
1352 add_instruction:
1353 if (getDWARFLineTable()) {
1354 Instruction.setLoc(findDebugLineInformationForInstructionAt(
1355 AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1356 }
1357
1358 // Record offset of the instruction for profile matching.
1359 if (BC.keepOffsetForInstruction(Instruction))
1360 MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1361
1362 if (BC.MIB->isNoop(Instruction)) {
1363 // NOTE: disassembly loses the correct size information for noops.
1364 // E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
1365 // 5 bytes. Preserve the size info using annotations.
1366 MIB->addAnnotation(Instruction, "Size", static_cast<uint32_t>(Size));
1367 }
1368
1369 addInstruction(Offset, std::move(Instruction));
1370 }
1371
1372 // Reset symbolizer for the disassembler.
1373 BC.SymbolicDisAsm->setSymbolizer(nullptr);
1374
1375 if (uint64_t Offset = getFirstInstructionOffset())
1376 Labels[Offset] = BC.Ctx->createNamedTempSymbol();
1377
1378 clearList(Relocations);
1379
1380 if (!IsSimple) {
1381 clearList(Instructions);
1382 return false;
1383 }
1384
1385 updateState(State::Disassembled);
1386
1387 return true;
1388 }
1389
scanExternalRefs()1390 bool BinaryFunction::scanExternalRefs() {
1391 bool Success = true;
1392 bool DisassemblyFailed = false;
1393
1394 // Ignore pseudo functions.
1395 if (isPseudo())
1396 return Success;
1397
1398 if (opts::NoScan) {
1399 clearList(Relocations);
1400 clearList(ExternallyReferencedOffsets);
1401
1402 return false;
1403 }
1404
1405 // List of external references for this function.
1406 std::vector<Relocation> FunctionRelocations;
1407
1408 static BinaryContext::IndependentCodeEmitter Emitter =
1409 BC.createIndependentMCCodeEmitter();
1410
1411 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1412 assert(ErrorOrFunctionData && "function data is not available");
1413 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1414 assert(FunctionData.size() == getMaxSize() &&
1415 "function size does not match raw data size");
1416
1417 uint64_t Size = 0; // instruction size
1418 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1419 // Check for data inside code and ignore it
1420 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1421 Size = DataInCodeSize;
1422 continue;
1423 }
1424
1425 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1426 MCInst Instruction;
1427 if (!BC.DisAsm->getInstruction(Instruction, Size,
1428 FunctionData.slice(Offset),
1429 AbsoluteInstrAddr, nulls())) {
1430 if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
1431 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1432 << Twine::utohexstr(Offset) << " (address 0x"
1433 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function "
1434 << *this << '\n';
1435 }
1436 Success = false;
1437 DisassemblyFailed = true;
1438 break;
1439 }
1440
1441 // Return true if we can skip handling the Target function reference.
1442 auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1443 if (&Target == this)
1444 return true;
1445
1446 // Note that later we may decide not to emit Target function. In that
1447 // case, we conservatively create references that will be ignored or
1448 // resolved to the same function.
1449 if (!BC.shouldEmit(Target))
1450 return true;
1451
1452 return false;
1453 };
1454
1455 // Return true if we can ignore reference to the symbol.
1456 auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1457 if (!TargetSymbol)
1458 return true;
1459
1460 if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1461 return false;
1462
1463 BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1464 if (!TargetFunction)
1465 return true;
1466
1467 return ignoreFunctionRef(*TargetFunction);
1468 };
1469
1470 // Detect if the instruction references an address.
1471 // Without relocations, we can only trust PC-relative address modes.
1472 uint64_t TargetAddress = 0;
1473 bool IsPCRel = false;
1474 bool IsBranch = false;
1475 if (BC.MIB->hasPCRelOperand(Instruction)) {
1476 if (BC.MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1477 AbsoluteInstrAddr, Size)) {
1478 IsPCRel = true;
1479 }
1480 } else if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1481 if (BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1482 TargetAddress)) {
1483 IsBranch = true;
1484 }
1485 }
1486
1487 MCSymbol *TargetSymbol = nullptr;
1488
1489 // Create an entry point at reference address if needed.
1490 BinaryFunction *TargetFunction =
1491 BC.getBinaryFunctionContainingAddress(TargetAddress);
1492 if (TargetFunction && !ignoreFunctionRef(*TargetFunction)) {
1493 const uint64_t FunctionOffset =
1494 TargetAddress - TargetFunction->getAddress();
1495 TargetSymbol = FunctionOffset
1496 ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1497 : TargetFunction->getSymbol();
1498 }
1499
1500 // Can't find more references and not creating relocations.
1501 if (!BC.HasRelocations)
1502 continue;
1503
1504 // Create a relocation against the TargetSymbol as the symbol might get
1505 // moved.
1506 if (TargetSymbol) {
1507 if (IsBranch) {
1508 BC.MIB->replaceBranchTarget(Instruction, TargetSymbol,
1509 Emitter.LocalCtx.get());
1510 } else if (IsPCRel) {
1511 const MCExpr *Expr = MCSymbolRefExpr::create(
1512 TargetSymbol, MCSymbolRefExpr::VK_None, *Emitter.LocalCtx.get());
1513 BC.MIB->replaceMemOperandDisp(
1514 Instruction, MCOperand::createExpr(BC.MIB->getTargetExprFor(
1515 Instruction, Expr, *Emitter.LocalCtx.get(), 0)));
1516 }
1517 }
1518
1519 // Create more relocations based on input file relocations.
1520 bool HasRel = false;
1521 for (auto Itr = Relocations.lower_bound(Offset),
1522 ItrE = Relocations.lower_bound(Offset + Size);
1523 Itr != ItrE; ++Itr) {
1524 Relocation &Relocation = Itr->second;
1525 if (Relocation.isPCRelative() && BC.isX86())
1526 continue;
1527 if (ignoreReference(Relocation.Symbol))
1528 continue;
1529
1530 int64_t Value = Relocation.Value;
1531 const bool Result = BC.MIB->replaceImmWithSymbolRef(
1532 Instruction, Relocation.Symbol, Relocation.Addend,
1533 Emitter.LocalCtx.get(), Value, Relocation.Type);
1534 (void)Result;
1535 assert(Result && "cannot replace immediate with relocation");
1536
1537 HasRel = true;
1538 }
1539
1540 if (!TargetSymbol && !HasRel)
1541 continue;
1542
1543 // Emit the instruction using temp emitter and generate relocations.
1544 SmallString<256> Code;
1545 SmallVector<MCFixup, 4> Fixups;
1546 raw_svector_ostream VecOS(Code);
1547 Emitter.MCE->encodeInstruction(Instruction, VecOS, Fixups, *BC.STI);
1548
1549 // Create relocation for every fixup.
1550 for (const MCFixup &Fixup : Fixups) {
1551 Optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1552 if (!Rel) {
1553 Success = false;
1554 continue;
1555 }
1556
1557 if (Relocation::getSizeForType(Rel->Type) < 4) {
1558 // If the instruction uses a short form, then we might not be able
1559 // to handle the rewrite without relaxation, and hence cannot reliably
1560 // create an external reference relocation.
1561 Success = false;
1562 continue;
1563 }
1564 Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1565 FunctionRelocations.push_back(*Rel);
1566 }
1567
1568 if (!Success)
1569 break;
1570 }
1571
1572 // Add relocations unless disassembly failed for this function.
1573 if (!DisassemblyFailed)
1574 for (Relocation &Rel : FunctionRelocations)
1575 getOriginSection()->addPendingRelocation(Rel);
1576
1577 // Inform BinaryContext that this function symbols will not be defined and
1578 // relocations should not be created against them.
1579 if (BC.HasRelocations) {
1580 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1581 BC.UndefinedSymbols.insert(LI.second);
1582 if (FunctionEndLabel)
1583 BC.UndefinedSymbols.insert(FunctionEndLabel);
1584 }
1585
1586 clearList(Relocations);
1587 clearList(ExternallyReferencedOffsets);
1588
1589 if (Success && BC.HasRelocations)
1590 HasExternalRefRelocations = true;
1591
1592 if (opts::Verbosity >= 1 && !Success)
1593 outs() << "BOLT-INFO: failed to scan refs for " << *this << '\n';
1594
1595 return Success;
1596 }
1597
postProcessEntryPoints()1598 void BinaryFunction::postProcessEntryPoints() {
1599 if (!isSimple())
1600 return;
1601
1602 for (auto &KV : Labels) {
1603 MCSymbol *Label = KV.second;
1604 if (!getSecondaryEntryPointSymbol(Label))
1605 continue;
1606
1607 // In non-relocation mode there's potentially an external undetectable
1608 // reference to the entry point and hence we cannot move this entry
1609 // point. Optimizing without moving could be difficult.
1610 if (!BC.HasRelocations)
1611 setSimple(false);
1612
1613 const uint32_t Offset = KV.first;
1614
1615 // If we are at Offset 0 and there is no instruction associated with it,
1616 // this means this is an empty function. Just ignore. If we find an
1617 // instruction at this offset, this entry point is valid.
1618 if (!Offset || getInstructionAtOffset(Offset))
1619 continue;
1620
1621 // On AArch64 there are legitimate reasons to have references past the
1622 // end of the function, e.g. jump tables.
1623 if (BC.isAArch64() && Offset == getSize())
1624 continue;
1625
1626 errs() << "BOLT-WARNING: reference in the middle of instruction "
1627 "detected in function "
1628 << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
1629 if (BC.HasRelocations)
1630 setIgnored();
1631 setSimple(false);
1632 return;
1633 }
1634 }
1635
postProcessJumpTables()1636 void BinaryFunction::postProcessJumpTables() {
1637 // Create labels for all entries.
1638 for (auto &JTI : JumpTables) {
1639 JumpTable &JT = *JTI.second;
1640 if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1641 opts::JumpTables = JTS_MOVE;
1642 outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
1643 "detected in function "
1644 << *this << '\n';
1645 }
1646 if (JT.Entries.empty()) {
1647 bool HasOneParent = (JT.Parents.size() == 1);
1648 for (unsigned I = 0; I < JT.EntriesAsAddress.size(); ++I) {
1649 uint64_t EntryAddress = JT.EntriesAsAddress[I];
1650 // builtin_unreachable does not belong to any function
1651 // Need to handle separately
1652 bool IsBuiltIn = false;
1653 for (BinaryFunction *Parent : JT.Parents) {
1654 if (EntryAddress == Parent->getAddress() + Parent->getSize()) {
1655 IsBuiltIn = true;
1656 // Specify second parameter as true to accept builtin_unreachable
1657 MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true);
1658 JT.Entries.push_back(Label);
1659 break;
1660 }
1661 }
1662 if (IsBuiltIn)
1663 continue;
1664 // Create local label for targets cannot be reached by other fragments
1665 // Otherwise, secondary entry point to target function
1666 BinaryFunction *TargetBF =
1667 BC.getBinaryFunctionContainingAddress(EntryAddress);
1668 if (TargetBF->getAddress() != EntryAddress) {
1669 MCSymbol *Label =
1670 (HasOneParent && TargetBF == this)
1671 ? getOrCreateLocalLabel(JT.EntriesAsAddress[I], true)
1672 : TargetBF->addEntryPointAtOffset(EntryAddress -
1673 TargetBF->getAddress());
1674 JT.Entries.push_back(Label);
1675 }
1676 }
1677 }
1678
1679 const uint64_t BDSize =
1680 BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1681 if (!BDSize) {
1682 BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1683 } else {
1684 assert(BDSize >= JT.getSize() &&
1685 "jump table cannot be larger than the containing object");
1686 }
1687 }
1688
1689 // Add TakenBranches from JumpTables.
1690 //
1691 // We want to do it after initial processing since we don't know jump tables'
1692 // boundaries until we process them all.
1693 for (auto &JTSite : JTSites) {
1694 const uint64_t JTSiteOffset = JTSite.first;
1695 const uint64_t JTAddress = JTSite.second;
1696 const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1697 assert(JT && "cannot find jump table for address");
1698
1699 uint64_t EntryOffset = JTAddress - JT->getAddress();
1700 while (EntryOffset < JT->getSize()) {
1701 uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize];
1702 uint64_t TargetOffset = EntryAddress - getAddress();
1703 if (TargetOffset < getSize()) {
1704 TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1705
1706 if (opts::StrictMode)
1707 registerReferencedOffset(TargetOffset);
1708 }
1709
1710 EntryOffset += JT->EntrySize;
1711
1712 // A label at the next entry means the end of this jump table.
1713 if (JT->Labels.count(EntryOffset))
1714 break;
1715 }
1716 }
1717 clearList(JTSites);
1718
1719 // Conservatively populate all possible destinations for unknown indirect
1720 // branches.
1721 if (opts::StrictMode && hasInternalReference()) {
1722 for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1723 for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1724 // Ignore __builtin_unreachable().
1725 if (PossibleDestination == getSize())
1726 continue;
1727 TakenBranches.emplace_back(Offset, PossibleDestination);
1728 }
1729 }
1730 }
1731
1732 // Remove duplicates branches. We can get a bunch of them from jump tables.
1733 // Without doing jump table value profiling we don't have use for extra
1734 // (duplicate) branches.
1735 llvm::sort(TakenBranches);
1736 auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1737 TakenBranches.erase(NewEnd, TakenBranches.end());
1738 }
1739
postProcessIndirectBranches(MCPlusBuilder::AllocatorIdTy AllocId)1740 bool BinaryFunction::postProcessIndirectBranches(
1741 MCPlusBuilder::AllocatorIdTy AllocId) {
1742 auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1743 HasUnknownControlFlow = true;
1744 BB.removeAllSuccessors();
1745 for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1746 if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1747 BB.addSuccessor(SuccBB);
1748 };
1749
1750 uint64_t NumIndirectJumps = 0;
1751 MCInst *LastIndirectJump = nullptr;
1752 BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1753 uint64_t LastJT = 0;
1754 uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1755 for (BinaryBasicBlock &BB : blocks()) {
1756 for (MCInst &Instr : BB) {
1757 if (!BC.MIB->isIndirectBranch(Instr))
1758 continue;
1759
1760 // If there's an indirect branch in a single-block function -
1761 // it must be a tail call.
1762 if (BasicBlocks.size() == 1) {
1763 BC.MIB->convertJmpToTailCall(Instr);
1764 return true;
1765 }
1766
1767 ++NumIndirectJumps;
1768
1769 if (opts::StrictMode && !hasInternalReference()) {
1770 BC.MIB->convertJmpToTailCall(Instr);
1771 break;
1772 }
1773
1774 // Validate the tail call or jump table assumptions now that we know
1775 // basic block boundaries.
1776 if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1777 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1778 MCInst *MemLocInstr;
1779 unsigned BaseRegNum, IndexRegNum;
1780 int64_t DispValue;
1781 const MCExpr *DispExpr;
1782 MCInst *PCRelBaseInstr;
1783 IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1784 Instr, BB.begin(), BB.end(), PtrSize, MemLocInstr, BaseRegNum,
1785 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1786 if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1787 continue;
1788
1789 if (!opts::StrictMode)
1790 return false;
1791
1792 if (BC.MIB->isTailCall(Instr)) {
1793 BC.MIB->convertTailCallToJmp(Instr);
1794 } else {
1795 LastIndirectJump = &Instr;
1796 LastIndirectJumpBB = &BB;
1797 LastJT = BC.MIB->getJumpTable(Instr);
1798 LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1799 BC.MIB->unsetJumpTable(Instr);
1800
1801 JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1802 if (JT->Type == JumpTable::JTT_NORMAL) {
1803 // Invalidating the jump table may also invalidate other jump table
1804 // boundaries. Until we have/need a support for this, mark the
1805 // function as non-simple.
1806 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1807 << JT->getName() << " in " << *this << '\n');
1808 return false;
1809 }
1810 }
1811
1812 addUnknownControlFlow(BB);
1813 continue;
1814 }
1815
1816 // If this block contains an epilogue code and has an indirect branch,
1817 // then most likely it's a tail call. Otherwise, we cannot tell for sure
1818 // what it is and conservatively reject the function's CFG.
1819 bool IsEpilogue = false;
1820 for (const MCInst &Instr : BB) {
1821 if (BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr)) {
1822 IsEpilogue = true;
1823 break;
1824 }
1825 }
1826 if (IsEpilogue) {
1827 BC.MIB->convertJmpToTailCall(Instr);
1828 BB.removeAllSuccessors();
1829 continue;
1830 }
1831
1832 if (opts::Verbosity >= 2) {
1833 outs() << "BOLT-INFO: rejected potential indirect tail call in "
1834 << "function " << *this << " in basic block " << BB.getName()
1835 << ".\n";
1836 LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(),
1837 BB.getOffset(), this, true));
1838 }
1839
1840 if (!opts::StrictMode)
1841 return false;
1842
1843 addUnknownControlFlow(BB);
1844 }
1845 }
1846
1847 if (HasInternalLabelReference)
1848 return false;
1849
1850 // If there's only one jump table, and one indirect jump, and no other
1851 // references, then we should be able to derive the jump table even if we
1852 // fail to match the pattern.
1853 if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1854 JumpTables.size() == 1 && LastIndirectJump) {
1855 BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1856 HasUnknownControlFlow = false;
1857
1858 LastIndirectJumpBB->updateJumpTableSuccessors();
1859 }
1860
1861 if (HasFixedIndirectBranch)
1862 return false;
1863
1864 if (HasUnknownControlFlow && !BC.HasRelocations)
1865 return false;
1866
1867 return true;
1868 }
1869
recomputeLandingPads()1870 void BinaryFunction::recomputeLandingPads() {
1871 updateBBIndices(0);
1872
1873 for (BinaryBasicBlock *BB : BasicBlocks) {
1874 BB->LandingPads.clear();
1875 BB->Throwers.clear();
1876 }
1877
1878 for (BinaryBasicBlock *BB : BasicBlocks) {
1879 std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1880 for (MCInst &Instr : *BB) {
1881 if (!BC.MIB->isInvoke(Instr))
1882 continue;
1883
1884 const Optional<MCPlus::MCLandingPad> EHInfo = BC.MIB->getEHInfo(Instr);
1885 if (!EHInfo || !EHInfo->first)
1886 continue;
1887
1888 BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1889 if (!BBLandingPads.count(LPBlock)) {
1890 BBLandingPads.insert(LPBlock);
1891 BB->LandingPads.emplace_back(LPBlock);
1892 LPBlock->Throwers.emplace_back(BB);
1893 }
1894 }
1895 }
1896 }
1897
buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId)1898 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1899 auto &MIB = BC.MIB;
1900
1901 if (!isSimple()) {
1902 assert(!BC.HasRelocations &&
1903 "cannot process file with non-simple function in relocs mode");
1904 return false;
1905 }
1906
1907 if (CurrentState != State::Disassembled)
1908 return false;
1909
1910 assert(BasicBlocks.empty() && "basic block list should be empty");
1911 assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) &&
1912 "first instruction should always have a label");
1913
1914 // Create basic blocks in the original layout order:
1915 //
1916 // * Every instruction with associated label marks
1917 // the beginning of a basic block.
1918 // * Conditional instruction marks the end of a basic block,
1919 // except when the following instruction is an
1920 // unconditional branch, and the unconditional branch is not
1921 // a destination of another branch. In the latter case, the
1922 // basic block will consist of a single unconditional branch
1923 // (missed "double-jump" optimization).
1924 //
1925 // Created basic blocks are sorted in layout order since they are
1926 // created in the same order as instructions, and instructions are
1927 // sorted by offsets.
1928 BinaryBasicBlock *InsertBB = nullptr;
1929 BinaryBasicBlock *PrevBB = nullptr;
1930 bool IsLastInstrNop = false;
1931 // Offset of the last non-nop instruction.
1932 uint64_t LastInstrOffset = 0;
1933
1934 auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1935 BinaryBasicBlock *InsertBB) {
1936 for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1937 FE = OffsetToCFI.upper_bound(CFIOffset);
1938 FI != FE; ++FI) {
1939 addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1940 }
1941 };
1942
1943 // For profiling purposes we need to save the offset of the last instruction
1944 // in the basic block.
1945 // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1946 // older profiles ignored nops.
1947 auto updateOffset = [&](uint64_t Offset) {
1948 assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1949 MCInst *LastNonNop = nullptr;
1950 for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1951 E = PrevBB->rend();
1952 RII != E; ++RII) {
1953 if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1954 LastNonNop = &*RII;
1955 break;
1956 }
1957 }
1958 if (LastNonNop && !MIB->getOffset(*LastNonNop))
1959 MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
1960 };
1961
1962 for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
1963 const uint32_t Offset = I->first;
1964 MCInst &Instr = I->second;
1965
1966 auto LI = Labels.find(Offset);
1967 if (LI != Labels.end()) {
1968 // Always create new BB at branch destination.
1969 PrevBB = InsertBB ? InsertBB : PrevBB;
1970 InsertBB = addBasicBlockAt(LI->first, LI->second);
1971 if (opts::PreserveBlocksAlignment && IsLastInstrNop)
1972 InsertBB->setDerivedAlignment();
1973
1974 if (PrevBB)
1975 updateOffset(LastInstrOffset);
1976 }
1977
1978 const uint64_t InstrInputAddr = I->first + Address;
1979 bool IsSDTMarker =
1980 MIB->isNoop(Instr) && BC.SDTMarkers.count(InstrInputAddr);
1981 bool IsLKMarker = BC.LKMarkers.count(InstrInputAddr);
1982 // Mark all nops with Offset for profile tracking purposes.
1983 if (MIB->isNoop(Instr) || IsLKMarker) {
1984 if (!MIB->getOffset(Instr))
1985 MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
1986 if (IsSDTMarker || IsLKMarker)
1987 HasSDTMarker = true;
1988 else
1989 // Annotate ordinary nops, so we can safely delete them if required.
1990 MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
1991 }
1992
1993 if (!InsertBB) {
1994 // It must be a fallthrough or unreachable code. Create a new block unless
1995 // we see an unconditional branch following a conditional one. The latter
1996 // should not be a conditional tail call.
1997 assert(PrevBB && "no previous basic block for a fall through");
1998 MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
1999 assert(PrevInstr && "no previous instruction for a fall through");
2000 if (MIB->isUnconditionalBranch(Instr) &&
2001 !MIB->isUnconditionalBranch(*PrevInstr) &&
2002 !MIB->getConditionalTailCall(*PrevInstr) &&
2003 !MIB->isReturn(*PrevInstr)) {
2004 // Temporarily restore inserter basic block.
2005 InsertBB = PrevBB;
2006 } else {
2007 MCSymbol *Label;
2008 {
2009 auto L = BC.scopeLock();
2010 Label = BC.Ctx->createNamedTempSymbol("FT");
2011 }
2012 InsertBB = addBasicBlockAt(Offset, Label);
2013 if (opts::PreserveBlocksAlignment && IsLastInstrNop)
2014 InsertBB->setDerivedAlignment();
2015 updateOffset(LastInstrOffset);
2016 }
2017 }
2018 if (Offset == getFirstInstructionOffset()) {
2019 // Add associated CFI pseudos in the first offset
2020 addCFIPlaceholders(Offset, InsertBB);
2021 }
2022
2023 const bool IsBlockEnd = MIB->isTerminator(Instr);
2024 IsLastInstrNop = MIB->isNoop(Instr);
2025 if (!IsLastInstrNop)
2026 LastInstrOffset = Offset;
2027 InsertBB->addInstruction(std::move(Instr));
2028
2029 // Add associated CFI instrs. We always add the CFI instruction that is
2030 // located immediately after this instruction, since the next CFI
2031 // instruction reflects the change in state caused by this instruction.
2032 auto NextInstr = std::next(I);
2033 uint64_t CFIOffset;
2034 if (NextInstr != E)
2035 CFIOffset = NextInstr->first;
2036 else
2037 CFIOffset = getSize();
2038
2039 // Note: this potentially invalidates instruction pointers/iterators.
2040 addCFIPlaceholders(CFIOffset, InsertBB);
2041
2042 if (IsBlockEnd) {
2043 PrevBB = InsertBB;
2044 InsertBB = nullptr;
2045 }
2046 }
2047
2048 if (BasicBlocks.empty()) {
2049 setSimple(false);
2050 return false;
2051 }
2052
2053 // Intermediate dump.
2054 LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2055
2056 // TODO: handle properly calls to no-return functions,
2057 // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2058 // blocks.
2059
2060 for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2061 LLVM_DEBUG(dbgs() << "registering branch [0x"
2062 << Twine::utohexstr(Branch.first) << "] -> [0x"
2063 << Twine::utohexstr(Branch.second) << "]\n");
2064 BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2065 BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2066 if (!FromBB || !ToBB) {
2067 if (!FromBB)
2068 errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2069 if (!ToBB)
2070 errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2071 BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2072 *this);
2073 }
2074
2075 FromBB->addSuccessor(ToBB);
2076 }
2077
2078 // Add fall-through branches.
2079 PrevBB = nullptr;
2080 bool IsPrevFT = false; // Is previous block a fall-through.
2081 for (BinaryBasicBlock *BB : BasicBlocks) {
2082 if (IsPrevFT)
2083 PrevBB->addSuccessor(BB);
2084
2085 if (BB->empty()) {
2086 IsPrevFT = true;
2087 PrevBB = BB;
2088 continue;
2089 }
2090
2091 MCInst *LastInstr = BB->getLastNonPseudoInstr();
2092 assert(LastInstr &&
2093 "should have non-pseudo instruction in non-empty block");
2094
2095 if (BB->succ_size() == 0) {
2096 // Since there's no existing successors, we know the last instruction is
2097 // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2098 // fall-through.
2099 //
2100 // Conditional tail call is a special case since we don't add a taken
2101 // branch successor for it.
2102 IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2103 MIB->getConditionalTailCall(*LastInstr);
2104 } else if (BB->succ_size() == 1) {
2105 IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2106 } else {
2107 IsPrevFT = false;
2108 }
2109
2110 PrevBB = BB;
2111 }
2112
2113 // Assign landing pads and throwers info.
2114 recomputeLandingPads();
2115
2116 // Assign CFI information to each BB entry.
2117 annotateCFIState();
2118
2119 // Annotate invoke instructions with GNU_args_size data.
2120 propagateGnuArgsSizeInfo(AllocatorId);
2121
2122 // Set the basic block layout to the original order and set end offsets.
2123 PrevBB = nullptr;
2124 for (BinaryBasicBlock *BB : BasicBlocks) {
2125 Layout.addBasicBlock(BB);
2126 if (PrevBB)
2127 PrevBB->setEndOffset(BB->getOffset());
2128 PrevBB = BB;
2129 }
2130 PrevBB->setEndOffset(getSize());
2131
2132 Layout.updateLayoutIndices();
2133
2134 normalizeCFIState();
2135
2136 // Clean-up memory taken by intermediate structures.
2137 //
2138 // NB: don't clear Labels list as we may need them if we mark the function
2139 // as non-simple later in the process of discovering extra entry points.
2140 clearList(Instructions);
2141 clearList(OffsetToCFI);
2142 clearList(TakenBranches);
2143
2144 // Update the state.
2145 CurrentState = State::CFG;
2146
2147 // Make any necessary adjustments for indirect branches.
2148 if (!postProcessIndirectBranches(AllocatorId)) {
2149 if (opts::Verbosity) {
2150 errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2151 << *this << '\n';
2152 }
2153 // In relocation mode we want to keep processing the function but avoid
2154 // optimizing it.
2155 setSimple(false);
2156 }
2157
2158 clearList(ExternallyReferencedOffsets);
2159 clearList(UnknownIndirectBranchOffsets);
2160
2161 return true;
2162 }
2163
postProcessCFG()2164 void BinaryFunction::postProcessCFG() {
2165 if (isSimple() && !BasicBlocks.empty()) {
2166 // Convert conditional tail call branches to conditional branches that jump
2167 // to a tail call.
2168 removeConditionalTailCalls();
2169
2170 postProcessProfile();
2171
2172 // Eliminate inconsistencies between branch instructions and CFG.
2173 postProcessBranches();
2174 }
2175
2176 calculateMacroOpFusionStats();
2177
2178 // The final cleanup of intermediate structures.
2179 clearList(IgnoredBranches);
2180
2181 // Remove "Offset" annotations, unless we need an address-translation table
2182 // later. This has no cost, since annotations are allocated by a bumpptr
2183 // allocator and won't be released anyway until late in the pipeline.
2184 if (!requiresAddressTranslation() && !opts::Instrument) {
2185 for (BinaryBasicBlock &BB : blocks())
2186 for (MCInst &Inst : BB)
2187 BC.MIB->clearOffset(Inst);
2188 }
2189
2190 assert((!isSimple() || validateCFG()) &&
2191 "invalid CFG detected after post-processing");
2192 }
2193
calculateMacroOpFusionStats()2194 void BinaryFunction::calculateMacroOpFusionStats() {
2195 if (!getBinaryContext().isX86())
2196 return;
2197 for (const BinaryBasicBlock &BB : blocks()) {
2198 auto II = BB.getMacroOpFusionPair();
2199 if (II == BB.end())
2200 continue;
2201
2202 // Check offset of the second instruction.
2203 // FIXME: arch-specific.
2204 const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2205 if (!Offset || (getAddress() + Offset) % 64)
2206 continue;
2207
2208 LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2209 << Twine::utohexstr(getAddress() + Offset)
2210 << " in function " << *this << "; executed "
2211 << BB.getKnownExecutionCount() << " times.\n");
2212 ++BC.MissedMacroFusionPairs;
2213 BC.MissedMacroFusionExecCount += BB.getKnownExecutionCount();
2214 }
2215 }
2216
removeTagsFromProfile()2217 void BinaryFunction::removeTagsFromProfile() {
2218 for (BinaryBasicBlock *BB : BasicBlocks) {
2219 if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2220 BB->ExecutionCount = 0;
2221 for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2222 if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2223 BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2224 continue;
2225 BI.Count = 0;
2226 BI.MispredictedCount = 0;
2227 }
2228 }
2229 }
2230
removeConditionalTailCalls()2231 void BinaryFunction::removeConditionalTailCalls() {
2232 // Blocks to be appended at the end.
2233 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2234
2235 for (auto BBI = begin(); BBI != end(); ++BBI) {
2236 BinaryBasicBlock &BB = *BBI;
2237 MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2238 if (!CTCInstr)
2239 continue;
2240
2241 Optional<uint64_t> TargetAddressOrNone =
2242 BC.MIB->getConditionalTailCall(*CTCInstr);
2243 if (!TargetAddressOrNone)
2244 continue;
2245
2246 // Gather all necessary information about CTC instruction before
2247 // annotations are destroyed.
2248 const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2249 uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2250 uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2251 if (hasValidProfile()) {
2252 CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2253 *CTCInstr, "CTCTakenCount");
2254 CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2255 *CTCInstr, "CTCMispredCount");
2256 }
2257
2258 // Assert that the tail call does not throw.
2259 assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2260 "found tail call with associated landing pad");
2261
2262 // Create a basic block with an unconditional tail call instruction using
2263 // the same destination.
2264 const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2265 assert(CTCTargetLabel && "symbol expected for conditional tail call");
2266 MCInst TailCallInstr;
2267 BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2268 // Link new BBs to the original input offset of the BB where the CTC
2269 // is, so we can map samples recorded in new BBs back to the original BB
2270 // seem in the input binary (if using BAT)
2271 std::unique_ptr<BinaryBasicBlock> TailCallBB =
2272 createBasicBlock(BC.Ctx->createNamedTempSymbol("TC"));
2273 TailCallBB->setOffset(BB.getInputOffset());
2274 TailCallBB->addInstruction(TailCallInstr);
2275 TailCallBB->setCFIState(CFIStateBeforeCTC);
2276
2277 // Add CFG edge with profile info from BB to TailCallBB.
2278 BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2279
2280 // Add execution count for the block.
2281 TailCallBB->setExecutionCount(CTCTakenCount);
2282
2283 BC.MIB->convertTailCallToJmp(*CTCInstr);
2284
2285 BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2286 BC.Ctx.get());
2287
2288 // Add basic block to the list that will be added to the end.
2289 NewBlocks.emplace_back(std::move(TailCallBB));
2290
2291 // Swap edges as the TailCallBB corresponds to the taken branch.
2292 BB.swapConditionalSuccessors();
2293
2294 // This branch is no longer a conditional tail call.
2295 BC.MIB->unsetConditionalTailCall(*CTCInstr);
2296 }
2297
2298 insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2299 /* UpdateLayout */ true,
2300 /* UpdateCFIState */ false);
2301 }
2302
getFunctionScore() const2303 uint64_t BinaryFunction::getFunctionScore() const {
2304 if (FunctionScore != -1)
2305 return FunctionScore;
2306
2307 if (!isSimple() || !hasValidProfile()) {
2308 FunctionScore = 0;
2309 return FunctionScore;
2310 }
2311
2312 uint64_t TotalScore = 0ULL;
2313 for (const BinaryBasicBlock &BB : blocks()) {
2314 uint64_t BBExecCount = BB.getExecutionCount();
2315 if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2316 continue;
2317 TotalScore += BBExecCount * BB.getNumNonPseudos();
2318 }
2319 FunctionScore = TotalScore;
2320 return FunctionScore;
2321 }
2322
annotateCFIState()2323 void BinaryFunction::annotateCFIState() {
2324 assert(CurrentState == State::Disassembled && "unexpected function state");
2325 assert(!BasicBlocks.empty() && "basic block list should not be empty");
2326
2327 // This is an index of the last processed CFI in FDE CFI program.
2328 uint32_t State = 0;
2329
2330 // This is an index of RememberState CFI reflecting effective state right
2331 // after execution of RestoreState CFI.
2332 //
2333 // It differs from State iff the CFI at (State-1)
2334 // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2335 //
2336 // This allows us to generate shorter replay sequences when producing new
2337 // CFI programs.
2338 uint32_t EffectiveState = 0;
2339
2340 // For tracking RememberState/RestoreState sequences.
2341 std::stack<uint32_t> StateStack;
2342
2343 for (BinaryBasicBlock *BB : BasicBlocks) {
2344 BB->setCFIState(EffectiveState);
2345
2346 for (const MCInst &Instr : *BB) {
2347 const MCCFIInstruction *CFI = getCFIFor(Instr);
2348 if (!CFI)
2349 continue;
2350
2351 ++State;
2352
2353 switch (CFI->getOperation()) {
2354 case MCCFIInstruction::OpRememberState:
2355 StateStack.push(EffectiveState);
2356 EffectiveState = State;
2357 break;
2358 case MCCFIInstruction::OpRestoreState:
2359 assert(!StateStack.empty() && "corrupt CFI stack");
2360 EffectiveState = StateStack.top();
2361 StateStack.pop();
2362 break;
2363 case MCCFIInstruction::OpGnuArgsSize:
2364 // OpGnuArgsSize CFIs do not affect the CFI state.
2365 break;
2366 default:
2367 // Any other CFI updates the state.
2368 EffectiveState = State;
2369 break;
2370 }
2371 }
2372 }
2373
2374 assert(StateStack.empty() && "corrupt CFI stack");
2375 }
2376
2377 namespace {
2378
2379 /// Our full interpretation of a DWARF CFI machine state at a given point
2380 struct CFISnapshot {
2381 /// CFA register number and offset defining the canonical frame at this
2382 /// point, or the number of a rule (CFI state) that computes it with a
2383 /// DWARF expression. This number will be negative if it refers to a CFI
2384 /// located in the CIE instead of the FDE.
2385 uint32_t CFAReg;
2386 int32_t CFAOffset;
2387 int32_t CFARule;
2388 /// Mapping of rules (CFI states) that define the location of each
2389 /// register. If absent, no rule defining the location of such register
2390 /// was ever read. This number will be negative if it refers to a CFI
2391 /// located in the CIE instead of the FDE.
2392 DenseMap<int32_t, int32_t> RegRule;
2393
2394 /// References to CIE, FDE and expanded instructions after a restore state
2395 const BinaryFunction::CFIInstrMapType &CIE;
2396 const BinaryFunction::CFIInstrMapType &FDE;
2397 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2398
2399 /// Current FDE CFI number representing the state where the snapshot is at
2400 int32_t CurState;
2401
2402 /// Used when we don't have information about which state/rule to apply
2403 /// to recover the location of either the CFA or a specific register
2404 constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2405
2406 private:
2407 /// Update our snapshot by executing a single CFI
updatellvm::bolt::__anon03fb23f90f11::CFISnapshot2408 void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2409 switch (Instr.getOperation()) {
2410 case MCCFIInstruction::OpSameValue:
2411 case MCCFIInstruction::OpRelOffset:
2412 case MCCFIInstruction::OpOffset:
2413 case MCCFIInstruction::OpRestore:
2414 case MCCFIInstruction::OpUndefined:
2415 case MCCFIInstruction::OpRegister:
2416 RegRule[Instr.getRegister()] = RuleNumber;
2417 break;
2418 case MCCFIInstruction::OpDefCfaRegister:
2419 CFAReg = Instr.getRegister();
2420 CFARule = UNKNOWN;
2421 break;
2422 case MCCFIInstruction::OpDefCfaOffset:
2423 CFAOffset = Instr.getOffset();
2424 CFARule = UNKNOWN;
2425 break;
2426 case MCCFIInstruction::OpDefCfa:
2427 CFAReg = Instr.getRegister();
2428 CFAOffset = Instr.getOffset();
2429 CFARule = UNKNOWN;
2430 break;
2431 case MCCFIInstruction::OpEscape: {
2432 Optional<uint8_t> Reg = readDWARFExpressionTargetReg(Instr.getValues());
2433 // Handle DW_CFA_def_cfa_expression
2434 if (!Reg) {
2435 CFARule = RuleNumber;
2436 break;
2437 }
2438 RegRule[*Reg] = RuleNumber;
2439 break;
2440 }
2441 case MCCFIInstruction::OpAdjustCfaOffset:
2442 case MCCFIInstruction::OpWindowSave:
2443 case MCCFIInstruction::OpNegateRAState:
2444 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2445 llvm_unreachable("unsupported CFI opcode");
2446 break;
2447 case MCCFIInstruction::OpRememberState:
2448 case MCCFIInstruction::OpRestoreState:
2449 case MCCFIInstruction::OpGnuArgsSize:
2450 // do not affect CFI state
2451 break;
2452 }
2453 }
2454
2455 public:
2456 /// Advance state reading FDE CFI instructions up to State number
advanceTollvm::bolt::__anon03fb23f90f11::CFISnapshot2457 void advanceTo(int32_t State) {
2458 for (int32_t I = CurState, E = State; I != E; ++I) {
2459 const MCCFIInstruction &Instr = FDE[I];
2460 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2461 update(Instr, I);
2462 continue;
2463 }
2464 // If restore state instruction, fetch the equivalent CFIs that have
2465 // the same effect of this restore. This is used to ensure remember-
2466 // restore pairs are completely removed.
2467 auto Iter = FrameRestoreEquivalents.find(I);
2468 if (Iter == FrameRestoreEquivalents.end())
2469 continue;
2470 for (int32_t RuleNumber : Iter->second)
2471 update(FDE[RuleNumber], RuleNumber);
2472 }
2473
2474 assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2475 CFARule != UNKNOWN) &&
2476 "CIE did not define default CFA?");
2477
2478 CurState = State;
2479 }
2480
2481 /// Interpret all CIE and FDE instructions up until CFI State number and
2482 /// populate this snapshot
CFISnapshotllvm::bolt::__anon03fb23f90f11::CFISnapshot2483 CFISnapshot(
2484 const BinaryFunction::CFIInstrMapType &CIE,
2485 const BinaryFunction::CFIInstrMapType &FDE,
2486 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2487 int32_t State)
2488 : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2489 CFAReg = UNKNOWN;
2490 CFAOffset = UNKNOWN;
2491 CFARule = UNKNOWN;
2492 CurState = 0;
2493
2494 for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2495 const MCCFIInstruction &Instr = CIE[I];
2496 update(Instr, -I);
2497 }
2498
2499 advanceTo(State);
2500 }
2501 };
2502
2503 /// A CFI snapshot with the capability of checking if incremental additions to
2504 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2505 /// back-to-back that are doing the same state change, or to avoid emitting a
2506 /// CFI at all when the state at that point would not be modified after that CFI
2507 struct CFISnapshotDiff : public CFISnapshot {
2508 bool RestoredCFAReg{false};
2509 bool RestoredCFAOffset{false};
2510 DenseMap<int32_t, bool> RestoredRegs;
2511
CFISnapshotDiffllvm::bolt::__anon03fb23f90f11::CFISnapshotDiff2512 CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2513
CFISnapshotDiffllvm::bolt::__anon03fb23f90f11::CFISnapshotDiff2514 CFISnapshotDiff(
2515 const BinaryFunction::CFIInstrMapType &CIE,
2516 const BinaryFunction::CFIInstrMapType &FDE,
2517 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2518 int32_t State)
2519 : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2520
2521 /// Return true if applying Instr to this state is redundant and can be
2522 /// dismissed.
isRedundantllvm::bolt::__anon03fb23f90f11::CFISnapshotDiff2523 bool isRedundant(const MCCFIInstruction &Instr) {
2524 switch (Instr.getOperation()) {
2525 case MCCFIInstruction::OpSameValue:
2526 case MCCFIInstruction::OpRelOffset:
2527 case MCCFIInstruction::OpOffset:
2528 case MCCFIInstruction::OpRestore:
2529 case MCCFIInstruction::OpUndefined:
2530 case MCCFIInstruction::OpRegister:
2531 case MCCFIInstruction::OpEscape: {
2532 uint32_t Reg;
2533 if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2534 Reg = Instr.getRegister();
2535 } else {
2536 Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2537 // Handle DW_CFA_def_cfa_expression
2538 if (!R) {
2539 if (RestoredCFAReg && RestoredCFAOffset)
2540 return true;
2541 RestoredCFAReg = true;
2542 RestoredCFAOffset = true;
2543 return false;
2544 }
2545 Reg = *R;
2546 }
2547 if (RestoredRegs[Reg])
2548 return true;
2549 RestoredRegs[Reg] = true;
2550 const int32_t CurRegRule =
2551 RegRule.find(Reg) != RegRule.end() ? RegRule[Reg] : UNKNOWN;
2552 if (CurRegRule == UNKNOWN) {
2553 if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2554 Instr.getOperation() == MCCFIInstruction::OpSameValue)
2555 return true;
2556 return false;
2557 }
2558 const MCCFIInstruction &LastDef =
2559 CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2560 return LastDef == Instr;
2561 }
2562 case MCCFIInstruction::OpDefCfaRegister:
2563 if (RestoredCFAReg)
2564 return true;
2565 RestoredCFAReg = true;
2566 return CFAReg == Instr.getRegister();
2567 case MCCFIInstruction::OpDefCfaOffset:
2568 if (RestoredCFAOffset)
2569 return true;
2570 RestoredCFAOffset = true;
2571 return CFAOffset == Instr.getOffset();
2572 case MCCFIInstruction::OpDefCfa:
2573 if (RestoredCFAReg && RestoredCFAOffset)
2574 return true;
2575 RestoredCFAReg = true;
2576 RestoredCFAOffset = true;
2577 return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2578 case MCCFIInstruction::OpAdjustCfaOffset:
2579 case MCCFIInstruction::OpWindowSave:
2580 case MCCFIInstruction::OpNegateRAState:
2581 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2582 llvm_unreachable("unsupported CFI opcode");
2583 return false;
2584 case MCCFIInstruction::OpRememberState:
2585 case MCCFIInstruction::OpRestoreState:
2586 case MCCFIInstruction::OpGnuArgsSize:
2587 // do not affect CFI state
2588 return true;
2589 }
2590 return false;
2591 }
2592 };
2593
2594 } // end anonymous namespace
2595
replayCFIInstrs(int32_t FromState,int32_t ToState,BinaryBasicBlock * InBB,BinaryBasicBlock::iterator InsertIt)2596 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2597 BinaryBasicBlock *InBB,
2598 BinaryBasicBlock::iterator InsertIt) {
2599 if (FromState == ToState)
2600 return true;
2601 assert(FromState < ToState && "can only replay CFIs forward");
2602
2603 CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2604 FrameRestoreEquivalents, FromState);
2605
2606 std::vector<uint32_t> NewCFIs;
2607 for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2608 MCCFIInstruction *Instr = &FrameInstructions[CurState];
2609 if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2610 auto Iter = FrameRestoreEquivalents.find(CurState);
2611 assert(Iter != FrameRestoreEquivalents.end());
2612 NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2613 // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2614 // so we might as well fall-through here.
2615 }
2616 NewCFIs.push_back(CurState);
2617 continue;
2618 }
2619
2620 // Replay instructions while avoiding duplicates
2621 for (auto I = NewCFIs.rbegin(), E = NewCFIs.rend(); I != E; ++I) {
2622 if (CFIDiff.isRedundant(FrameInstructions[*I]))
2623 continue;
2624 InsertIt = addCFIPseudo(InBB, InsertIt, *I);
2625 }
2626
2627 return true;
2628 }
2629
2630 SmallVector<int32_t, 4>
unwindCFIState(int32_t FromState,int32_t ToState,BinaryBasicBlock * InBB,BinaryBasicBlock::iterator & InsertIt)2631 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2632 BinaryBasicBlock *InBB,
2633 BinaryBasicBlock::iterator &InsertIt) {
2634 SmallVector<int32_t, 4> NewStates;
2635
2636 CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2637 FrameRestoreEquivalents, ToState);
2638 CFISnapshotDiff FromCFITable(ToCFITable);
2639 FromCFITable.advanceTo(FromState);
2640
2641 auto undoStateDefCfa = [&]() {
2642 if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2643 FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2644 nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2645 if (FromCFITable.isRedundant(FrameInstructions.back())) {
2646 FrameInstructions.pop_back();
2647 return;
2648 }
2649 NewStates.push_back(FrameInstructions.size() - 1);
2650 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2651 ++InsertIt;
2652 } else if (ToCFITable.CFARule < 0) {
2653 if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2654 return;
2655 NewStates.push_back(FrameInstructions.size());
2656 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2657 ++InsertIt;
2658 FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2659 } else if (!FromCFITable.isRedundant(
2660 FrameInstructions[ToCFITable.CFARule])) {
2661 NewStates.push_back(ToCFITable.CFARule);
2662 InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2663 ++InsertIt;
2664 }
2665 };
2666
2667 auto undoState = [&](const MCCFIInstruction &Instr) {
2668 switch (Instr.getOperation()) {
2669 case MCCFIInstruction::OpRememberState:
2670 case MCCFIInstruction::OpRestoreState:
2671 break;
2672 case MCCFIInstruction::OpSameValue:
2673 case MCCFIInstruction::OpRelOffset:
2674 case MCCFIInstruction::OpOffset:
2675 case MCCFIInstruction::OpRestore:
2676 case MCCFIInstruction::OpUndefined:
2677 case MCCFIInstruction::OpEscape:
2678 case MCCFIInstruction::OpRegister: {
2679 uint32_t Reg;
2680 if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2681 Reg = Instr.getRegister();
2682 } else {
2683 Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2684 // Handle DW_CFA_def_cfa_expression
2685 if (!R) {
2686 undoStateDefCfa();
2687 return;
2688 }
2689 Reg = *R;
2690 }
2691
2692 if (ToCFITable.RegRule.find(Reg) == ToCFITable.RegRule.end()) {
2693 FrameInstructions.emplace_back(
2694 MCCFIInstruction::createRestore(nullptr, Reg));
2695 if (FromCFITable.isRedundant(FrameInstructions.back())) {
2696 FrameInstructions.pop_back();
2697 break;
2698 }
2699 NewStates.push_back(FrameInstructions.size() - 1);
2700 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2701 ++InsertIt;
2702 break;
2703 }
2704 const int32_t Rule = ToCFITable.RegRule[Reg];
2705 if (Rule < 0) {
2706 if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2707 break;
2708 NewStates.push_back(FrameInstructions.size());
2709 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2710 ++InsertIt;
2711 FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2712 break;
2713 }
2714 if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2715 break;
2716 NewStates.push_back(Rule);
2717 InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2718 ++InsertIt;
2719 break;
2720 }
2721 case MCCFIInstruction::OpDefCfaRegister:
2722 case MCCFIInstruction::OpDefCfaOffset:
2723 case MCCFIInstruction::OpDefCfa:
2724 undoStateDefCfa();
2725 break;
2726 case MCCFIInstruction::OpAdjustCfaOffset:
2727 case MCCFIInstruction::OpWindowSave:
2728 case MCCFIInstruction::OpNegateRAState:
2729 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2730 llvm_unreachable("unsupported CFI opcode");
2731 break;
2732 case MCCFIInstruction::OpGnuArgsSize:
2733 // do not affect CFI state
2734 break;
2735 }
2736 };
2737
2738 // Undo all modifications from ToState to FromState
2739 for (int32_t I = ToState, E = FromState; I != E; ++I) {
2740 const MCCFIInstruction &Instr = FrameInstructions[I];
2741 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2742 undoState(Instr);
2743 continue;
2744 }
2745 auto Iter = FrameRestoreEquivalents.find(I);
2746 if (Iter == FrameRestoreEquivalents.end())
2747 continue;
2748 for (int32_t State : Iter->second)
2749 undoState(FrameInstructions[State]);
2750 }
2751
2752 return NewStates;
2753 }
2754
normalizeCFIState()2755 void BinaryFunction::normalizeCFIState() {
2756 // Reordering blocks with remember-restore state instructions can be specially
2757 // tricky. When rewriting the CFI, we omit remember-restore state instructions
2758 // entirely. For restore state, we build a map expanding each restore to the
2759 // equivalent unwindCFIState sequence required at that point to achieve the
2760 // same effect of the restore. All remember state are then just ignored.
2761 std::stack<int32_t> Stack;
2762 for (BinaryBasicBlock *CurBB : Layout.blocks()) {
2763 for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2764 if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2765 if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2766 Stack.push(II->getOperand(0).getImm());
2767 continue;
2768 }
2769 if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2770 const int32_t RememberState = Stack.top();
2771 const int32_t CurState = II->getOperand(0).getImm();
2772 FrameRestoreEquivalents[CurState] =
2773 unwindCFIState(CurState, RememberState, CurBB, II);
2774 Stack.pop();
2775 }
2776 }
2777 }
2778 }
2779 }
2780
finalizeCFIState()2781 bool BinaryFunction::finalizeCFIState() {
2782 LLVM_DEBUG(
2783 dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2784 LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2785 << ": ");
2786
2787 const char *Sep = "";
2788 (void)Sep;
2789 for (const FunctionFragment F : Layout) {
2790 // Hot-cold border: at start of each region (with a different FDE) we need
2791 // to reset the CFI state.
2792 int32_t State = 0;
2793
2794 for (BinaryBasicBlock *BB : F) {
2795 const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2796
2797 // We need to recover the correct state if it doesn't match expected
2798 // state at BB entry point.
2799 if (BB->getCFIState() < State) {
2800 // In this case, State is currently higher than what this BB expect it
2801 // to be. To solve this, we need to insert CFI instructions to undo
2802 // the effect of all CFI from BB's state to current State.
2803 auto InsertIt = BB->begin();
2804 unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2805 } else if (BB->getCFIState() > State) {
2806 // If BB's CFI state is greater than State, it means we are behind in
2807 // the state. Just emit all instructions to reach this state at the
2808 // beginning of this BB. If this sequence of instructions involve
2809 // remember state or restore state, bail out.
2810 if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2811 return false;
2812 }
2813
2814 State = CFIStateAtExit;
2815 LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2816 }
2817 }
2818 LLVM_DEBUG(dbgs() << "\n");
2819
2820 for (BinaryBasicBlock &BB : blocks()) {
2821 for (auto II = BB.begin(); II != BB.end();) {
2822 const MCCFIInstruction *CFI = getCFIFor(*II);
2823 if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2824 CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2825 II = BB.eraseInstruction(II);
2826 } else {
2827 ++II;
2828 }
2829 }
2830 }
2831
2832 return true;
2833 }
2834
requiresAddressTranslation() const2835 bool BinaryFunction::requiresAddressTranslation() const {
2836 return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2837 }
2838
getInstructionCount() const2839 uint64_t BinaryFunction::getInstructionCount() const {
2840 uint64_t Count = 0;
2841 for (const BinaryBasicBlock &BB : blocks())
2842 Count += BB.getNumNonPseudos();
2843 return Count;
2844 }
2845
clearDisasmState()2846 void BinaryFunction::clearDisasmState() {
2847 clearList(Instructions);
2848 clearList(IgnoredBranches);
2849 clearList(TakenBranches);
2850
2851 if (BC.HasRelocations) {
2852 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2853 BC.UndefinedSymbols.insert(LI.second);
2854 if (FunctionEndLabel)
2855 BC.UndefinedSymbols.insert(FunctionEndLabel);
2856 }
2857 }
2858
setTrapOnEntry()2859 void BinaryFunction::setTrapOnEntry() {
2860 clearDisasmState();
2861
2862 auto addTrapAtOffset = [&](uint64_t Offset) {
2863 MCInst TrapInstr;
2864 BC.MIB->createTrap(TrapInstr);
2865 addInstruction(Offset, std::move(TrapInstr));
2866 };
2867
2868 addTrapAtOffset(0);
2869 for (const std::pair<const uint32_t, MCSymbol *> &KV : getLabels())
2870 if (getSecondaryEntryPointSymbol(KV.second))
2871 addTrapAtOffset(KV.first);
2872
2873 TrapsOnEntry = true;
2874 }
2875
setIgnored()2876 void BinaryFunction::setIgnored() {
2877 if (opts::processAllFunctions()) {
2878 // We can accept ignored functions before they've been disassembled.
2879 // In that case, they would still get disassembled and emited, but not
2880 // optimized.
2881 assert(CurrentState == State::Empty &&
2882 "cannot ignore non-empty functions in current mode");
2883 IsIgnored = true;
2884 return;
2885 }
2886
2887 clearDisasmState();
2888
2889 // Clear CFG state too.
2890 if (hasCFG()) {
2891 releaseCFG();
2892
2893 for (BinaryBasicBlock *BB : BasicBlocks)
2894 delete BB;
2895 clearList(BasicBlocks);
2896
2897 for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2898 delete BB;
2899 clearList(DeletedBasicBlocks);
2900
2901 Layout.clear();
2902 }
2903
2904 CurrentState = State::Empty;
2905
2906 IsIgnored = true;
2907 IsSimple = false;
2908 LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2909 }
2910
duplicateConstantIslands()2911 void BinaryFunction::duplicateConstantIslands() {
2912 assert(Islands && "function expected to have constant islands");
2913
2914 for (BinaryBasicBlock *BB : getLayout().blocks()) {
2915 if (!BB->isCold())
2916 continue;
2917
2918 for (MCInst &Inst : *BB) {
2919 int OpNum = 0;
2920 for (MCOperand &Operand : Inst) {
2921 if (!Operand.isExpr()) {
2922 ++OpNum;
2923 continue;
2924 }
2925 const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2926 // Check if this is an island symbol
2927 if (!Islands->Symbols.count(Symbol) &&
2928 !Islands->ProxySymbols.count(Symbol))
2929 continue;
2930
2931 // Create cold symbol, if missing
2932 auto ISym = Islands->ColdSymbols.find(Symbol);
2933 MCSymbol *ColdSymbol;
2934 if (ISym != Islands->ColdSymbols.end()) {
2935 ColdSymbol = ISym->second;
2936 } else {
2937 ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2938 Islands->ColdSymbols[Symbol] = ColdSymbol;
2939 // Check if this is a proxy island symbol and update owner proxy map
2940 if (Islands->ProxySymbols.count(Symbol)) {
2941 BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2942 auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2943 Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2944 }
2945 }
2946
2947 // Update instruction reference
2948 Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
2949 Inst,
2950 MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
2951 *BC.Ctx),
2952 *BC.Ctx, 0));
2953 ++OpNum;
2954 }
2955 }
2956 }
2957 }
2958
2959 namespace {
2960
2961 #ifndef MAX_PATH
2962 #define MAX_PATH 255
2963 #endif
2964
constructFilename(std::string Filename,std::string Annotation,std::string Suffix)2965 std::string constructFilename(std::string Filename, std::string Annotation,
2966 std::string Suffix) {
2967 std::replace(Filename.begin(), Filename.end(), '/', '-');
2968 if (!Annotation.empty())
2969 Annotation.insert(0, "-");
2970 if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
2971 assert(Suffix.size() + Annotation.size() <= MAX_PATH);
2972 if (opts::Verbosity >= 1) {
2973 errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
2974 << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
2975 }
2976 Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
2977 }
2978 Filename += Annotation;
2979 Filename += Suffix;
2980 return Filename;
2981 }
2982
formatEscapes(const std::string & Str)2983 std::string formatEscapes(const std::string &Str) {
2984 std::string Result;
2985 for (unsigned I = 0; I < Str.size(); ++I) {
2986 char C = Str[I];
2987 switch (C) {
2988 case '\n':
2989 Result += " ";
2990 break;
2991 case '"':
2992 break;
2993 default:
2994 Result += C;
2995 break;
2996 }
2997 }
2998 return Result;
2999 }
3000
3001 } // namespace
3002
dumpGraph(raw_ostream & OS) const3003 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3004 OS << "digraph \"" << getPrintName() << "\" {\n"
3005 << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n";
3006 uint64_t Offset = Address;
3007 for (BinaryBasicBlock *BB : BasicBlocks) {
3008 auto LayoutPos = find(Layout.blocks(), BB);
3009 unsigned LayoutIndex = LayoutPos - Layout.block_begin();
3010 const char *ColdStr = BB->isCold() ? " (cold)" : "";
3011 std::vector<std::string> Attrs;
3012 // Bold box for entry points
3013 if (isEntryPoint(*BB))
3014 Attrs.push_back("penwidth=2");
3015 if (BLI && BLI->getLoopFor(BB)) {
3016 // Distinguish innermost loops
3017 const BinaryLoop *Loop = BLI->getLoopFor(BB);
3018 if (Loop->isInnermost())
3019 Attrs.push_back("fillcolor=6");
3020 else // some outer loop
3021 Attrs.push_back("fillcolor=4");
3022 } else { // non-loopy code
3023 Attrs.push_back("fillcolor=5");
3024 }
3025 ListSeparator LS;
3026 OS << "\"" << BB->getName() << "\" [";
3027 for (StringRef Attr : Attrs)
3028 OS << LS << Attr;
3029 OS << "]\n";
3030 OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n",
3031 BB->getName().data(), BB->getName().data(), ColdStr,
3032 BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB),
3033 LayoutIndex, BB->getCFIState());
3034
3035 if (opts::DotToolTipCode) {
3036 std::string Str;
3037 raw_string_ostream CS(Str);
3038 Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this,
3039 /* PrintMCInst = */ false,
3040 /* PrintMemData = */ false,
3041 /* PrintRelocations = */ false,
3042 /* Endl = */ R"(\\l)");
3043 OS << formatEscapes(CS.str()) << '\n';
3044 }
3045 OS << "\"]\n";
3046
3047 // analyzeBranch is just used to get the names of the branch
3048 // opcodes.
3049 const MCSymbol *TBB = nullptr;
3050 const MCSymbol *FBB = nullptr;
3051 MCInst *CondBranch = nullptr;
3052 MCInst *UncondBranch = nullptr;
3053 const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3054
3055 const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3056 const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3057
3058 auto BI = BB->branch_info_begin();
3059 for (BinaryBasicBlock *Succ : BB->successors()) {
3060 std::string Branch;
3061 if (Success) {
3062 if (Succ == BB->getConditionalSuccessor(true)) {
3063 Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3064 CondBranch->getOpcode()))
3065 : "TB";
3066 } else if (Succ == BB->getConditionalSuccessor(false)) {
3067 Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3068 UncondBranch->getOpcode()))
3069 : "FB";
3070 } else {
3071 Branch = "FT";
3072 }
3073 }
3074 if (IsJumpTable)
3075 Branch = "JT";
3076 OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3077 Succ->getName().data(), Branch.c_str());
3078
3079 if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3080 BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3081 OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3082 } else if (ExecutionCount != COUNT_NO_PROFILE &&
3083 BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3084 OS << "\\n(IC:" << BI->Count << ")";
3085 }
3086 OS << "\"]\n";
3087
3088 ++BI;
3089 }
3090 for (BinaryBasicBlock *LP : BB->landing_pads()) {
3091 OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3092 BB->getName().data(), LP->getName().data());
3093 }
3094 }
3095 OS << "}\n";
3096 }
3097
viewGraph() const3098 void BinaryFunction::viewGraph() const {
3099 SmallString<MAX_PATH> Filename;
3100 if (std::error_code EC =
3101 sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3102 errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3103 << " bolt-cfg-XXXXX.dot temporary file.\n";
3104 return;
3105 }
3106 dumpGraphToFile(std::string(Filename));
3107 if (DisplayGraph(Filename))
3108 errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3109 if (std::error_code EC = sys::fs::remove(Filename)) {
3110 errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3111 << Filename << "\n";
3112 }
3113 }
3114
dumpGraphForPass(std::string Annotation) const3115 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3116 if (!opts::shouldPrint(*this))
3117 return;
3118
3119 std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3120 if (opts::Verbosity >= 1)
3121 outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3122 dumpGraphToFile(Filename);
3123 }
3124
dumpGraphToFile(std::string Filename) const3125 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3126 std::error_code EC;
3127 raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3128 if (EC) {
3129 if (opts::Verbosity >= 1) {
3130 errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3131 << Filename << " for output.\n";
3132 }
3133 return;
3134 }
3135 dumpGraph(of);
3136 }
3137
validateCFG() const3138 bool BinaryFunction::validateCFG() const {
3139 bool Valid = true;
3140 for (BinaryBasicBlock *BB : BasicBlocks)
3141 Valid &= BB->validateSuccessorInvariants();
3142
3143 if (!Valid)
3144 return Valid;
3145
3146 // Make sure all blocks in CFG are valid.
3147 auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3148 if (!BB->isValid()) {
3149 errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3150 << " detected in:\n";
3151 this->dump();
3152 return false;
3153 }
3154 return true;
3155 };
3156 for (const BinaryBasicBlock *BB : BasicBlocks) {
3157 if (!validateBlock(BB, "block"))
3158 return false;
3159 for (const BinaryBasicBlock *PredBB : BB->predecessors())
3160 if (!validateBlock(PredBB, "predecessor"))
3161 return false;
3162 for (const BinaryBasicBlock *SuccBB : BB->successors())
3163 if (!validateBlock(SuccBB, "successor"))
3164 return false;
3165 for (const BinaryBasicBlock *LP : BB->landing_pads())
3166 if (!validateBlock(LP, "landing pad"))
3167 return false;
3168 for (const BinaryBasicBlock *Thrower : BB->throwers())
3169 if (!validateBlock(Thrower, "thrower"))
3170 return false;
3171 }
3172
3173 for (const BinaryBasicBlock *BB : BasicBlocks) {
3174 std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3175 for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3176 if (BBLandingPads.count(LP)) {
3177 errs() << "BOLT-ERROR: duplicate landing pad detected in"
3178 << BB->getName() << " in function " << *this << '\n';
3179 return false;
3180 }
3181 BBLandingPads.insert(LP);
3182 }
3183
3184 std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3185 for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3186 if (BBThrowers.count(Thrower)) {
3187 errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3188 << " in function " << *this << '\n';
3189 return false;
3190 }
3191 BBThrowers.insert(Thrower);
3192 }
3193
3194 for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3195 if (!llvm::is_contained(LPBlock->throwers(), BB)) {
3196 errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3197 << ": " << BB->getName() << " is in LandingPads but not in "
3198 << LPBlock->getName() << " Throwers\n";
3199 return false;
3200 }
3201 }
3202 for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3203 if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
3204 errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3205 << ": " << BB->getName() << " is in Throwers list but not in "
3206 << Thrower->getName() << " LandingPads\n";
3207 return false;
3208 }
3209 }
3210 }
3211
3212 return Valid;
3213 }
3214
fixBranches()3215 void BinaryFunction::fixBranches() {
3216 auto &MIB = BC.MIB;
3217 MCContext *Ctx = BC.Ctx.get();
3218
3219 for (BinaryBasicBlock *BB : BasicBlocks) {
3220 const MCSymbol *TBB = nullptr;
3221 const MCSymbol *FBB = nullptr;
3222 MCInst *CondBranch = nullptr;
3223 MCInst *UncondBranch = nullptr;
3224 if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3225 continue;
3226
3227 // We will create unconditional branch with correct destination if needed.
3228 if (UncondBranch)
3229 BB->eraseInstruction(BB->findInstruction(UncondBranch));
3230
3231 // Basic block that follows the current one in the final layout.
3232 const BinaryBasicBlock *NextBB =
3233 Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false);
3234
3235 if (BB->succ_size() == 1) {
3236 // __builtin_unreachable() could create a conditional branch that
3237 // falls-through into the next function - hence the block will have only
3238 // one valid successor. Since behaviour is undefined - we replace
3239 // the conditional branch with an unconditional if required.
3240 if (CondBranch)
3241 BB->eraseInstruction(BB->findInstruction(CondBranch));
3242 if (BB->getSuccessor() == NextBB)
3243 continue;
3244 BB->addBranchInstruction(BB->getSuccessor());
3245 } else if (BB->succ_size() == 2) {
3246 assert(CondBranch && "conditional branch expected");
3247 const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3248 const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3249 // Check whether we support reversing this branch direction
3250 const bool IsSupported =
3251 !MIB->isUnsupportedBranch(CondBranch->getOpcode());
3252 if (NextBB && NextBB == TSuccessor && IsSupported) {
3253 std::swap(TSuccessor, FSuccessor);
3254 {
3255 auto L = BC.scopeLock();
3256 MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3257 }
3258 BB->swapConditionalSuccessors();
3259 } else {
3260 auto L = BC.scopeLock();
3261 MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3262 }
3263 if (TSuccessor == FSuccessor)
3264 BB->removeDuplicateConditionalSuccessor(CondBranch);
3265 if (!NextBB ||
3266 ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3267 // If one of the branches is guaranteed to be "long" while the other
3268 // could be "short", then prioritize short for "taken". This will
3269 // generate a sequence 1 byte shorter on x86.
3270 if (IsSupported && BC.isX86() &&
3271 TSuccessor->isCold() != FSuccessor->isCold() &&
3272 BB->isCold() != TSuccessor->isCold()) {
3273 std::swap(TSuccessor, FSuccessor);
3274 {
3275 auto L = BC.scopeLock();
3276 MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3277 Ctx);
3278 }
3279 BB->swapConditionalSuccessors();
3280 }
3281 BB->addBranchInstruction(FSuccessor);
3282 }
3283 }
3284 // Cases where the number of successors is 0 (block ends with a
3285 // terminator) or more than 2 (switch table) don't require branch
3286 // instruction adjustments.
3287 }
3288 assert((!isSimple() || validateCFG()) &&
3289 "Invalid CFG detected after fixing branches");
3290 }
3291
propagateGnuArgsSizeInfo(MCPlusBuilder::AllocatorIdTy AllocId)3292 void BinaryFunction::propagateGnuArgsSizeInfo(
3293 MCPlusBuilder::AllocatorIdTy AllocId) {
3294 assert(CurrentState == State::Disassembled && "unexpected function state");
3295
3296 if (!hasEHRanges() || !usesGnuArgsSize())
3297 return;
3298
3299 // The current value of DW_CFA_GNU_args_size affects all following
3300 // invoke instructions until the next CFI overrides it.
3301 // It is important to iterate basic blocks in the original order when
3302 // assigning the value.
3303 uint64_t CurrentGnuArgsSize = 0;
3304 for (BinaryBasicBlock *BB : BasicBlocks) {
3305 for (auto II = BB->begin(); II != BB->end();) {
3306 MCInst &Instr = *II;
3307 if (BC.MIB->isCFI(Instr)) {
3308 const MCCFIInstruction *CFI = getCFIFor(Instr);
3309 if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3310 CurrentGnuArgsSize = CFI->getOffset();
3311 // Delete DW_CFA_GNU_args_size instructions and only regenerate
3312 // during the final code emission. The information is embedded
3313 // inside call instructions.
3314 II = BB->erasePseudoInstruction(II);
3315 continue;
3316 }
3317 } else if (BC.MIB->isInvoke(Instr)) {
3318 // Add the value of GNU_args_size as an extra operand to invokes.
3319 BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3320 }
3321 ++II;
3322 }
3323 }
3324 }
3325
postProcessBranches()3326 void BinaryFunction::postProcessBranches() {
3327 if (!isSimple())
3328 return;
3329 for (BinaryBasicBlock &BB : blocks()) {
3330 auto LastInstrRI = BB.getLastNonPseudo();
3331 if (BB.succ_size() == 1) {
3332 if (LastInstrRI != BB.rend() &&
3333 BC.MIB->isConditionalBranch(*LastInstrRI)) {
3334 // __builtin_unreachable() could create a conditional branch that
3335 // falls-through into the next function - hence the block will have only
3336 // one valid successor. Such behaviour is undefined and thus we remove
3337 // the conditional branch while leaving a valid successor.
3338 BB.eraseInstruction(std::prev(LastInstrRI.base()));
3339 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3340 << BB.getName() << " in function " << *this << '\n');
3341 }
3342 } else if (BB.succ_size() == 0) {
3343 // Ignore unreachable basic blocks.
3344 if (BB.pred_size() == 0 || BB.isLandingPad())
3345 continue;
3346
3347 // If it's the basic block that does not end up with a terminator - we
3348 // insert a return instruction unless it's a call instruction.
3349 if (LastInstrRI == BB.rend()) {
3350 LLVM_DEBUG(
3351 dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3352 << BB.getName() << " in function " << *this << '\n');
3353 continue;
3354 }
3355 if (!BC.MIB->isTerminator(*LastInstrRI) &&
3356 !BC.MIB->isCall(*LastInstrRI)) {
3357 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3358 << BB.getName() << " in function " << *this << '\n');
3359 MCInst ReturnInstr;
3360 BC.MIB->createReturn(ReturnInstr);
3361 BB.addInstruction(ReturnInstr);
3362 }
3363 }
3364 }
3365 assert(validateCFG() && "invalid CFG");
3366 }
3367
addEntryPointAtOffset(uint64_t Offset)3368 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3369 assert(Offset && "cannot add primary entry point");
3370 assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3371
3372 const uint64_t EntryPointAddress = getAddress() + Offset;
3373 MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3374
3375 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3376 if (EntrySymbol)
3377 return EntrySymbol;
3378
3379 if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3380 EntrySymbol = EntryBD->getSymbol();
3381 } else {
3382 EntrySymbol = BC.getOrCreateGlobalSymbol(
3383 EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3384 }
3385 SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3386
3387 BC.setSymbolToFunctionMap(EntrySymbol, this);
3388
3389 return EntrySymbol;
3390 }
3391
addEntryPoint(const BinaryBasicBlock & BB)3392 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3393 assert(CurrentState == State::CFG &&
3394 "basic block can be added as an entry only in a function with CFG");
3395
3396 if (&BB == BasicBlocks.front())
3397 return getSymbol();
3398
3399 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3400 if (EntrySymbol)
3401 return EntrySymbol;
3402
3403 EntrySymbol =
3404 BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3405
3406 SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3407
3408 BC.setSymbolToFunctionMap(EntrySymbol, this);
3409
3410 return EntrySymbol;
3411 }
3412
getSymbolForEntryID(uint64_t EntryID)3413 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3414 if (EntryID == 0)
3415 return getSymbol();
3416
3417 if (!isMultiEntry())
3418 return nullptr;
3419
3420 uint64_t NumEntries = 0;
3421 if (hasCFG()) {
3422 for (BinaryBasicBlock *BB : BasicBlocks) {
3423 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3424 if (!EntrySymbol)
3425 continue;
3426 if (NumEntries == EntryID)
3427 return EntrySymbol;
3428 ++NumEntries;
3429 }
3430 } else {
3431 for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3432 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3433 if (!EntrySymbol)
3434 continue;
3435 if (NumEntries == EntryID)
3436 return EntrySymbol;
3437 ++NumEntries;
3438 }
3439 }
3440
3441 return nullptr;
3442 }
3443
getEntryIDForSymbol(const MCSymbol * Symbol) const3444 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3445 if (!isMultiEntry())
3446 return 0;
3447
3448 for (const MCSymbol *FunctionSymbol : getSymbols())
3449 if (FunctionSymbol == Symbol)
3450 return 0;
3451
3452 // Check all secondary entries available as either basic blocks or lables.
3453 uint64_t NumEntries = 0;
3454 for (const BinaryBasicBlock *BB : BasicBlocks) {
3455 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3456 if (!EntrySymbol)
3457 continue;
3458 if (EntrySymbol == Symbol)
3459 return NumEntries;
3460 ++NumEntries;
3461 }
3462 NumEntries = 0;
3463 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3464 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3465 if (!EntrySymbol)
3466 continue;
3467 if (EntrySymbol == Symbol)
3468 return NumEntries;
3469 ++NumEntries;
3470 }
3471
3472 llvm_unreachable("symbol not found");
3473 }
3474
forEachEntryPoint(EntryPointCallbackTy Callback) const3475 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3476 bool Status = Callback(0, getSymbol());
3477 if (!isMultiEntry())
3478 return Status;
3479
3480 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3481 if (!Status)
3482 break;
3483
3484 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3485 if (!EntrySymbol)
3486 continue;
3487
3488 Status = Callback(KV.first, EntrySymbol);
3489 }
3490
3491 return Status;
3492 }
3493
dfs() const3494 BinaryFunction::BasicBlockListType BinaryFunction::dfs() const {
3495 BasicBlockListType DFS;
3496 unsigned Index = 0;
3497 std::stack<BinaryBasicBlock *> Stack;
3498
3499 // Push entry points to the stack in reverse order.
3500 //
3501 // NB: we rely on the original order of entries to match.
3502 SmallVector<BinaryBasicBlock *> EntryPoints;
3503 llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints),
3504 [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); });
3505 // Sort entry points by their offset to make sure we got them in the right
3506 // order.
3507 llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A,
3508 const BinaryBasicBlock *const B) {
3509 return A->getOffset() < B->getOffset();
3510 });
3511 for (BinaryBasicBlock *const BB : reverse(EntryPoints))
3512 Stack.push(BB);
3513
3514 for (BinaryBasicBlock &BB : blocks())
3515 BB.setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3516
3517 while (!Stack.empty()) {
3518 BinaryBasicBlock *BB = Stack.top();
3519 Stack.pop();
3520
3521 if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3522 continue;
3523
3524 BB->setLayoutIndex(Index++);
3525 DFS.push_back(BB);
3526
3527 for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3528 Stack.push(SuccBB);
3529 }
3530
3531 const MCSymbol *TBB = nullptr;
3532 const MCSymbol *FBB = nullptr;
3533 MCInst *CondBranch = nullptr;
3534 MCInst *UncondBranch = nullptr;
3535 if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3536 BB->succ_size() == 2) {
3537 if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3538 *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3539 Stack.push(BB->getConditionalSuccessor(true));
3540 Stack.push(BB->getConditionalSuccessor(false));
3541 } else {
3542 Stack.push(BB->getConditionalSuccessor(false));
3543 Stack.push(BB->getConditionalSuccessor(true));
3544 }
3545 } else {
3546 for (BinaryBasicBlock *SuccBB : BB->successors()) {
3547 Stack.push(SuccBB);
3548 }
3549 }
3550 }
3551
3552 return DFS;
3553 }
3554
computeHash(bool UseDFS,OperandHashFuncTy OperandHashFunc) const3555 size_t BinaryFunction::computeHash(bool UseDFS,
3556 OperandHashFuncTy OperandHashFunc) const {
3557 if (size() == 0)
3558 return 0;
3559
3560 assert(hasCFG() && "function is expected to have CFG");
3561
3562 BasicBlockListType Order;
3563 if (UseDFS)
3564 Order = dfs();
3565 else
3566 llvm::copy(Layout.blocks(), std::back_inserter(Order));
3567
3568 // The hash is computed by creating a string of all instruction opcodes and
3569 // possibly their operands and then hashing that string with std::hash.
3570 std::string HashString;
3571 for (const BinaryBasicBlock *BB : Order) {
3572 for (const MCInst &Inst : *BB) {
3573 unsigned Opcode = Inst.getOpcode();
3574
3575 if (BC.MIB->isPseudo(Inst))
3576 continue;
3577
3578 // Ignore unconditional jumps since we check CFG consistency by processing
3579 // basic blocks in order and do not rely on branches to be in-sync with
3580 // CFG. Note that we still use condition code of conditional jumps.
3581 if (BC.MIB->isUnconditionalBranch(Inst))
3582 continue;
3583
3584 if (Opcode == 0)
3585 HashString.push_back(0);
3586
3587 while (Opcode) {
3588 uint8_t LSB = Opcode & 0xff;
3589 HashString.push_back(LSB);
3590 Opcode = Opcode >> 8;
3591 }
3592
3593 for (const MCOperand &Op : MCPlus::primeOperands(Inst))
3594 HashString.append(OperandHashFunc(Op));
3595 }
3596 }
3597
3598 return Hash = std::hash<std::string>{}(HashString);
3599 }
3600
insertBasicBlocks(BinaryBasicBlock * Start,std::vector<std::unique_ptr<BinaryBasicBlock>> && NewBBs,const bool UpdateLayout,const bool UpdateCFIState,const bool RecomputeLandingPads)3601 void BinaryFunction::insertBasicBlocks(
3602 BinaryBasicBlock *Start,
3603 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3604 const bool UpdateLayout, const bool UpdateCFIState,
3605 const bool RecomputeLandingPads) {
3606 const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3607 const size_t NumNewBlocks = NewBBs.size();
3608
3609 BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3610 nullptr);
3611
3612 int64_t I = StartIndex + 1;
3613 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3614 assert(!BasicBlocks[I]);
3615 BasicBlocks[I++] = BB.release();
3616 }
3617
3618 if (RecomputeLandingPads)
3619 recomputeLandingPads();
3620 else
3621 updateBBIndices(0);
3622
3623 if (UpdateLayout)
3624 updateLayout(Start, NumNewBlocks);
3625
3626 if (UpdateCFIState)
3627 updateCFIState(Start, NumNewBlocks);
3628 }
3629
insertBasicBlocks(BinaryFunction::iterator StartBB,std::vector<std::unique_ptr<BinaryBasicBlock>> && NewBBs,const bool UpdateLayout,const bool UpdateCFIState,const bool RecomputeLandingPads)3630 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3631 BinaryFunction::iterator StartBB,
3632 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3633 const bool UpdateLayout, const bool UpdateCFIState,
3634 const bool RecomputeLandingPads) {
3635 const unsigned StartIndex = getIndex(&*StartBB);
3636 const size_t NumNewBlocks = NewBBs.size();
3637
3638 BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3639 nullptr);
3640 auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3641
3642 unsigned I = StartIndex + 1;
3643 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3644 assert(!BasicBlocks[I]);
3645 BasicBlocks[I++] = BB.release();
3646 }
3647
3648 if (RecomputeLandingPads)
3649 recomputeLandingPads();
3650 else
3651 updateBBIndices(0);
3652
3653 if (UpdateLayout)
3654 updateLayout(*std::prev(RetIter), NumNewBlocks);
3655
3656 if (UpdateCFIState)
3657 updateCFIState(*std::prev(RetIter), NumNewBlocks);
3658
3659 return RetIter;
3660 }
3661
updateBBIndices(const unsigned StartIndex)3662 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3663 for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3664 BasicBlocks[I]->Index = I;
3665 }
3666
updateCFIState(BinaryBasicBlock * Start,const unsigned NumNewBlocks)3667 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3668 const unsigned NumNewBlocks) {
3669 const int32_t CFIState = Start->getCFIStateAtExit();
3670 const unsigned StartIndex = getIndex(Start) + 1;
3671 for (unsigned I = 0; I < NumNewBlocks; ++I)
3672 BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3673 }
3674
updateLayout(BinaryBasicBlock * Start,const unsigned NumNewBlocks)3675 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3676 const unsigned NumNewBlocks) {
3677 BasicBlockListType::iterator Begin;
3678 BasicBlockListType::iterator End;
3679
3680 // If start not provided copy new blocks from the beginning of BasicBlocks
3681 if (!Start) {
3682 Begin = BasicBlocks.begin();
3683 End = BasicBlocks.begin() + NumNewBlocks;
3684 } else {
3685 unsigned StartIndex = getIndex(Start);
3686 Begin = std::next(BasicBlocks.begin(), StartIndex + 1);
3687 End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1);
3688 }
3689
3690 // Insert new blocks in the layout immediately after Start.
3691 Layout.insertBasicBlocks(Start, {Begin, End});
3692 Layout.updateLayoutIndices();
3693 }
3694
checkForAmbiguousJumpTables()3695 bool BinaryFunction::checkForAmbiguousJumpTables() {
3696 SmallSet<uint64_t, 4> JumpTables;
3697 for (BinaryBasicBlock *&BB : BasicBlocks) {
3698 for (MCInst &Inst : *BB) {
3699 if (!BC.MIB->isIndirectBranch(Inst))
3700 continue;
3701 uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3702 if (!JTAddress)
3703 continue;
3704 // This address can be inside another jump table, but we only consider
3705 // it ambiguous when the same start address is used, not the same JT
3706 // object.
3707 if (!JumpTables.count(JTAddress)) {
3708 JumpTables.insert(JTAddress);
3709 continue;
3710 }
3711 return true;
3712 }
3713 }
3714 return false;
3715 }
3716
disambiguateJumpTables(MCPlusBuilder::AllocatorIdTy AllocId)3717 void BinaryFunction::disambiguateJumpTables(
3718 MCPlusBuilder::AllocatorIdTy AllocId) {
3719 assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3720 SmallPtrSet<JumpTable *, 4> JumpTables;
3721 for (BinaryBasicBlock *&BB : BasicBlocks) {
3722 for (MCInst &Inst : *BB) {
3723 if (!BC.MIB->isIndirectBranch(Inst))
3724 continue;
3725 JumpTable *JT = getJumpTable(Inst);
3726 if (!JT)
3727 continue;
3728 auto Iter = JumpTables.find(JT);
3729 if (Iter == JumpTables.end()) {
3730 JumpTables.insert(JT);
3731 continue;
3732 }
3733 // This instruction is an indirect jump using a jump table, but it is
3734 // using the same jump table of another jump. Try all our tricks to
3735 // extract the jump table symbol and make it point to a new, duplicated JT
3736 MCPhysReg BaseReg1;
3737 uint64_t Scale;
3738 const MCSymbol *Target;
3739 // In case we match if our first matcher, first instruction is the one to
3740 // patch
3741 MCInst *JTLoadInst = &Inst;
3742 // Try a standard indirect jump matcher, scale 8
3743 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3744 BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3745 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3746 /*Offset=*/BC.MIB->matchSymbol(Target));
3747 if (!IndJmpMatcher->match(
3748 *BC.MRI, *BC.MIB,
3749 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3750 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3751 MCPhysReg BaseReg2;
3752 uint64_t Offset;
3753 // Standard JT matching failed. Trying now:
3754 // movq "jt.2397/1"(,%rax,8), %rax
3755 // jmpq *%rax
3756 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3757 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3758 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3759 /*Offset=*/BC.MIB->matchSymbol(Target));
3760 MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3761 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3762 BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3763 if (!IndJmpMatcher2->match(
3764 *BC.MRI, *BC.MIB,
3765 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3766 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3767 // JT matching failed. Trying now:
3768 // PIC-style matcher, scale 4
3769 // addq %rdx, %rsi
3770 // addq %rdx, %rdi
3771 // leaq DATAat0x402450(%rip), %r11
3772 // movslq (%r11,%rdx,4), %rcx
3773 // addq %r11, %rcx
3774 // jmpq *%rcx # JUMPTABLE @0x402450
3775 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3776 BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3777 BC.MIB->matchReg(BaseReg1),
3778 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3779 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3780 BC.MIB->matchImm(Offset))));
3781 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3782 BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3783 MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3784 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3785 BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3786 BC.MIB->matchAnyOperand()));
3787 if (!PICIndJmpMatcher->match(
3788 *BC.MRI, *BC.MIB,
3789 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3790 Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3791 !PICBaseAddrMatcher->match(
3792 *BC.MRI, *BC.MIB,
3793 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3794 llvm_unreachable("Failed to extract jump table base");
3795 continue;
3796 }
3797 // Matched PIC, identify the instruction with the reference to the JT
3798 JTLoadInst = LEAMatcher->CurInst;
3799 } else {
3800 // Matched non-PIC
3801 JTLoadInst = LoadMatcher->CurInst;
3802 }
3803 }
3804
3805 uint64_t NewJumpTableID = 0;
3806 const MCSymbol *NewJTLabel;
3807 std::tie(NewJumpTableID, NewJTLabel) =
3808 BC.duplicateJumpTable(*this, JT, Target);
3809 {
3810 auto L = BC.scopeLock();
3811 BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3812 }
3813 // We use a unique ID with the high bit set as address for this "injected"
3814 // jump table (not originally in the input binary).
3815 BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3816 }
3817 }
3818 }
3819
replaceJumpTableEntryIn(BinaryBasicBlock * BB,BinaryBasicBlock * OldDest,BinaryBasicBlock * NewDest)3820 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3821 BinaryBasicBlock *OldDest,
3822 BinaryBasicBlock *NewDest) {
3823 MCInst *Instr = BB->getLastNonPseudoInstr();
3824 if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3825 return false;
3826 uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3827 assert(JTAddress && "Invalid jump table address");
3828 JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3829 assert(JT && "No jump table structure for this indirect branch");
3830 bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3831 NewDest->getLabel());
3832 (void)Patched;
3833 assert(Patched && "Invalid entry to be replaced in jump table");
3834 return true;
3835 }
3836
splitEdge(BinaryBasicBlock * From,BinaryBasicBlock * To)3837 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3838 BinaryBasicBlock *To) {
3839 // Create intermediate BB
3840 MCSymbol *Tmp;
3841 {
3842 auto L = BC.scopeLock();
3843 Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3844 }
3845 // Link new BBs to the original input offset of the From BB, so we can map
3846 // samples recorded in new BBs back to the original BB seem in the input
3847 // binary (if using BAT)
3848 std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
3849 NewBB->setOffset(From->getInputOffset());
3850 BinaryBasicBlock *NewBBPtr = NewBB.get();
3851
3852 // Update "From" BB
3853 auto I = From->succ_begin();
3854 auto BI = From->branch_info_begin();
3855 for (; I != From->succ_end(); ++I) {
3856 if (*I == To)
3857 break;
3858 ++BI;
3859 }
3860 assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3861 uint64_t OrigCount = BI->Count;
3862 uint64_t OrigMispreds = BI->MispredictedCount;
3863 replaceJumpTableEntryIn(From, To, NewBBPtr);
3864 From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3865
3866 NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3867 NewBB->setExecutionCount(OrigCount);
3868 NewBB->setIsCold(From->isCold());
3869
3870 // Update CFI and BB layout with new intermediate BB
3871 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3872 NewBBs.emplace_back(std::move(NewBB));
3873 insertBasicBlocks(From, std::move(NewBBs), true, true,
3874 /*RecomputeLandingPads=*/false);
3875 return NewBBPtr;
3876 }
3877
deleteConservativeEdges()3878 void BinaryFunction::deleteConservativeEdges() {
3879 // Our goal is to aggressively remove edges from the CFG that we believe are
3880 // wrong. This is used for instrumentation, where it is safe to remove
3881 // fallthrough edges because we won't reorder blocks.
3882 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3883 BinaryBasicBlock *BB = *I;
3884 if (BB->succ_size() != 1 || BB->size() == 0)
3885 continue;
3886
3887 auto NextBB = std::next(I);
3888 MCInst *Last = BB->getLastNonPseudoInstr();
3889 // Fallthrough is a landing pad? Delete this edge (as long as we don't
3890 // have a direct jump to it)
3891 if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3892 *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3893 BB->removeAllSuccessors();
3894 continue;
3895 }
3896
3897 // Look for suspicious calls at the end of BB where gcc may optimize it and
3898 // remove the jump to the epilogue when it knows the call won't return.
3899 if (!Last || !BC.MIB->isCall(*Last))
3900 continue;
3901
3902 const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3903 if (!CalleeSymbol)
3904 continue;
3905
3906 StringRef CalleeName = CalleeSymbol->getName();
3907 if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3908 CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3909 CalleeName != "abort@PLT")
3910 continue;
3911
3912 BB->removeAllSuccessors();
3913 }
3914 }
3915
isSymbolValidInScope(const SymbolRef & Symbol,uint64_t SymbolSize) const3916 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3917 uint64_t SymbolSize) const {
3918 // If this symbol is in a different section from the one where the
3919 // function symbol is, don't consider it as valid.
3920 if (!getOriginSection()->containsAddress(
3921 cantFail(Symbol.getAddress(), "cannot get symbol address")))
3922 return false;
3923
3924 // Some symbols are tolerated inside function bodies, others are not.
3925 // The real function boundaries may not be known at this point.
3926 if (BC.isMarker(Symbol))
3927 return true;
3928
3929 // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3930 // function.
3931 if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3932 return true;
3933
3934 if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3935 return false;
3936
3937 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3938 return false;
3939
3940 return true;
3941 }
3942
adjustExecutionCount(uint64_t Count)3943 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3944 if (getKnownExecutionCount() == 0 || Count == 0)
3945 return;
3946
3947 if (ExecutionCount < Count)
3948 Count = ExecutionCount;
3949
3950 double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3951 if (AdjustmentRatio < 0.0)
3952 AdjustmentRatio = 0.0;
3953
3954 for (BinaryBasicBlock &BB : blocks())
3955 BB.adjustExecutionCount(AdjustmentRatio);
3956
3957 ExecutionCount -= Count;
3958 }
3959
~BinaryFunction()3960 BinaryFunction::~BinaryFunction() {
3961 for (BinaryBasicBlock *BB : BasicBlocks)
3962 delete BB;
3963 for (BinaryBasicBlock *BB : DeletedBasicBlocks)
3964 delete BB;
3965 }
3966
calculateLoopInfo()3967 void BinaryFunction::calculateLoopInfo() {
3968 // Discover loops.
3969 BinaryDominatorTree DomTree;
3970 DomTree.recalculate(*this);
3971 BLI.reset(new BinaryLoopInfo());
3972 BLI->analyze(DomTree);
3973
3974 // Traverse discovered loops and add depth and profile information.
3975 std::stack<BinaryLoop *> St;
3976 for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
3977 St.push(*I);
3978 ++BLI->OuterLoops;
3979 }
3980
3981 while (!St.empty()) {
3982 BinaryLoop *L = St.top();
3983 St.pop();
3984 ++BLI->TotalLoops;
3985 BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
3986
3987 // Add nested loops in the stack.
3988 for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3989 St.push(*I);
3990
3991 // Skip if no valid profile is found.
3992 if (!hasValidProfile()) {
3993 L->EntryCount = COUNT_NO_PROFILE;
3994 L->ExitCount = COUNT_NO_PROFILE;
3995 L->TotalBackEdgeCount = COUNT_NO_PROFILE;
3996 continue;
3997 }
3998
3999 // Compute back edge count.
4000 SmallVector<BinaryBasicBlock *, 1> Latches;
4001 L->getLoopLatches(Latches);
4002
4003 for (BinaryBasicBlock *Latch : Latches) {
4004 auto BI = Latch->branch_info_begin();
4005 for (BinaryBasicBlock *Succ : Latch->successors()) {
4006 if (Succ == L->getHeader()) {
4007 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4008 "profile data not found");
4009 L->TotalBackEdgeCount += BI->Count;
4010 }
4011 ++BI;
4012 }
4013 }
4014
4015 // Compute entry count.
4016 L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4017
4018 // Compute exit count.
4019 SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4020 L->getExitEdges(ExitEdges);
4021 for (BinaryLoop::Edge &Exit : ExitEdges) {
4022 const BinaryBasicBlock *Exiting = Exit.first;
4023 const BinaryBasicBlock *ExitTarget = Exit.second;
4024 auto BI = Exiting->branch_info_begin();
4025 for (BinaryBasicBlock *Succ : Exiting->successors()) {
4026 if (Succ == ExitTarget) {
4027 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4028 "profile data not found");
4029 L->ExitCount += BI->Count;
4030 }
4031 ++BI;
4032 }
4033 }
4034 }
4035 }
4036
updateOutputValues(const MCAsmLayout & Layout)4037 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4038 if (!isEmitted()) {
4039 assert(!isInjected() && "injected function should be emitted");
4040 setOutputAddress(getAddress());
4041 setOutputSize(getSize());
4042 return;
4043 }
4044
4045 const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4046 ErrorOr<BinarySection &> ColdSection = getColdCodeSection();
4047 const uint64_t ColdBaseAddress =
4048 isSplit() ? ColdSection->getOutputAddress() : 0;
4049 if (BC.HasRelocations || isInjected()) {
4050 const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4051 const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4052 setOutputAddress(BaseAddress + StartOffset);
4053 setOutputSize(EndOffset - StartOffset);
4054 if (hasConstantIsland()) {
4055 const uint64_t DataOffset =
4056 Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4057 setOutputDataAddress(BaseAddress + DataOffset);
4058 }
4059 if (isSplit()) {
4060 const MCSymbol *ColdStartSymbol = getColdSymbol();
4061 assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4062 "split function should have defined cold symbol");
4063 const MCSymbol *ColdEndSymbol = getFunctionColdEndLabel();
4064 assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4065 "split function should have defined cold end symbol");
4066 const uint64_t ColdStartOffset = Layout.getSymbolOffset(*ColdStartSymbol);
4067 const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4068 cold().setAddress(ColdBaseAddress + ColdStartOffset);
4069 cold().setImageSize(ColdEndOffset - ColdStartOffset);
4070 if (hasConstantIsland()) {
4071 const uint64_t DataOffset =
4072 Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4073 setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4074 }
4075 }
4076 } else {
4077 setOutputAddress(getAddress());
4078 setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4079 }
4080
4081 // Update basic block output ranges for the debug info, if we have
4082 // secondary entry points in the symbol table to update or if writing BAT.
4083 if (!opts::UpdateDebugSections && !isMultiEntry() &&
4084 !requiresAddressTranslation())
4085 return;
4086
4087 // Output ranges should match the input if the body hasn't changed.
4088 if (!isSimple() && !BC.HasRelocations)
4089 return;
4090
4091 // AArch64 may have functions that only contains a constant island (no code).
4092 if (getLayout().block_empty())
4093 return;
4094
4095 BinaryBasicBlock *PrevBB = nullptr;
4096 for (BinaryBasicBlock *BB : this->Layout.blocks()) {
4097 assert(BB->getLabel()->isDefined() && "symbol should be defined");
4098 const uint64_t BBBaseAddress = BB->isCold() ? ColdBaseAddress : BaseAddress;
4099 if (!BC.HasRelocations) {
4100 if (BB->isCold()) {
4101 assert(BBBaseAddress == cold().getAddress());
4102 } else {
4103 assert(BBBaseAddress == getOutputAddress());
4104 }
4105 }
4106 const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4107 const uint64_t BBAddress = BBBaseAddress + BBOffset;
4108 BB->setOutputStartAddress(BBAddress);
4109
4110 if (PrevBB) {
4111 uint64_t PrevBBEndAddress = BBAddress;
4112 if (BB->isCold() != PrevBB->isCold())
4113 PrevBBEndAddress = getOutputAddress() + getOutputSize();
4114 PrevBB->setOutputEndAddress(PrevBBEndAddress);
4115 }
4116 PrevBB = BB;
4117
4118 BB->updateOutputValues(Layout);
4119 }
4120 PrevBB->setOutputEndAddress(PrevBB->isCold()
4121 ? cold().getAddress() + cold().getImageSize()
4122 : getOutputAddress() + getOutputSize());
4123 }
4124
getOutputAddressRanges() const4125 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4126 DebugAddressRangesVector OutputRanges;
4127
4128 if (isFolded())
4129 return OutputRanges;
4130
4131 if (IsFragment)
4132 return OutputRanges;
4133
4134 OutputRanges.emplace_back(getOutputAddress(),
4135 getOutputAddress() + getOutputSize());
4136 if (isSplit()) {
4137 assert(isEmitted() && "split function should be emitted");
4138 OutputRanges.emplace_back(cold().getAddress(),
4139 cold().getAddress() + cold().getImageSize());
4140 }
4141
4142 if (isSimple())
4143 return OutputRanges;
4144
4145 for (BinaryFunction *Frag : Fragments) {
4146 assert(!Frag->isSimple() &&
4147 "fragment of non-simple function should also be non-simple");
4148 OutputRanges.emplace_back(Frag->getOutputAddress(),
4149 Frag->getOutputAddress() + Frag->getOutputSize());
4150 }
4151
4152 return OutputRanges;
4153 }
4154
translateInputToOutputAddress(uint64_t Address) const4155 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4156 if (isFolded())
4157 return 0;
4158
4159 // If the function hasn't changed return the same address.
4160 if (!isEmitted())
4161 return Address;
4162
4163 if (Address < getAddress())
4164 return 0;
4165
4166 // Check if the address is associated with an instruction that is tracked
4167 // by address translation.
4168 auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4169 if (KV != InputOffsetToAddressMap.end())
4170 return KV->second;
4171
4172 // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4173 // intact. Instead we can use pseudo instructions and/or annotations.
4174 const uint64_t Offset = Address - getAddress();
4175 const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4176 if (!BB) {
4177 // Special case for address immediately past the end of the function.
4178 if (Offset == getSize())
4179 return getOutputAddress() + getOutputSize();
4180
4181 return 0;
4182 }
4183
4184 return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4185 BB->getOutputAddressRange().second);
4186 }
4187
translateInputToOutputRanges(const DWARFAddressRangesVector & InputRanges) const4188 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4189 const DWARFAddressRangesVector &InputRanges) const {
4190 DebugAddressRangesVector OutputRanges;
4191
4192 if (isFolded())
4193 return OutputRanges;
4194
4195 // If the function hasn't changed return the same ranges.
4196 if (!isEmitted()) {
4197 OutputRanges.resize(InputRanges.size());
4198 llvm::transform(InputRanges, OutputRanges.begin(),
4199 [](const DWARFAddressRange &Range) {
4200 return DebugAddressRange(Range.LowPC, Range.HighPC);
4201 });
4202 return OutputRanges;
4203 }
4204
4205 // Even though we will merge ranges in a post-processing pass, we attempt to
4206 // merge them in a main processing loop as it improves the processing time.
4207 uint64_t PrevEndAddress = 0;
4208 for (const DWARFAddressRange &Range : InputRanges) {
4209 if (!containsAddress(Range.LowPC)) {
4210 LLVM_DEBUG(
4211 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4212 << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4213 << Twine::utohexstr(Range.HighPC) << "]\n");
4214 PrevEndAddress = 0;
4215 continue;
4216 }
4217 uint64_t InputOffset = Range.LowPC - getAddress();
4218 const uint64_t InputEndOffset =
4219 std::min(Range.HighPC - getAddress(), getSize());
4220
4221 auto BBI = llvm::upper_bound(BasicBlockOffsets,
4222 BasicBlockOffset(InputOffset, nullptr),
4223 CompareBasicBlockOffsets());
4224 --BBI;
4225 do {
4226 const BinaryBasicBlock *BB = BBI->second;
4227 if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4228 LLVM_DEBUG(
4229 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4230 << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4231 << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4232 PrevEndAddress = 0;
4233 break;
4234 }
4235
4236 // Skip the range if the block was deleted.
4237 if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4238 const uint64_t StartAddress =
4239 OutputStart + InputOffset - BB->getOffset();
4240 uint64_t EndAddress = BB->getOutputAddressRange().second;
4241 if (InputEndOffset < BB->getEndOffset())
4242 EndAddress = StartAddress + InputEndOffset - InputOffset;
4243
4244 if (StartAddress == PrevEndAddress) {
4245 OutputRanges.back().HighPC =
4246 std::max(OutputRanges.back().HighPC, EndAddress);
4247 } else {
4248 OutputRanges.emplace_back(StartAddress,
4249 std::max(StartAddress, EndAddress));
4250 }
4251 PrevEndAddress = OutputRanges.back().HighPC;
4252 }
4253
4254 InputOffset = BB->getEndOffset();
4255 ++BBI;
4256 } while (InputOffset < InputEndOffset);
4257 }
4258
4259 // Post-processing pass to sort and merge ranges.
4260 llvm::sort(OutputRanges);
4261 DebugAddressRangesVector MergedRanges;
4262 PrevEndAddress = 0;
4263 for (const DebugAddressRange &Range : OutputRanges) {
4264 if (Range.LowPC <= PrevEndAddress) {
4265 MergedRanges.back().HighPC =
4266 std::max(MergedRanges.back().HighPC, Range.HighPC);
4267 } else {
4268 MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4269 }
4270 PrevEndAddress = MergedRanges.back().HighPC;
4271 }
4272
4273 return MergedRanges;
4274 }
4275
getInstructionAtOffset(uint64_t Offset)4276 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4277 if (CurrentState == State::Disassembled) {
4278 auto II = Instructions.find(Offset);
4279 return (II == Instructions.end()) ? nullptr : &II->second;
4280 } else if (CurrentState == State::CFG) {
4281 BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4282 if (!BB)
4283 return nullptr;
4284
4285 for (MCInst &Inst : *BB) {
4286 constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4287 if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4288 return &Inst;
4289 }
4290
4291 if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4292 const uint32_t Size =
4293 BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4294 if (BB->getEndOffset() - Offset == Size)
4295 return LastInstr;
4296 }
4297
4298 return nullptr;
4299 } else {
4300 llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4301 }
4302 }
4303
translateInputToOutputLocationList(const DebugLocationsVector & InputLL) const4304 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4305 const DebugLocationsVector &InputLL) const {
4306 DebugLocationsVector OutputLL;
4307
4308 if (isFolded())
4309 return OutputLL;
4310
4311 // If the function hasn't changed - there's nothing to update.
4312 if (!isEmitted())
4313 return InputLL;
4314
4315 uint64_t PrevEndAddress = 0;
4316 SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4317 for (const DebugLocationEntry &Entry : InputLL) {
4318 const uint64_t Start = Entry.LowPC;
4319 const uint64_t End = Entry.HighPC;
4320 if (!containsAddress(Start)) {
4321 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4322 "for "
4323 << *this << " : [0x" << Twine::utohexstr(Start)
4324 << ", 0x" << Twine::utohexstr(End) << "]\n");
4325 continue;
4326 }
4327 uint64_t InputOffset = Start - getAddress();
4328 const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4329 auto BBI = llvm::upper_bound(BasicBlockOffsets,
4330 BasicBlockOffset(InputOffset, nullptr),
4331 CompareBasicBlockOffsets());
4332 --BBI;
4333 do {
4334 const BinaryBasicBlock *BB = BBI->second;
4335 if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4336 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4337 "for "
4338 << *this << " : [0x" << Twine::utohexstr(Start)
4339 << ", 0x" << Twine::utohexstr(End) << "]\n");
4340 PrevEndAddress = 0;
4341 break;
4342 }
4343
4344 // Skip the range if the block was deleted.
4345 if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4346 const uint64_t StartAddress =
4347 OutputStart + InputOffset - BB->getOffset();
4348 uint64_t EndAddress = BB->getOutputAddressRange().second;
4349 if (InputEndOffset < BB->getEndOffset())
4350 EndAddress = StartAddress + InputEndOffset - InputOffset;
4351
4352 if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4353 OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4354 } else {
4355 OutputLL.emplace_back(DebugLocationEntry{
4356 StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4357 }
4358 PrevEndAddress = OutputLL.back().HighPC;
4359 PrevExpr = &OutputLL.back().Expr;
4360 }
4361
4362 ++BBI;
4363 InputOffset = BB->getEndOffset();
4364 } while (InputOffset < InputEndOffset);
4365 }
4366
4367 // Sort and merge adjacent entries with identical location.
4368 llvm::stable_sort(
4369 OutputLL, [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4370 return A.LowPC < B.LowPC;
4371 });
4372 DebugLocationsVector MergedLL;
4373 PrevEndAddress = 0;
4374 PrevExpr = nullptr;
4375 for (const DebugLocationEntry &Entry : OutputLL) {
4376 if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4377 MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4378 } else {
4379 const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4380 const uint64_t End = std::max(Begin, Entry.HighPC);
4381 MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4382 }
4383 PrevEndAddress = MergedLL.back().HighPC;
4384 PrevExpr = &MergedLL.back().Expr;
4385 }
4386
4387 return MergedLL;
4388 }
4389
printLoopInfo(raw_ostream & OS) const4390 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4391 if (!opts::shouldPrint(*this))
4392 return;
4393
4394 OS << "Loop Info for Function \"" << *this << "\"";
4395 if (hasValidProfile())
4396 OS << " (count: " << getExecutionCount() << ")";
4397 OS << "\n";
4398
4399 std::stack<BinaryLoop *> St;
4400 for_each(*BLI, [&](BinaryLoop *L) { St.push(L); });
4401 while (!St.empty()) {
4402 BinaryLoop *L = St.top();
4403 St.pop();
4404
4405 for_each(*L, [&](BinaryLoop *Inner) { St.push(Inner); });
4406
4407 if (!hasValidProfile())
4408 continue;
4409
4410 OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4411 << " loop header: " << L->getHeader()->getName();
4412 OS << "\n";
4413 OS << "Loop basic blocks: ";
4414 ListSeparator LS;
4415 for (BinaryBasicBlock *BB : L->blocks())
4416 OS << LS << BB->getName();
4417 OS << "\n";
4418 if (hasValidProfile()) {
4419 OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4420 OS << "Loop entry count: " << L->EntryCount << "\n";
4421 OS << "Loop exit count: " << L->ExitCount << "\n";
4422 if (L->EntryCount > 0) {
4423 OS << "Average iters per entry: "
4424 << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4425 << "\n";
4426 }
4427 }
4428 OS << "----\n";
4429 }
4430
4431 OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4432 OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4433 OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4434 }
4435
isAArch64Veneer() const4436 bool BinaryFunction::isAArch64Veneer() const {
4437 if (empty())
4438 return false;
4439
4440 BinaryBasicBlock &BB = **BasicBlocks.begin();
4441 for (MCInst &Inst : BB)
4442 if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4443 return false;
4444
4445 for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
4446 for (MCInst &Inst : **I)
4447 if (!BC.MIB->isNoop(Inst))
4448 return false;
4449 }
4450
4451 return true;
4452 }
4453
4454 } // namespace bolt
4455 } // namespace llvm
4456