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