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