1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
48 #define DEBUG_TYPE "bolt"
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(
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 "
73 cl::Hidden
, cl::cat(BoltCategory
));
75 static cl::opt
<bool> DotToolTipCode(
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)"),
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 "
98 cl::cat(BoltOptCategory
));
100 static cl::opt
<bool> NoScan(
103 "do not scan cold functions for external references (may result in "
105 cl::Hidden
, cl::cat(BoltOptCategory
));
108 PreserveBlocksAlignment("preserve-blocks-alignment",
109 cl::desc("try to preserve basic block alignment"),
110 cl::cat(BoltOptCategory
));
113 PrintDynoStats("dyno-stats",
114 cl::desc("print execution info based on profile"),
115 cl::cat(BoltCategory
));
118 PrintDynoStatsOnly("print-dyno-stats-only",
119 cl::desc("while printing functions output dyno-stats and skip instructions"),
122 cl::cat(BoltCategory
));
124 static cl::list
<std::string
>
125 PrintOnly("print-only",
127 cl::desc("list of functions to print"),
128 cl::value_desc("func1,func2,func3,..."),
130 cl::cat(BoltCategory
));
133 TimeBuild("time-build",
134 cl::desc("print time spent constructing binary functions"),
135 cl::Hidden
, cl::cat(BoltCategory
));
138 TrapOnAVX512("trap-avx512",
139 cl::desc("in relocation mode trap upon entry to any function that uses "
140 "AVX-512 instructions"),
144 cl::cat(BoltCategory
));
146 bool shouldPrint(const BinaryFunction
&Function
) {
147 if (Function
.isIgnored())
150 if (PrintOnly
.empty())
153 for (std::string
&Name
: opts::PrintOnly
) {
154 if (Function
.hasNameRegex(Name
)) {
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.
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
)
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
) {
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
) {
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;
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
,
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
);
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());
263 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset
) {
267 if (BasicBlockOffsets
.empty())
271 * This is commented out because it makes BOLT too slow.
272 * assert(std::is_sorted(BasicBlockOffsets.begin(),
273 * BasicBlockOffsets.end(),
274 * CompareBasicBlockOffsets())));
277 llvm::upper_bound(BasicBlockOffsets
, BasicBlockOffset(Offset
, nullptr),
278 CompareBasicBlockOffsets());
279 assert(I
!= BasicBlockOffsets
.begin() && "first basic block not at offset 0");
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())
291 // Add all entries and landing pads as roots.
292 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
293 if (isEntryPoint(*BB
) || BB
->isLandingPad()) {
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
)) {
310 // Determine reachable BBs from the entry point
311 while (!Stack
.empty()) {
312 BinaryBasicBlock
*BB
= Stack
.top();
314 for (BinaryBasicBlock
*Succ
: BB
->successors()) {
317 Succ
->markValid(true);
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
;
329 for (BinaryBasicBlock
*const BB
: BasicBlocks
) {
330 if (!BB
->isValid()) {
331 assert(!isEntryPoint(*BB
) && "all entry blocks must be valid");
332 InvalidBBs
.insert(BB
);
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
);
348 NewBasicBlocks
.push_back(BB
);
351 BasicBlocks
= std::move(NewBasicBlocks
);
353 assert(BasicBlocks
.size() == Layout
.block_size());
355 // Update CFG state if needed
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
);
370 if (CalleeBF
->isInjected())
373 if (hasValidIndex() && CalleeBF
->hasValidIndex()) {
374 return getIndex() < CalleeBF
->getIndex();
375 } else if (hasValidIndex() && !CalleeBF
->hasValidIndex()) {
377 } else if (!hasValidIndex() && CalleeBF
->hasValidIndex()) {
380 return getAddress() < CalleeBF
->getAddress();
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))
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
) {
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();
440 OS
<< "\n IsFragment : true";
442 OS
<< "\n FoldedInto : " << *getFoldedIntoFunction();
443 for (BinaryFunction
*ParentFragment
: ParentFragments
)
444 OS
<< "\n Parent : " << *ParentFragment
;
445 if (!Fragments
.empty()) {
446 OS
<< "\n Fragments : ";
448 for (BinaryFunction
*Frag
: Fragments
)
452 OS
<< "\n Hash : " << Twine::utohexstr(computeHash());
453 if (isMultiEntry()) {
454 OS
<< "\n Secondary Entry Points : ";
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 : ";
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()) {
477 DynoStats dynoStats
= getDynoStats(*this);
483 if (opts::PrintDynoStatsOnly
|| !BC
.InstPrinter
)
486 // Offset of the instruction in function.
489 if (BasicBlocks
.empty() && !Instructions
.empty()) {
490 // Print before CFG was built.
491 for (const std::pair
<const uint32_t, MCInst
> &II
: Instructions
) {
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()) {
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';
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';
533 if (BB
->getCFIState() >= 0)
534 OS
<< " CFI State : " << BB
->getCFIState() << '\n';
535 if (opts::EnableBAT
) {
536 OS
<< " Input offset: " << Twine::utohexstr(BB
->getInputOffset())
539 if (!BB
->pred_empty()) {
540 OS
<< " Predecessors: ";
542 for (BinaryBasicBlock
*Pred
: BB
->predecessors())
543 OS
<< LS
<< Pred
->getName();
546 if (!BB
->throw_empty()) {
549 for (BinaryBasicBlock
*Throw
: BB
->throwers())
550 OS
<< LS
<< Throw
->getName();
554 Offset
= alignTo(Offset
, BB
->getAlignment());
556 // Note: offsets are imprecise since this is happening prior to
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
];
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
<< ")";
588 if (!BB
->lp_empty()) {
589 OS
<< " Landing Pads: ";
591 for (BinaryBasicBlock
*LP
: BB
->landing_pads()) {
592 OS
<< LS
<< LP
->getName();
593 if (ExecutionCount
!= COUNT_NO_PROFILE
) {
594 OS
<< " (count: " << LP
->getExecutionCount() << ")";
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';
611 // Dump new exception ranges for the function.
612 if (!CallSites
.empty()) {
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 : ";
622 OS
<< ", action : " << CSI
.Action
<< '\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
]);
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
);
650 if (FrameInstructions
.empty())
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
<< ")";
668 static std::string
mutateDWARFExpressionTargetReg(const MCCFIInstruction
&Instr
,
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");
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);
682 decodeULEB128(Start
, &Size
, End
);
683 assert(Size
> 0 && "Invalid reg encoding for DWARF expression CFI");
685 raw_svector_ostream
OSE(Tmp
);
686 encodeULEB128(NewReg
, OSE
);
687 return Twine(ExprBytes
.slice(0, 1))
689 .concat(ExprBytes
.drop_front(1 + Size
))
693 void BinaryFunction::mutateCFIRegisterFor(const MCInst
&Instr
,
695 const MCCFIInstruction
*OldCFI
= getCFIFor(Instr
);
696 assert(OldCFI
&& "invalid CFI instr");
697 switch (OldCFI
->getOperation()) {
699 llvm_unreachable("Unexpected instruction");
700 case MCCFIInstruction::OpDefCfa
:
701 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfa(nullptr, NewReg
,
702 OldCFI
->getOffset()));
704 case MCCFIInstruction::OpDefCfaRegister
:
705 setCFIFor(Instr
, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg
));
707 case MCCFIInstruction::OpOffset
:
708 setCFIFor(Instr
, MCCFIInstruction::createOffset(nullptr, NewReg
,
709 OldCFI
->getOffset()));
711 case MCCFIInstruction::OpRegister
:
712 setCFIFor(Instr
, MCCFIInstruction::createRegister(nullptr, NewReg
,
713 OldCFI
->getRegister2()));
715 case MCCFIInstruction::OpSameValue
:
716 setCFIFor(Instr
, MCCFIInstruction::createSameValue(nullptr, NewReg
));
718 case MCCFIInstruction::OpEscape
:
720 MCCFIInstruction::createEscape(
722 StringRef(mutateDWARFExpressionTargetReg(*OldCFI
, NewReg
))));
724 case MCCFIInstruction::OpRestore
:
725 setCFIFor(Instr
, MCCFIInstruction::createRestore(nullptr, NewReg
));
727 case MCCFIInstruction::OpUndefined
:
728 setCFIFor(Instr
, MCCFIInstruction::createUndefined(nullptr, NewReg
));
733 const MCCFIInstruction
*BinaryFunction::mutateCFIOffsetFor(const MCInst
&Instr
,
735 const MCCFIInstruction
*OldCFI
= getCFIFor(Instr
);
736 assert(OldCFI
&& "invalid CFI instr");
737 switch (OldCFI
->getOperation()) {
739 llvm_unreachable("Unexpected instruction");
740 case MCCFIInstruction::OpDefCfaOffset
:
741 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset
));
743 case MCCFIInstruction::OpAdjustCfaOffset
:
745 MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset
));
747 case MCCFIInstruction::OpDefCfa
:
748 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI
->getRegister(),
751 case MCCFIInstruction::OpOffset
:
752 setCFIFor(Instr
, MCCFIInstruction::createOffset(
753 nullptr, OldCFI
->getRegister(), NewOffset
));
756 return getCFIFor(Instr
);
760 BinaryFunction::processIndirectBranch(MCInst
&Instruction
, unsigned Size
,
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.
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
;
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
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()) {
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
)
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
;
816 for (std::pair
<const uint32_t, MCSymbol
*> &Elmt
: Labels
) {
817 if (Elmt
.second
== Sym
) {
818 PCRelAddr
= Elmt
.first
+ getAddress();
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();
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).
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
;
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
);
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 "
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
);
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
)
897 TargetAddress
= *Value
;
901 // Check if there's already a jump table registered at this address.
902 MemoryContentsType MemType
;
903 if (JumpTable
*JT
= BC
.getJumpTableContainingAddress(ArrayStart
)) {
905 case JumpTable::JTT_NORMAL
:
906 MemType
= MemoryContentsType::POSSIBLE_JUMP_TABLE
;
908 case JumpTable::JTT_PIC
:
909 MemType
= MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE
;
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
;
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
);
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())
954 // For AArch64, check if this address is part of a constant island.
955 if (BC
.isAArch64()) {
956 if (MCSymbol
*IslandSym
= getOrCreateIslandAccess(Address
))
960 MCSymbol
*Label
= BC
.Ctx
->createNamedTempSymbol();
961 Labels
[Offset
] = 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 {
989 if (!llvm::is_contained(Islands
->DataOffsets
, Offset
))
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();
1002 auto Iter
= Islands
->DataOffsets
.upper_bound(Offset
);
1003 if (Iter
!= Islands
->DataOffsets
.end())
1006 for (uint64_t I
= Offset
; I
< EndOfCode
; ++I
)
1007 if (FunctionData
[I
] != 0)
1013 void BinaryFunction::handlePCRelOperand(MCInst
&Instruction
, uint64_t Address
,
1016 uint64_t TargetAddress
= 0;
1017 if (!MIB
->evaluateMemOperandTarget(Instruction
, TargetAddress
, Address
,
1019 errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1020 BC
.InstPrinter
->printInst(&Instruction
, 0, "", *BC
.STI
, errs());
1022 Instruction
.dump_pretty(errs(), BC
.InstPrinter
.get());
1024 errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1025 << Twine::utohexstr(Address
) << ". Skipping function " << *this
1027 if (BC
.HasRelocations
)
1032 if (TargetAddress
== 0 && opts::Verbosity
>= 1) {
1033 outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
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
,
1051 uint64_t TargetAddress
,
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.
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";
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
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
,
1096 uint64_t IndirectTarget
= 0;
1097 IndirectBranchType Result
=
1098 processIndirectBranch(Instruction
, Size
, Offset
, IndirectTarget
);
1101 llvm_unreachable("unexpected result");
1102 case IndirectBranchType::POSSIBLE_TAIL_CALL
: {
1103 bool Result
= MIB
->convertJmpToTailCall(Instruction
);
1108 case IndirectBranchType::POSSIBLE_JUMP_TABLE
:
1109 case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE
:
1110 if (opts::JumpTables
== JTS_NONE
)
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;
1121 MIB
->convertJmpToTailCall(Instruction
);
1122 BC
.addInterproceduralReference(this, IndirectTarget
);
1126 case IndirectBranchType::UNKNOWN
:
1127 // Keep processing. We'll do more checks and fixes in
1128 // postProcessIndirectBranches().
1129 UnknownIndirectBranchOffsets
.emplace(Offset
);
1134 void BinaryFunction::handleAArch64IndirectCall(MCInst
&Instruction
,
1135 const uint64_t Offset
) {
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
);
1144 MIB
->addAnnotation(Instruction
, "AArch64Veneer", true);
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
,
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");
1168 BC
.SymbolicDisAsm
->setSymbolizer(MIB
->createTargetSymbolizer(*this));
1170 // Insert a label at the beginning of the function. This will be our first
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
) {
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
;
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
))
1200 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1201 << Twine::utohexstr(Offset
) << " (address 0x"
1202 << Twine::utohexstr(AbsoluteInstrAddr
) << ") in function " << *this
1204 // Some AVX-512 instructions could not be disassembled at all.
1205 if (BC
.HasRelocations
&& opts::TrapOnAVX512
&& BC
.isX86()) {
1207 BC
.TrappedFunctions
.push_back(this);
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
);
1226 // Special handling for AVX-512 instructions.
1227 if (MIB
->hasEVEXEncoding(Instruction
)) {
1228 if (BC
.HasRelocations
&& opts::TrapOnAVX512
) {
1230 BC
.TrappedFunctions
.push_back(this);
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';
1244 if (MIB
->isBranch(Instruction
) || MIB
->isCall(Instruction
)) {
1245 uint64_t TargetAddress
= 0;
1246 if (MIB
->evaluateBranch(Instruction
, AbsoluteInstrAddr
, Size
,
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
)) {
1259 if (BinaryFunction
*TargetFunc
=
1260 BC
.getBinaryFunctionContainingAddress(TargetAddress
))
1261 TargetFunc
->setIgnored();
1264 if (IsCall
&& containsAddress(TargetAddress
)) {
1265 if (TargetAddress
== getAddress()) {
1267 TargetSymbol
= getSymbol();
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;
1274 errs() << "BOLT-WARNING: internal call detected at 0x"
1275 << Twine::utohexstr(AbsoluteInstrAddr
) << " in function "
1276 << *this << ". Skipping.\n";
1282 if (!TargetSymbol
) {
1283 // Create either local label or external symbol.
1284 if (containsAddress(TargetAddress
)) {
1285 TargetSymbol
= getOrCreateLocalLabel(TargetAddress
);
1287 if (TargetAddress
== getAddress() + getSize() &&
1288 TargetAddress
< getAddress() + getMaxSize() &&
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
);
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
);
1310 // Add taken branch info.
1311 TakenBranches
.emplace_back(Offset
, TargetAddress
- getAddress());
1313 BC
.MIB
->replaceBranchTarget(Instruction
, TargetSymbol
, &*Ctx
);
1316 if (IsCondBranch
&& IsCall
)
1317 MIB
->setConditionalTailCall(Instruction
, TargetAddress
);
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
);
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
);
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
,
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.
1364 if (!BC
.isRISCV() && MIB
->hasPCRelOperand(Instruction
) && !UsedReloc
)
1365 handlePCRelOperand(Instruction
, AbsoluteInstrAddr
, Size
);
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
);
1404 clearList(Instructions
);
1408 updateState(State::Disassembled
);
1413 bool BinaryFunction::scanExternalRefs() {
1414 bool Success
= true;
1415 bool DisassemblyFailed
= false;
1417 // Ignore pseudo functions.
1422 clearList(Relocations
);
1423 clearList(ExternallyReferencedOffsets
);
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
;
1453 const uint64_t AbsoluteInstrAddr
= getAddress() + Offset
;
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 "
1465 DisassemblyFailed
= true;
1469 // Return true if we can skip handling the Target function reference.
1470 auto ignoreFunctionRef
= [&](const BinaryFunction
&Target
) {
1471 if (&Target
== this)
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
))
1483 // Return true if we can ignore reference to the symbol.
1484 auto ignoreReference
= [&](const MCSymbol
*TargetSymbol
) {
1488 if (BC
.forceSymbolRelocations(TargetSymbol
->getName()))
1491 BinaryFunction
*TargetFunction
= BC
.getFunctionForSymbol(TargetSymbol
);
1492 if (!TargetFunction
)
1495 return ignoreFunctionRef(*TargetFunction
);
1498 // Handle calls and branches separately as symbolization doesn't work for
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
,
1506 // Create an entry point at reference address if needed.
1507 BinaryFunction
*TargetFunction
=
1508 BC
.getBinaryFunctionContainingAddress(TargetAddress
);
1510 if (!TargetFunction
|| ignoreFunctionRef(*TargetFunction
))
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
1522 if (!BC
.HasRelocations
)
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.
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
);
1547 if (ignoreReference(Rel
->Symbol
))
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.
1557 Rel
->Offset
+= getAddress() - getOriginSection()->getAddress() + Offset
;
1558 FunctionRelocations
.push_back(*Rel
);
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
)
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';
1595 void BinaryFunction::postProcessEntryPoints() {
1599 for (auto &KV
: Labels
) {
1600 MCSymbol
*Label
= KV
.second
;
1601 if (!getSecondaryEntryPointSymbol(Label
))
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
)
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
))
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())
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
)
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 "
1643 const uint64_t BDSize
=
1644 BC
.getBinaryDataAtAddress(JT
.getAddress())->getSize();
1646 BC
.setBinaryDataSize(JT
.getAddress(), JT
.getSize());
1648 assert(BDSize
>= JT
.getSize() &&
1649 "jump table cannot be larger than the containing object");
1651 if (!JT
.Entries
.empty())
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
);
1667 // Create a local label for targets that cannot be reached by other
1668 // fragments. Otherwise, create a secondary entry point in the target
1670 BinaryFunction
*TargetBF
=
1671 BC
.getBinaryFunctionContainingAddress(EntryAddress
);
1673 if (HasOneParent
&& TargetBF
== this) {
1674 Label
= getOrCreateLocalLabel(EntryAddress
, true);
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
))
1714 // Conservatively populate all possible destinations for unknown indirect
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())
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())
1745 // Ignore constant islands
1746 if (isInConstantIsland(Destination
+ getAddress()))
1749 if (BinaryBasicBlock
*BB
= getBasicBlockAtOffset(Destination
)) {
1750 // Check if the externally referenced offset is a recognized jump table
1752 if (JTTargets
.contains(BB
->getLabel()))
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();
1763 errs() << "BOLT-WARNING: unknown data to code reference to offset "
1764 << Twine::utohexstr(Destination
) << " in " << *this << "\n";
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
))
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
);
1804 if (opts::StrictMode
&& !hasInternalReference()) {
1805 BC
.MIB
->convertJmpToTailCall(Instr
);
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
;
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)
1824 if (!opts::StrictMode
)
1827 if (BC
.MIB
->isTailCall(Instr
)) {
1828 BC
.MIB
->convertTailCallToJmp(Instr
);
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');
1847 addUnknownControlFlow(BB
);
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
);
1858 BC
.MIB
->convertJmpToTailCall(Instr
);
1859 BB
.removeAllSuccessors();
1863 if (opts::Verbosity
>= 2) {
1864 outs() << "BOLT-INFO: rejected potential indirect tail call in "
1865 << "function " << *this << " in basic block " << BB
.getName()
1867 LLVM_DEBUG(BC
.printInstructions(dbgs(), BB
.begin(), BB
.end(),
1868 BB
.getOffset(), this, true));
1871 if (!opts::StrictMode
)
1874 addUnknownControlFlow(BB
);
1878 if (HasInternalLabelReference
)
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 "
1889 BC
.MIB
->setJumpTable(*LastIndirectJump
, LastJT
, LastJTIndexReg
, AllocId
);
1890 HasUnknownControlFlow
= false;
1892 LastIndirectJumpBB
->updateJumpTableSuccessors();
1895 if (HasFixedIndirectBranch
)
1898 // Validate that all data references to function offsets are claimed by
1899 // recognized jump tables. Register externally referenced blocks as entry
1901 if (!opts::StrictMode
&& hasInternalReference()) {
1902 if (!validateExternallyReferencedOffsets())
1906 if (HasUnknownControlFlow
&& !BC
.HasRelocations
)
1912 void BinaryFunction::recomputeLandingPads() {
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
))
1926 const std::optional
<MCPlus::MCLandingPad
> EHInfo
=
1927 BC
.MIB
->getEHInfo(Instr
);
1928 if (!EHInfo
|| !EHInfo
->first
)
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
) {
1945 assert(!BC
.HasRelocations
&&
1946 "cannot process file with non-simple function in relocs mode");
1950 if (CurrentState
!= State::Disassembled
)
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
);
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(),
1996 if (!BC
.MIB
->isPseudo(*RII
) && !BC
.MIB
->isNoop(*RII
)) {
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();
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
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
);
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.
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
);
2073 CFIOffset
= NextInstr
->first
;
2075 CFIOffset
= getSize();
2077 // Note: this potentially invalidates instruction pointers/iterators.
2078 addCFIPlaceholders(CFIOffset
, InsertBB
);
2086 if (BasicBlocks
.empty()) {
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
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
) {
2106 errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2108 errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2109 BC
.exitWithBugReport("disassembly failed - inconsistent branch found.",
2113 FromBB
->addSuccessor(ToBB
);
2116 // Add fall-through branches.
2118 bool IsPrevFT
= false; // Is previous block a fall-through.
2119 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
2121 PrevBB
->addSuccessor(BB
);
2129 MCInst
*LastInstr
= BB
->getLastNonPseudoInstr();
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
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
);
2151 // Assign landing pads and throwers info.
2152 recomputeLandingPads();
2154 // Assign CFI information to each BB entry.
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.
2162 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
2163 Layout
.addBasicBlock(BB
);
2165 PrevBB
->setEndOffset(BB
->getOffset());
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 "
2191 // In relocation mode we want to keep processing the function but avoid
2196 clearList(ExternallyReferencedOffsets
);
2197 clearList(UnknownIndirectBranchOffsets
);
2202 void BinaryFunction::postProcessCFG() {
2203 if (isSimple() && !BasicBlocks
.empty()) {
2204 // Convert conditional tail call branches to conditional branches that jump
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())
2235 for (const BinaryBasicBlock
&BB
: blocks()) {
2236 auto II
= BB
.getMacroOpFusionPair();
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)
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
)
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();
2279 std::optional
<uint64_t> TargetAddressOrNone
=
2280 BC
.MIB
->getConditionalTailCall(*CTCInstr
);
2281 if (!TargetAddressOrNone
)
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(),
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()) {
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
)
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.
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
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
);
2397 switch (CFI
->getOperation()) {
2398 case MCCFIInstruction::OpRememberState
:
2399 StateStack
.push(EffectiveState
);
2400 EffectiveState
= State
;
2402 case MCCFIInstruction::OpRestoreState
:
2403 assert(!StateStack
.empty() && "corrupt CFI stack");
2404 EffectiveState
= StateStack
.top();
2407 case MCCFIInstruction::OpGnuArgsSize
:
2408 // OpGnuArgsSize CFIs do not affect the CFI state.
2411 // Any other CFI updates the state.
2412 EffectiveState
= State
;
2418 assert(StateStack
.empty() && "corrupt CFI stack");
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.
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
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();
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
;
2462 case MCCFIInstruction::OpDefCfaRegister
:
2463 CFAReg
= Instr
.getRegister();
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
)
2473 case MCCFIInstruction::OpDefCfaOffset
:
2474 CFAOffset
= Instr
.getOffset();
2477 case MCCFIInstruction::OpDefCfa
:
2478 CFAReg
= Instr
.getRegister();
2479 CFAOffset
= Instr
.getOffset();
2482 case MCCFIInstruction::OpEscape
: {
2483 std::optional
<uint8_t> Reg
=
2484 readDWARFExpressionTargetReg(Instr
.getValues());
2485 // Handle DW_CFA_def_cfa_expression
2487 CFARule
= RuleNumber
;
2490 RegRule
[*Reg
] = RuleNumber
;
2493 case MCCFIInstruction::OpAdjustCfaOffset
:
2494 case MCCFIInstruction::OpWindowSave
:
2495 case MCCFIInstruction::OpNegateRAState
:
2496 case MCCFIInstruction::OpLLVMDefAspaceCfa
:
2497 llvm_unreachable("unsupported CFI opcode");
2499 case MCCFIInstruction::OpRememberState
:
2500 case MCCFIInstruction::OpRestoreState
:
2501 case MCCFIInstruction::OpGnuArgsSize
:
2502 // do not affect CFI state
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
) {
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())
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?");
2533 /// Interpret all CIE and FDE instructions up until CFI State number and
2534 /// populate this snapshot
2536 const BinaryFunction::CFIInstrMapType
&CIE
,
2537 const BinaryFunction::CFIInstrMapType
&FDE
,
2538 const DenseMap
<int32_t, SmallVector
<int32_t, 4>> &FrameRestoreEquivalents
,
2540 : CIE(CIE
), FDE(FDE
), FrameRestoreEquivalents(FrameRestoreEquivalents
) {
2542 CFAOffset
= UNKNOWN
;
2546 for (int32_t I
= 0, E
= CIE
.size(); I
!= E
; ++I
) {
2547 const MCCFIInstruction
&Instr
= CIE
[I
];
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
) {}
2567 const BinaryFunction::CFIInstrMapType
&CIE
,
2568 const BinaryFunction::CFIInstrMapType
&FDE
,
2569 const DenseMap
<int32_t, SmallVector
<int32_t, 4>> &FrameRestoreEquivalents
,
2571 : CFISnapshot(CIE
, FDE
, FrameRestoreEquivalents
, State
) {}
2573 /// Return true if applying Instr to this state is redundant and can be
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
: {
2585 if (Instr
.getOperation() != MCCFIInstruction::OpEscape
) {
2586 Reg
= Instr
.getRegister();
2588 std::optional
<uint8_t> R
=
2589 readDWARFExpressionTargetReg(Instr
.getValues());
2590 // Handle DW_CFA_def_cfa_expression
2592 if (RestoredCFAReg
&& RestoredCFAOffset
)
2594 RestoredCFAReg
= true;
2595 RestoredCFAOffset
= true;
2600 if (RestoredRegs
[Reg
])
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
)
2610 const MCCFIInstruction
&LastDef
=
2611 CurRegRule
< 0 ? CIE
[-CurRegRule
] : FDE
[CurRegRule
];
2612 return LastDef
== Instr
;
2614 case MCCFIInstruction::OpDefCfaRegister
:
2617 RestoredCFAReg
= true;
2618 return CFAReg
== Instr
.getRegister();
2619 case MCCFIInstruction::OpDefCfaOffset
:
2620 if (RestoredCFAOffset
)
2622 RestoredCFAOffset
= true;
2623 return CFAOffset
== Instr
.getOffset();
2624 case MCCFIInstruction::OpDefCfa
:
2625 if (RestoredCFAReg
&& RestoredCFAOffset
)
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");
2636 case MCCFIInstruction::OpRememberState
:
2637 case MCCFIInstruction::OpRestoreState
:
2638 case MCCFIInstruction::OpGnuArgsSize
:
2639 // do not affect CFI state
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
)
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
]))
2675 InsertIt
= addCFIPseudo(InBB
, InsertIt
, State
);
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();
2700 NewStates
.push_back(FrameInstructions
.size() - 1);
2701 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size() - 1);
2703 } else if (ToCFITable
.CFARule
< 0) {
2704 if (FromCFITable
.isRedundant(CIEFrameInstructions
[-ToCFITable
.CFARule
]))
2706 NewStates
.push_back(FrameInstructions
.size());
2707 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size());
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
);
2718 auto undoState
= [&](const MCCFIInstruction
&Instr
) {
2719 switch (Instr
.getOperation()) {
2720 case MCCFIInstruction::OpRememberState
:
2721 case MCCFIInstruction::OpRestoreState
:
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
: {
2731 if (Instr
.getOperation() != MCCFIInstruction::OpEscape
) {
2732 Reg
= Instr
.getRegister();
2734 std::optional
<uint8_t> R
=
2735 readDWARFExpressionTargetReg(Instr
.getValues());
2736 // Handle DW_CFA_def_cfa_expression
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();
2751 NewStates
.push_back(FrameInstructions
.size() - 1);
2752 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size() - 1);
2756 const int32_t Rule
= ToCFITable
.RegRule
[Reg
];
2758 if (FromCFITable
.isRedundant(CIEFrameInstructions
[-Rule
]))
2760 NewStates
.push_back(FrameInstructions
.size());
2761 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size());
2763 FrameInstructions
.emplace_back(CIEFrameInstructions
[-Rule
]);
2766 if (FromCFITable
.isRedundant(FrameInstructions
[Rule
]))
2768 NewStates
.push_back(Rule
);
2769 InsertIt
= addCFIPseudo(InBB
, InsertIt
, Rule
);
2773 case MCCFIInstruction::OpDefCfaRegister
:
2774 case MCCFIInstruction::OpDefCfaOffset
:
2775 case MCCFIInstruction::OpDefCfa
:
2778 case MCCFIInstruction::OpAdjustCfaOffset
:
2779 case MCCFIInstruction::OpWindowSave
:
2780 case MCCFIInstruction::OpNegateRAState
:
2781 case MCCFIInstruction::OpLLVMDefAspaceCfa
:
2782 llvm_unreachable("unsupported CFI opcode");
2784 case MCCFIInstruction::OpGnuArgsSize
:
2785 // do not affect CFI state
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
) {
2797 auto Iter
= FrameRestoreEquivalents
.find(I
);
2798 if (Iter
== FrameRestoreEquivalents
.end())
2800 for (int32_t State
: Iter
->second
)
2801 undoState(FrameInstructions
[State
]);
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());
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
);
2833 bool BinaryFunction::finalizeCFIState() {
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
2839 const char *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.
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()))
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
);
2887 bool BinaryFunction::requiresAddressTranslation() const {
2888 return opts::EnableBAT
|| hasSDTMarker() || hasPseudoProbe();
2891 bool BinaryFunction::requiresAddressMap() const {
2895 return opts::UpdateDebugSections
|| isMultiEntry() ||
2896 requiresAddressTranslation();
2899 uint64_t BinaryFunction::getInstructionCount() const {
2901 for (const BinaryBasicBlock
&BB
: blocks())
2902 Count
+= BB
.getNumNonPseudos();
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
)
2916 BC
.UndefinedSymbols
.insert(EndLabel
);
2920 void BinaryFunction::setTrapOnEntry() {
2923 forEachEntryPoint([&](uint64_t Offset
, const MCSymbol
*Label
) -> bool {
2925 BC
.MIB
->createTrap(TrapInstr
);
2926 addInstruction(Offset
, std::move(TrapInstr
));
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
2938 assert(CurrentState
== State::Empty
&&
2939 "cannot ignore non-empty functions in current mode");
2946 // Clear CFG state too.
2950 for (BinaryBasicBlock
*BB
: BasicBlocks
)
2952 clearList(BasicBlocks
);
2954 for (BinaryBasicBlock
*BB
: DeletedBasicBlocks
)
2956 clearList(DeletedBasicBlocks
);
2961 CurrentState
= State::Empty
;
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()) {
2975 for (MCInst
&Inst
: *BB
) {
2977 for (MCOperand
&Operand
: Inst
) {
2978 if (!Operand
.isExpr()) {
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
))
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
;
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(
3007 MCSymbolRefExpr::create(ColdSymbol
, MCSymbolRefExpr::VK_None
,
3017 #define MAX_PATH 255
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
;
3039 static std::string
formatEscapes(const std::string
&Str
) {
3041 for (unsigned I
= 0; I
< Str
.size(); ++I
) {
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");
3080 OS
<< "\"" << BB
->getName() << "\" [";
3081 for (StringRef Attr
: Attrs
)
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
) {
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';
3101 // analyzeBranch is just used to get the names of the branch
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()) {
3116 if (Succ
== BB
->getConditionalSuccessor(true)) {
3117 Branch
= CondBranch
? std::string(BC
.InstPrinter
->getOpcodeName(
3118 CondBranch
->getOpcode()))
3120 } else if (Succ
== BB
->getConditionalSuccessor(false)) {
3121 Branch
= UncondBranch
? std::string(BC
.InstPrinter
->getOpcodeName(
3122 UncondBranch
->getOpcode()))
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
<< ")";
3144 for (BinaryBasicBlock
*LP
: BB
->landing_pads()) {
3145 OS
<< format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3146 BB
->getName().data(), LP
->getName().data());
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";
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))
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 {
3181 raw_fd_ostream
of(Filename
, EC
, sys::fs::OF_None
);
3183 if (opts::Verbosity
>= 1) {
3184 errs() << "BOLT-WARNING: " << EC
.message() << ", unable to open "
3185 << Filename
<< " for output.\n";
3192 bool BinaryFunction::validateCFG() const {
3193 // Skip the validation of CFG after it is finalized
3194 if (CurrentState
== State::CFG_Finalized
)
3198 for (BinaryBasicBlock
*BB
: BasicBlocks
)
3199 Valid
&= BB
->validateSuccessorInvariants();
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";
3214 for (const BinaryBasicBlock
*BB
: BasicBlocks
) {
3215 if (!validateBlock(BB
, "block"))
3217 for (const BinaryBasicBlock
*PredBB
: BB
->predecessors())
3218 if (!validateBlock(PredBB
, "predecessor"))
3220 for (const BinaryBasicBlock
*SuccBB
: BB
->successors())
3221 if (!validateBlock(SuccBB
, "successor"))
3223 for (const BinaryBasicBlock
*LP
: BB
->landing_pads())
3224 if (!validateBlock(LP
, "landing pad"))
3226 for (const BinaryBasicBlock
*Thrower
: BB
->throwers())
3227 if (!validateBlock(Thrower
, "thrower"))
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';
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';
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";
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";
3273 void BinaryFunction::fixBranches() {
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
))
3285 // We will create unconditional branch with correct destination if needed.
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.
3299 BB
->eraseInstruction(BB
->findInstruction(CondBranch
));
3300 if (BB
->getSuccessor() == NextBB
)
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();
3317 auto L
= BC
.scopeLock();
3318 MIB
->replaceBranchTarget(*CondBranch
, TSuccessor
->getLabel(), Ctx
);
3320 if (TSuccessor
== FSuccessor
)
3321 BB
->removeDuplicateConditionalSuccessor(CondBranch
);
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(),
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())
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
);
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
);
3383 void BinaryFunction::postProcessBranches() {
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())
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()) {
3408 dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3409 << BB
.getName() << " in function " << *this << '\n');
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');
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
);
3436 if (BinaryData
*EntryBD
= BC
.getBinaryDataAtAddress(EntryPointAddress
)) {
3437 EntrySymbol
= EntryBD
->getSymbol();
3439 EntrySymbol
= BC
.getOrCreateGlobalSymbol(
3440 EntryPointAddress
, Twine("__ENTRY_") + getOneName() + "@");
3442 SecondaryEntryPoints
[LocalSymbol
] = EntrySymbol
;
3444 BC
.setSymbolToFunctionMap(EntrySymbol
, this);
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())
3456 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(BB
);
3461 BC
.Ctx
->getOrCreateSymbol("__ENTRY_" + BB
.getLabel()->getName());
3463 SecondaryEntryPoints
[BB
.getLabel()] = EntrySymbol
;
3465 BC
.setSymbolToFunctionMap(EntrySymbol
, this);
3470 MCSymbol
*BinaryFunction::getSymbolForEntryID(uint64_t EntryID
) {
3474 if (!isMultiEntry())
3477 uint64_t NumEntries
= 0;
3479 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
3480 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(*BB
);
3483 if (NumEntries
== EntryID
)
3488 for (std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3489 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3492 if (NumEntries
== EntryID
)
3501 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol
*Symbol
) const {
3502 if (!isMultiEntry())
3505 for (const MCSymbol
*FunctionSymbol
: getSymbols())
3506 if (FunctionSymbol
== Symbol
)
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
);
3515 if (EntrySymbol
== Symbol
)
3520 for (const std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3521 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3524 if (EntrySymbol
== Symbol
)
3529 llvm_unreachable("symbol not found");
3532 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback
) const {
3533 bool Status
= Callback(0, getSymbol());
3534 if (!isMultiEntry())
3537 for (const std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3541 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3545 Status
= Callback(KV
.first
, EntrySymbol
);
3551 BinaryFunction::BasicBlockListType
BinaryFunction::dfs() const {
3552 BasicBlockListType DFS
;
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
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
))
3571 for (BinaryBasicBlock
&BB
: blocks())
3572 BB
.setLayoutIndex(BinaryBasicBlock::InvalidIndex
);
3574 while (!Stack
.empty()) {
3575 BinaryBasicBlock
*BB
= Stack
.top();
3578 if (BB
->getLayoutIndex() != BinaryBasicBlock::InvalidIndex
)
3581 BB
->setLayoutIndex(Index
++);
3584 for (BinaryBasicBlock
*SuccBB
: BB
->landing_pads()) {
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));
3599 Stack
.push(BB
->getConditionalSuccessor(false));
3600 Stack
.push(BB
->getConditionalSuccessor(true));
3603 for (BinaryBasicBlock
*SuccBB
: BB
->successors()) {
3612 size_t BinaryFunction::computeHash(bool UseDFS
,
3613 OperandHashFuncTy OperandHashFunc
) const {
3617 assert(hasCFG() && "function is expected to have CFG");
3619 SmallVector
<const BinaryBasicBlock
*, 0> Order
;
3621 llvm::copy(dfs(), std::back_inserter(Order
));
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
,
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();
3657 updateLayout(Start
, NumNewBlocks
);
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
,
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();
3687 updateLayout(*std::prev(RetIter
), NumNewBlocks
);
3690 updateCFIState(*std::prev(RetIter
), NumNewBlocks
);
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
3715 Begin
= BasicBlocks
.begin();
3716 End
= BasicBlocks
.begin() + NumNewBlocks
;
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
))
3734 uint64_t JTAddress
= BC
.MIB
->getJumpTable(Inst
);
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
3740 if (!JumpTables
.count(JTAddress
)) {
3741 JumpTables
.insert(JTAddress
);
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
))
3758 JumpTable
*JT
= getJumpTable(Inst
);
3761 auto Iter
= JumpTables
.find(JT
);
3762 if (Iter
== JumpTables
.end()) {
3763 JumpTables
.insert(JT
);
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
3771 const MCSymbol
*Target
;
3772 // In case we match if our first matcher, first instruction is the one to
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(
3782 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1) ||
3783 BaseReg1
!= BC
.MIB
->getNoRegister() || Scale
!= 8) {
3786 // Standard JT matching failed. Trying now:
3787 // movq "jt.2397/1"(,%rax,8), %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(
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
3804 // leaq DATAat0x402450(%rip), %r11
3805 // movslq (%r11,%rdx,4), %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(
3822 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1) ||
3823 Scale
!= 4 || BaseReg1
!= BaseReg2
|| Offset
!= 0 ||
3824 !PICBaseAddrMatcher
->match(
3826 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1)) {
3827 llvm_unreachable("Failed to extract jump table base");
3830 // Matched PIC, identify the instruction with the reference to the JT
3831 JTLoadInst
= LEAMatcher
->CurInst
;
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
))
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());
3866 assert(Patched
&& "Invalid entry to be replaced in jump table");
3870 BinaryBasicBlock
*BinaryFunction::splitEdge(BinaryBasicBlock
*From
,
3871 BinaryBasicBlock
*To
) {
3872 // Create intermediate BB
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();
3886 auto I
= From
->succ_begin();
3887 auto BI
= From
->branch_info_begin();
3888 for (; I
!= From
->succ_end(); ++I
) {
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);
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)
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();
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
))
3935 const MCSymbol
*CalleeSymbol
= BC
.MIB
->getTargetSymbol(*Last
);
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")
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")))
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
))
3962 // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3964 if (SymbolSize
== 0 && containsAddress(cantFail(Symbol
.getAddress())))
3967 if (cantFail(Symbol
.getType()) != SymbolRef::ST_Unknown
)
3970 if (cantFail(Symbol
.getFlags()) & SymbolRef::SF_Global
)
3976 void BinaryFunction::adjustExecutionCount(uint64_t Count
) {
3977 if (getKnownExecutionCount() == 0 || Count
== 0)
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
)
3996 for (BinaryBasicBlock
*BB
: DeletedBasicBlocks
)
4000 void BinaryFunction::calculateLoopInfo() {
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
) {
4014 while (!St
.empty()) {
4015 BinaryLoop
*L
= St
.top();
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
)
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
;
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
;
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
;
4070 void BinaryFunction::updateOutputValues(const BOLTLinker
&Linker
) {
4072 assert(!isInjected() && "injected function should be emitted");
4073 setOutputAddress(getAddress());
4074 setOutputSize(getSize());
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
);
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
);
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())
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())
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())
4138 // Output ranges should match the input if the body hasn't changed.
4139 if (!isSimple() && !BC
.HasRelocations
)
4142 // AArch64 may have functions that only contains a constant island (no code).
4143 if (getLayout().block_empty())
4146 for (FunctionFragment
&FF
: getLayout().fragments()) {
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
) {
4159 assert(FragmentBaseAddress
== FF
.getAddress());
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
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
);
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
);
4185 PrevBB
->setOutputEndAddress(PrevBB
->isSplit()
4186 ? FF
.getAddress() + FF
.getImageSize()
4187 : getOutputAddress() + getOutputSize());
4191 DebugAddressRangesVector
BinaryFunction::getOutputAddressRanges() const {
4192 DebugAddressRangesVector OutputRanges
;
4195 return OutputRanges
;
4198 return OutputRanges
;
4200 OutputRanges
.emplace_back(getOutputAddress(),
4201 getOutputAddress() + getOutputSize());
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());
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 {
4226 // If the function hasn't changed return the same address.
4230 if (Address
< getAddress())
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
);
4243 // Special case for address immediately past the end of the function.
4244 if (Offset
== getSize())
4245 return getOutputAddress() + getOutputSize();
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
;
4259 return OutputRanges
;
4261 // If the function hasn't changed return the same ranges.
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
)) {
4277 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4278 << *this << " : [0x" << Twine::utohexstr(Range
.LowPC
) << ", 0x"
4279 << Twine::utohexstr(Range
.HighPC
) << "]\n");
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());
4292 const BinaryBasicBlock
*BB
= BBI
->second
;
4293 if (InputOffset
< BB
->getOffset() || InputOffset
>= BB
->getEndOffset()) {
4295 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4296 << *this << " : [0x" << Twine::utohexstr(Range
.LowPC
)
4297 << ", 0x" << Twine::utohexstr(Range
.HighPC
) << "]\n");
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
);
4314 OutputRanges
.emplace_back(StartAddress
,
4315 std::max(StartAddress
, EndAddress
));
4317 PrevEndAddress
= OutputRanges
.back().HighPC
;
4320 InputOffset
= BB
->getEndOffset();
4322 } while (InputOffset
< InputEndOffset
);
4325 // Post-processing pass to sort and merge ranges.
4326 llvm::sort(OutputRanges
);
4327 DebugAddressRangesVector MergedRanges
;
4329 for (const DebugAddressRange
&Range
: OutputRanges
) {
4330 if (Range
.LowPC
<= PrevEndAddress
) {
4331 MergedRanges
.back().HighPC
=
4332 std::max(MergedRanges
.back().HighPC
, Range
.HighPC
);
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
);
4351 for (MCInst
&Inst
: *BB
) {
4352 constexpr uint32_t InvalidOffset
= std::numeric_limits
<uint32_t>::max();
4353 if (Offset
== BC
.MIB
->getOffsetWithDefault(Inst
, InvalidOffset
))
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
)
4366 llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4370 DebugLocationsVector
BinaryFunction::translateInputToOutputLocationList(
4371 const DebugLocationsVector
&InputLL
) const {
4372 DebugLocationsVector OutputLL
;
4377 // If the function hasn't changed - there's nothing to update.
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 "
4389 << *this << " : [0x" << Twine::utohexstr(Start
)
4390 << ", 0x" << Twine::utohexstr(End
) << "]\n");
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());
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 "
4404 << *this << " : [0x" << Twine::utohexstr(Start
)
4405 << ", 0x" << Twine::utohexstr(End
) << "]\n");
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
);
4421 OutputLL
.emplace_back(DebugLocationEntry
{
4422 StartAddress
, std::max(StartAddress
, EndAddress
), Entry
.Expr
});
4424 PrevEndAddress
= OutputLL
.back().HighPC
;
4425 PrevExpr
= &OutputLL
.back().Expr
;
4429 InputOffset
= BB
->getEndOffset();
4430 } while (InputOffset
< InputEndOffset
);
4433 // Sort and merge adjacent entries with identical location.
4435 OutputLL
, [](const DebugLocationEntry
&A
, const DebugLocationEntry
&B
) {
4436 return A
.LowPC
< B
.LowPC
;
4438 DebugLocationsVector MergedLL
;
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
);
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
;
4456 void BinaryFunction::printLoopInfo(raw_ostream
&OS
) const {
4457 if (!opts::shouldPrint(*this))
4460 OS
<< "Loop Info for Function \"" << *this << "\"";
4461 if (hasValidProfile())
4462 OS
<< " (count: " << getExecutionCount() << ")";
4465 std::stack
<BinaryLoop
*> St
;
4466 for (BinaryLoop
*L
: *BLI
)
4468 while (!St
.empty()) {
4469 BinaryLoop
*L
= St
.top();
4472 for (BinaryLoop
*Inner
: *L
)
4475 if (!hasValidProfile())
4478 OS
<< (L
->getLoopDepth() > 1 ? "Nested" : "Outer")
4479 << " loop header: " << L
->getHeader()->getName();
4481 OS
<< "Loop basic blocks: ";
4483 for (BinaryBasicBlock
*BB
: L
->blocks())
4484 OS
<< LS
<< BB
->getName();
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
)
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())
4508 BinaryBasicBlock
&BB
= **BasicBlocks
.begin();
4509 for (MCInst
&Inst
: BB
)
4510 if (!BC
.MIB
->hasAnnotation(Inst
, "AArch64Veneer"))
4513 for (auto I
= BasicBlocks
.begin() + 1, E
= BasicBlocks
.end(); I
!= E
; ++I
) {
4514 for (MCInst
&Inst
: **I
)
4515 if (!BC
.MIB
->isNoop(Inst
))
4522 void BinaryFunction::addRelocation(uint64_t Address
, MCSymbol
*Symbol
,
4523 uint64_t RelType
, uint64_t Addend
,
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
};