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