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