1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// 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 // Collect the sequence of machine instructions for a basic block. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/MachineBasicBlock.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/StringExtras.h" 16 #include "llvm/CodeGen/LiveIntervals.h" 17 #include "llvm/CodeGen/LivePhysRegs.h" 18 #include "llvm/CodeGen/LiveVariables.h" 19 #include "llvm/CodeGen/MachineDominators.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineInstrBuilder.h" 22 #include "llvm/CodeGen/MachineJumpTableInfo.h" 23 #include "llvm/CodeGen/MachineLoopInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/SlotIndexes.h" 26 #include "llvm/CodeGen/TargetInstrInfo.h" 27 #include "llvm/CodeGen/TargetLowering.h" 28 #include "llvm/CodeGen/TargetRegisterInfo.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/Config/llvm-config.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/DebugInfoMetadata.h" 33 #include "llvm/IR/ModuleSlotTracker.h" 34 #include "llvm/MC/MCAsmInfo.h" 35 #include "llvm/MC/MCContext.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetMachine.h" 39 #include <algorithm> 40 #include <cmath> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "codegen" 44 45 static cl::opt<bool> PrintSlotIndexes( 46 "print-slotindexes", 47 cl::desc("When printing machine IR, annotate instructions and blocks with " 48 "SlotIndexes when available"), 49 cl::init(true), cl::Hidden); 50 51 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B) 52 : BB(B), Number(-1), xParent(&MF) { 53 Insts.Parent = this; 54 if (B) 55 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight(); 56 } 57 58 MachineBasicBlock::~MachineBasicBlock() = default; 59 60 /// Return the MCSymbol for this basic block. 61 MCSymbol *MachineBasicBlock::getSymbol() const { 62 if (!CachedMCSymbol) { 63 const MachineFunction *MF = getParent(); 64 MCContext &Ctx = MF->getContext(); 65 66 // We emit a non-temporary symbol -- with a descriptive name -- if it begins 67 // a section (with basic block sections). Otherwise we fall back to use temp 68 // label. 69 if (MF->hasBBSections() && isBeginSection()) { 70 SmallString<5> Suffix; 71 if (SectionID == MBBSectionID::ColdSectionID) { 72 Suffix += ".cold"; 73 } else if (SectionID == MBBSectionID::ExceptionSectionID) { 74 Suffix += ".eh"; 75 } else { 76 // For symbols that represent basic block sections, we add ".__part." to 77 // allow tools like symbolizers to know that this represents a part of 78 // the original function. 79 Suffix = (Suffix + Twine(".__part.") + Twine(SectionID.Number)).str(); 80 } 81 CachedMCSymbol = Ctx.getOrCreateSymbol(MF->getName() + Suffix); 82 } else { 83 const StringRef Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); 84 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" + 85 Twine(MF->getFunctionNumber()) + 86 "_" + Twine(getNumber())); 87 } 88 } 89 return CachedMCSymbol; 90 } 91 92 MCSymbol *MachineBasicBlock::getEHCatchretSymbol() const { 93 if (!CachedEHCatchretMCSymbol) { 94 const MachineFunction *MF = getParent(); 95 SmallString<128> SymbolName; 96 raw_svector_ostream(SymbolName) 97 << "$ehgcr_" << MF->getFunctionNumber() << '_' << getNumber(); 98 CachedEHCatchretMCSymbol = MF->getContext().getOrCreateSymbol(SymbolName); 99 } 100 return CachedEHCatchretMCSymbol; 101 } 102 103 MCSymbol *MachineBasicBlock::getEndSymbol() const { 104 if (!CachedEndMCSymbol) { 105 const MachineFunction *MF = getParent(); 106 MCContext &Ctx = MF->getContext(); 107 auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); 108 CachedEndMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB_END" + 109 Twine(MF->getFunctionNumber()) + 110 "_" + Twine(getNumber())); 111 } 112 return CachedEndMCSymbol; 113 } 114 115 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) { 116 MBB.print(OS); 117 return OS; 118 } 119 120 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) { 121 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); }); 122 } 123 124 /// When an MBB is added to an MF, we need to update the parent pointer of the 125 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right 126 /// operand list for registers. 127 /// 128 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it 129 /// gets the next available unique MBB number. If it is removed from a 130 /// MachineFunction, it goes back to being #-1. 131 void ilist_callback_traits<MachineBasicBlock>::addNodeToList( 132 MachineBasicBlock *N) { 133 MachineFunction &MF = *N->getParent(); 134 N->Number = MF.addToMBBNumbering(N); 135 136 // Make sure the instructions have their operands in the reginfo lists. 137 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 138 for (MachineInstr &MI : N->instrs()) 139 MI.addRegOperandsToUseLists(RegInfo); 140 } 141 142 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList( 143 MachineBasicBlock *N) { 144 N->getParent()->removeFromMBBNumbering(N->Number); 145 N->Number = -1; 146 } 147 148 /// When we add an instruction to a basic block list, we update its parent 149 /// pointer and add its operands from reg use/def lists if appropriate. 150 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) { 151 assert(!N->getParent() && "machine instruction already in a basic block"); 152 N->setParent(Parent); 153 154 // Add the instruction's register operands to their corresponding 155 // use/def lists. 156 MachineFunction *MF = Parent->getParent(); 157 N->addRegOperandsToUseLists(MF->getRegInfo()); 158 MF->handleInsertion(*N); 159 } 160 161 /// When we remove an instruction from a basic block list, we update its parent 162 /// pointer and remove its operands from reg use/def lists if appropriate. 163 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) { 164 assert(N->getParent() && "machine instruction not in a basic block"); 165 166 // Remove from the use/def lists. 167 if (MachineFunction *MF = N->getMF()) { 168 MF->handleRemoval(*N); 169 N->removeRegOperandsFromUseLists(MF->getRegInfo()); 170 } 171 172 N->setParent(nullptr); 173 } 174 175 /// When moving a range of instructions from one MBB list to another, we need to 176 /// update the parent pointers and the use/def lists. 177 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList, 178 instr_iterator First, 179 instr_iterator Last) { 180 assert(Parent->getParent() == FromList.Parent->getParent() && 181 "cannot transfer MachineInstrs between MachineFunctions"); 182 183 // If it's within the same BB, there's nothing to do. 184 if (this == &FromList) 185 return; 186 187 assert(Parent != FromList.Parent && "Two lists have the same parent?"); 188 189 // If splicing between two blocks within the same function, just update the 190 // parent pointers. 191 for (; First != Last; ++First) 192 First->setParent(Parent); 193 } 194 195 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) { 196 assert(!MI->getParent() && "MI is still in a block!"); 197 Parent->getParent()->deleteMachineInstr(MI); 198 } 199 200 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() { 201 instr_iterator I = instr_begin(), E = instr_end(); 202 while (I != E && I->isPHI()) 203 ++I; 204 assert((I == E || !I->isInsideBundle()) && 205 "First non-phi MI cannot be inside a bundle!"); 206 return I; 207 } 208 209 MachineBasicBlock::iterator 210 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) { 211 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 212 213 iterator E = end(); 214 while (I != E && (I->isPHI() || I->isPosition() || 215 TII->isBasicBlockPrologue(*I))) 216 ++I; 217 // FIXME: This needs to change if we wish to bundle labels 218 // inside the bundle. 219 assert((I == E || !I->isInsideBundle()) && 220 "First non-phi / non-label instruction is inside a bundle!"); 221 return I; 222 } 223 224 MachineBasicBlock::iterator 225 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I, 226 bool SkipPseudoOp) { 227 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 228 229 iterator E = end(); 230 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() || 231 (SkipPseudoOp && I->isPseudoProbe()) || 232 TII->isBasicBlockPrologue(*I))) 233 ++I; 234 // FIXME: This needs to change if we wish to bundle labels / dbg_values 235 // inside the bundle. 236 assert((I == E || !I->isInsideBundle()) && 237 "First non-phi / non-label / non-debug " 238 "instruction is inside a bundle!"); 239 return I; 240 } 241 242 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { 243 iterator B = begin(), E = end(), I = E; 244 while (I != B && ((--I)->isTerminator() || I->isDebugInstr())) 245 ; /*noop */ 246 while (I != E && !I->isTerminator()) 247 ++I; 248 return I; 249 } 250 251 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() { 252 instr_iterator B = instr_begin(), E = instr_end(), I = E; 253 while (I != B && ((--I)->isTerminator() || I->isDebugInstr())) 254 ; /*noop */ 255 while (I != E && !I->isTerminator()) 256 ++I; 257 return I; 258 } 259 260 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminatorForward() { 261 return find_if(instrs(), [](auto &II) { return II.isTerminator(); }); 262 } 263 264 MachineBasicBlock::iterator 265 MachineBasicBlock::getFirstNonDebugInstr(bool SkipPseudoOp) { 266 // Skip over begin-of-block dbg_value instructions. 267 return skipDebugInstructionsForward(begin(), end(), SkipPseudoOp); 268 } 269 270 MachineBasicBlock::iterator 271 MachineBasicBlock::getLastNonDebugInstr(bool SkipPseudoOp) { 272 // Skip over end-of-block dbg_value instructions. 273 instr_iterator B = instr_begin(), I = instr_end(); 274 while (I != B) { 275 --I; 276 // Return instruction that starts a bundle. 277 if (I->isDebugInstr() || I->isInsideBundle()) 278 continue; 279 if (SkipPseudoOp && I->isPseudoProbe()) 280 continue; 281 return I; 282 } 283 // The block is all debug values. 284 return end(); 285 } 286 287 bool MachineBasicBlock::hasEHPadSuccessor() const { 288 for (const MachineBasicBlock *Succ : successors()) 289 if (Succ->isEHPad()) 290 return true; 291 return false; 292 } 293 294 bool MachineBasicBlock::isEntryBlock() const { 295 return getParent()->begin() == getIterator(); 296 } 297 298 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 299 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const { 300 print(dbgs()); 301 } 302 #endif 303 304 bool MachineBasicBlock::mayHaveInlineAsmBr() const { 305 for (const MachineBasicBlock *Succ : successors()) { 306 if (Succ->isInlineAsmBrIndirectTarget()) 307 return true; 308 } 309 return false; 310 } 311 312 bool MachineBasicBlock::isLegalToHoistInto() const { 313 if (isReturnBlock() || hasEHPadSuccessor() || mayHaveInlineAsmBr()) 314 return false; 315 return true; 316 } 317 318 StringRef MachineBasicBlock::getName() const { 319 if (const BasicBlock *LBB = getBasicBlock()) 320 return LBB->getName(); 321 else 322 return StringRef("", 0); 323 } 324 325 /// Return a hopefully unique identifier for this block. 326 std::string MachineBasicBlock::getFullName() const { 327 std::string Name; 328 if (getParent()) 329 Name = (getParent()->getName() + ":").str(); 330 if (getBasicBlock()) 331 Name += getBasicBlock()->getName(); 332 else 333 Name += ("BB" + Twine(getNumber())).str(); 334 return Name; 335 } 336 337 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes, 338 bool IsStandalone) const { 339 const MachineFunction *MF = getParent(); 340 if (!MF) { 341 OS << "Can't print out MachineBasicBlock because parent MachineFunction" 342 << " is null\n"; 343 return; 344 } 345 const Function &F = MF->getFunction(); 346 const Module *M = F.getParent(); 347 ModuleSlotTracker MST(M); 348 MST.incorporateFunction(F); 349 print(OS, MST, Indexes, IsStandalone); 350 } 351 352 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST, 353 const SlotIndexes *Indexes, 354 bool IsStandalone) const { 355 const MachineFunction *MF = getParent(); 356 if (!MF) { 357 OS << "Can't print out MachineBasicBlock because parent MachineFunction" 358 << " is null\n"; 359 return; 360 } 361 362 if (Indexes && PrintSlotIndexes) 363 OS << Indexes->getMBBStartIdx(this) << '\t'; 364 365 printName(OS, PrintNameIr | PrintNameAttributes, &MST); 366 OS << ":\n"; 367 368 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 369 const MachineRegisterInfo &MRI = MF->getRegInfo(); 370 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 371 bool HasLineAttributes = false; 372 373 // Print the preds of this block according to the CFG. 374 if (!pred_empty() && IsStandalone) { 375 if (Indexes) OS << '\t'; 376 // Don't indent(2), align with previous line attributes. 377 OS << "; predecessors: "; 378 ListSeparator LS; 379 for (auto *Pred : predecessors()) 380 OS << LS << printMBBReference(*Pred); 381 OS << '\n'; 382 HasLineAttributes = true; 383 } 384 385 if (!succ_empty()) { 386 if (Indexes) OS << '\t'; 387 // Print the successors 388 OS.indent(2) << "successors: "; 389 ListSeparator LS; 390 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) { 391 OS << LS << printMBBReference(**I); 392 if (!Probs.empty()) 393 OS << '(' 394 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator()) 395 << ')'; 396 } 397 if (!Probs.empty() && IsStandalone) { 398 // Print human readable probabilities as comments. 399 OS << "; "; 400 ListSeparator LS; 401 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) { 402 const BranchProbability &BP = getSuccProbability(I); 403 OS << LS << printMBBReference(**I) << '(' 404 << format("%.2f%%", 405 rint(((double)BP.getNumerator() / BP.getDenominator()) * 406 100.0 * 100.0) / 407 100.0) 408 << ')'; 409 } 410 } 411 412 OS << '\n'; 413 HasLineAttributes = true; 414 } 415 416 if (!livein_empty() && MRI.tracksLiveness()) { 417 if (Indexes) OS << '\t'; 418 OS.indent(2) << "liveins: "; 419 420 ListSeparator LS; 421 for (const auto &LI : liveins()) { 422 OS << LS << printReg(LI.PhysReg, TRI); 423 if (!LI.LaneMask.all()) 424 OS << ":0x" << PrintLaneMask(LI.LaneMask); 425 } 426 HasLineAttributes = true; 427 } 428 429 if (HasLineAttributes) 430 OS << '\n'; 431 432 bool IsInBundle = false; 433 for (const MachineInstr &MI : instrs()) { 434 if (Indexes && PrintSlotIndexes) { 435 if (Indexes->hasIndex(MI)) 436 OS << Indexes->getInstructionIndex(MI); 437 OS << '\t'; 438 } 439 440 if (IsInBundle && !MI.isInsideBundle()) { 441 OS.indent(2) << "}\n"; 442 IsInBundle = false; 443 } 444 445 OS.indent(IsInBundle ? 4 : 2); 446 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false, 447 /*AddNewLine=*/false, &TII); 448 449 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 450 OS << " {"; 451 IsInBundle = true; 452 } 453 OS << '\n'; 454 } 455 456 if (IsInBundle) 457 OS.indent(2) << "}\n"; 458 459 if (IrrLoopHeaderWeight && IsStandalone) { 460 if (Indexes) OS << '\t'; 461 OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight 462 << '\n'; 463 } 464 } 465 466 /// Print the basic block's name as: 467 /// 468 /// bb.{number}[.{ir-name}] [(attributes...)] 469 /// 470 /// The {ir-name} is only printed when the \ref PrintNameIr flag is passed 471 /// (which is the default). If the IR block has no name, it is identified 472 /// numerically using the attribute syntax as "(%ir-block.{ir-slot})". 473 /// 474 /// When the \ref PrintNameAttributes flag is passed, additional attributes 475 /// of the block are printed when set. 476 /// 477 /// \param printNameFlags Combination of \ref PrintNameFlag flags indicating 478 /// the parts to print. 479 /// \param moduleSlotTracker Optional ModuleSlotTracker. This method will 480 /// incorporate its own tracker when necessary to 481 /// determine the block's IR name. 482 void MachineBasicBlock::printName(raw_ostream &os, unsigned printNameFlags, 483 ModuleSlotTracker *moduleSlotTracker) const { 484 os << "bb." << getNumber(); 485 bool hasAttributes = false; 486 487 auto PrintBBRef = [&](const BasicBlock *bb) { 488 os << "%ir-block."; 489 if (bb->hasName()) { 490 os << bb->getName(); 491 } else { 492 int slot = -1; 493 494 if (moduleSlotTracker) { 495 slot = moduleSlotTracker->getLocalSlot(bb); 496 } else if (bb->getParent()) { 497 ModuleSlotTracker tmpTracker(bb->getModule(), false); 498 tmpTracker.incorporateFunction(*bb->getParent()); 499 slot = tmpTracker.getLocalSlot(bb); 500 } 501 502 if (slot == -1) 503 os << "<ir-block badref>"; 504 else 505 os << slot; 506 } 507 }; 508 509 if (printNameFlags & PrintNameIr) { 510 if (const auto *bb = getBasicBlock()) { 511 if (bb->hasName()) { 512 os << '.' << bb->getName(); 513 } else { 514 hasAttributes = true; 515 os << " ("; 516 PrintBBRef(bb); 517 } 518 } 519 } 520 521 if (printNameFlags & PrintNameAttributes) { 522 if (isMachineBlockAddressTaken()) { 523 os << (hasAttributes ? ", " : " ("); 524 os << "machine-block-address-taken"; 525 hasAttributes = true; 526 } 527 if (isIRBlockAddressTaken()) { 528 os << (hasAttributes ? ", " : " ("); 529 os << "ir-block-address-taken "; 530 PrintBBRef(getAddressTakenIRBlock()); 531 hasAttributes = true; 532 } 533 if (isEHPad()) { 534 os << (hasAttributes ? ", " : " ("); 535 os << "landing-pad"; 536 hasAttributes = true; 537 } 538 if (isInlineAsmBrIndirectTarget()) { 539 os << (hasAttributes ? ", " : " ("); 540 os << "inlineasm-br-indirect-target"; 541 hasAttributes = true; 542 } 543 if (isEHFuncletEntry()) { 544 os << (hasAttributes ? ", " : " ("); 545 os << "ehfunclet-entry"; 546 hasAttributes = true; 547 } 548 if (getAlignment() != Align(1)) { 549 os << (hasAttributes ? ", " : " ("); 550 os << "align " << getAlignment().value(); 551 hasAttributes = true; 552 } 553 if (getSectionID() != MBBSectionID(0)) { 554 os << (hasAttributes ? ", " : " ("); 555 os << "bbsections "; 556 switch (getSectionID().Type) { 557 case MBBSectionID::SectionType::Exception: 558 os << "Exception"; 559 break; 560 case MBBSectionID::SectionType::Cold: 561 os << "Cold"; 562 break; 563 default: 564 os << getSectionID().Number; 565 } 566 hasAttributes = true; 567 } 568 if (getBBID().has_value()) { 569 os << (hasAttributes ? ", " : " ("); 570 os << "bb_id " << *getBBID(); 571 hasAttributes = true; 572 } 573 if (CallFrameSize != 0) { 574 os << (hasAttributes ? ", " : " ("); 575 os << "call-frame-size " << CallFrameSize; 576 hasAttributes = true; 577 } 578 } 579 580 if (hasAttributes) 581 os << ')'; 582 } 583 584 void MachineBasicBlock::printAsOperand(raw_ostream &OS, 585 bool /*PrintType*/) const { 586 OS << '%'; 587 printName(OS, 0); 588 } 589 590 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) { 591 LiveInVector::iterator I = find_if( 592 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 593 if (I == LiveIns.end()) 594 return; 595 596 I->LaneMask &= ~LaneMask; 597 if (I->LaneMask.none()) 598 LiveIns.erase(I); 599 } 600 601 MachineBasicBlock::livein_iterator 602 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) { 603 // Get non-const version of iterator. 604 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin()); 605 return LiveIns.erase(LI); 606 } 607 608 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const { 609 livein_iterator I = find_if( 610 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 611 return I != livein_end() && (I->LaneMask & LaneMask).any(); 612 } 613 614 void MachineBasicBlock::sortUniqueLiveIns() { 615 llvm::sort(LiveIns, 616 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) { 617 return LI0.PhysReg < LI1.PhysReg; 618 }); 619 // Liveins are sorted by physreg now we can merge their lanemasks. 620 LiveInVector::const_iterator I = LiveIns.begin(); 621 LiveInVector::const_iterator J; 622 LiveInVector::iterator Out = LiveIns.begin(); 623 for (; I != LiveIns.end(); ++Out, I = J) { 624 MCRegister PhysReg = I->PhysReg; 625 LaneBitmask LaneMask = I->LaneMask; 626 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J) 627 LaneMask |= J->LaneMask; 628 Out->PhysReg = PhysReg; 629 Out->LaneMask = LaneMask; 630 } 631 LiveIns.erase(Out, LiveIns.end()); 632 } 633 634 Register 635 MachineBasicBlock::addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC) { 636 assert(getParent() && "MBB must be inserted in function"); 637 assert(Register::isPhysicalRegister(PhysReg) && "Expected physreg"); 638 assert(RC && "Register class is required"); 639 assert((isEHPad() || this == &getParent()->front()) && 640 "Only the entry block and landing pads can have physreg live ins"); 641 642 bool LiveIn = isLiveIn(PhysReg); 643 iterator I = SkipPHIsAndLabels(begin()), E = end(); 644 MachineRegisterInfo &MRI = getParent()->getRegInfo(); 645 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 646 647 // Look for an existing copy. 648 if (LiveIn) 649 for (;I != E && I->isCopy(); ++I) 650 if (I->getOperand(1).getReg() == PhysReg) { 651 Register VirtReg = I->getOperand(0).getReg(); 652 if (!MRI.constrainRegClass(VirtReg, RC)) 653 llvm_unreachable("Incompatible live-in register class."); 654 return VirtReg; 655 } 656 657 // No luck, create a virtual register. 658 Register VirtReg = MRI.createVirtualRegister(RC); 659 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg) 660 .addReg(PhysReg, RegState::Kill); 661 if (!LiveIn) 662 addLiveIn(PhysReg); 663 return VirtReg; 664 } 665 666 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) { 667 getParent()->splice(NewAfter->getIterator(), getIterator()); 668 } 669 670 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) { 671 getParent()->splice(++NewBefore->getIterator(), getIterator()); 672 } 673 674 static int findJumpTableIndex(const MachineBasicBlock &MBB) { 675 MachineBasicBlock::const_iterator TerminatorI = MBB.getFirstTerminator(); 676 if (TerminatorI == MBB.end()) 677 return -1; 678 const MachineInstr &Terminator = *TerminatorI; 679 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo(); 680 return TII->getJumpTableIndex(Terminator); 681 } 682 683 void MachineBasicBlock::updateTerminator( 684 MachineBasicBlock *PreviousLayoutSuccessor) { 685 LLVM_DEBUG(dbgs() << "Updating terminators on " << printMBBReference(*this) 686 << "\n"); 687 688 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 689 // A block with no successors has no concerns with fall-through edges. 690 if (this->succ_empty()) 691 return; 692 693 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 694 SmallVector<MachineOperand, 4> Cond; 695 DebugLoc DL = findBranchDebugLoc(); 696 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond); 697 (void) B; 698 assert(!B && "UpdateTerminators requires analyzable predecessors!"); 699 if (Cond.empty()) { 700 if (TBB) { 701 // The block has an unconditional branch. If its successor is now its 702 // layout successor, delete the branch. 703 if (isLayoutSuccessor(TBB)) 704 TII->removeBranch(*this); 705 } else { 706 // The block has an unconditional fallthrough, or the end of the block is 707 // unreachable. 708 709 // Unfortunately, whether the end of the block is unreachable is not 710 // immediately obvious; we must fall back to checking the successor list, 711 // and assuming that if the passed in block is in the succesor list and 712 // not an EHPad, it must be the intended target. 713 if (!PreviousLayoutSuccessor || !isSuccessor(PreviousLayoutSuccessor) || 714 PreviousLayoutSuccessor->isEHPad()) 715 return; 716 717 // If the unconditional successor block is not the current layout 718 // successor, insert a branch to jump to it. 719 if (!isLayoutSuccessor(PreviousLayoutSuccessor)) 720 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL); 721 } 722 return; 723 } 724 725 if (FBB) { 726 // The block has a non-fallthrough conditional branch. If one of its 727 // successors is its layout successor, rewrite it to a fallthrough 728 // conditional branch. 729 if (isLayoutSuccessor(TBB)) { 730 if (TII->reverseBranchCondition(Cond)) 731 return; 732 TII->removeBranch(*this); 733 TII->insertBranch(*this, FBB, nullptr, Cond, DL); 734 } else if (isLayoutSuccessor(FBB)) { 735 TII->removeBranch(*this); 736 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 737 } 738 return; 739 } 740 741 // We now know we're going to fallthrough to PreviousLayoutSuccessor. 742 assert(PreviousLayoutSuccessor); 743 assert(!PreviousLayoutSuccessor->isEHPad()); 744 assert(isSuccessor(PreviousLayoutSuccessor)); 745 746 if (PreviousLayoutSuccessor == TBB) { 747 // We had a fallthrough to the same basic block as the conditional jump 748 // targets. Remove the conditional jump, leaving an unconditional 749 // fallthrough or an unconditional jump. 750 TII->removeBranch(*this); 751 if (!isLayoutSuccessor(TBB)) { 752 Cond.clear(); 753 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 754 } 755 return; 756 } 757 758 // The block has a fallthrough conditional branch. 759 if (isLayoutSuccessor(TBB)) { 760 if (TII->reverseBranchCondition(Cond)) { 761 // We can't reverse the condition, add an unconditional branch. 762 Cond.clear(); 763 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL); 764 return; 765 } 766 TII->removeBranch(*this); 767 TII->insertBranch(*this, PreviousLayoutSuccessor, nullptr, Cond, DL); 768 } else if (!isLayoutSuccessor(PreviousLayoutSuccessor)) { 769 TII->removeBranch(*this); 770 TII->insertBranch(*this, TBB, PreviousLayoutSuccessor, Cond, DL); 771 } 772 } 773 774 void MachineBasicBlock::validateSuccProbs() const { 775 #ifndef NDEBUG 776 int64_t Sum = 0; 777 for (auto Prob : Probs) 778 Sum += Prob.getNumerator(); 779 // Due to precision issue, we assume that the sum of probabilities is one if 780 // the difference between the sum of their numerators and the denominator is 781 // no greater than the number of successors. 782 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <= 783 Probs.size() && 784 "The sum of successors's probabilities exceeds one."); 785 #endif // NDEBUG 786 } 787 788 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ, 789 BranchProbability Prob) { 790 // Probability list is either empty (if successor list isn't empty, this means 791 // disabled optimization) or has the same size as successor list. 792 if (!(Probs.empty() && !Successors.empty())) 793 Probs.push_back(Prob); 794 Successors.push_back(Succ); 795 Succ->addPredecessor(this); 796 } 797 798 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) { 799 // We need to make sure probability list is either empty or has the same size 800 // of successor list. When this function is called, we can safely delete all 801 // probability in the list. 802 Probs.clear(); 803 Successors.push_back(Succ); 804 Succ->addPredecessor(this); 805 } 806 807 void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old, 808 MachineBasicBlock *New, 809 bool NormalizeSuccProbs) { 810 succ_iterator OldI = llvm::find(successors(), Old); 811 assert(OldI != succ_end() && "Old is not a successor of this block!"); 812 assert(!llvm::is_contained(successors(), New) && 813 "New is already a successor of this block!"); 814 815 // Add a new successor with equal probability as the original one. Note 816 // that we directly copy the probability using the iterator rather than 817 // getting a potentially synthetic probability computed when unknown. This 818 // preserves the probabilities as-is and then we can renormalize them and 819 // query them effectively afterward. 820 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown() 821 : *getProbabilityIterator(OldI)); 822 if (NormalizeSuccProbs) 823 normalizeSuccProbs(); 824 } 825 826 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ, 827 bool NormalizeSuccProbs) { 828 succ_iterator I = find(Successors, Succ); 829 removeSuccessor(I, NormalizeSuccProbs); 830 } 831 832 MachineBasicBlock::succ_iterator 833 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) { 834 assert(I != Successors.end() && "Not a current successor!"); 835 836 // If probability list is empty it means we don't use it (disabled 837 // optimization). 838 if (!Probs.empty()) { 839 probability_iterator WI = getProbabilityIterator(I); 840 Probs.erase(WI); 841 if (NormalizeSuccProbs) 842 normalizeSuccProbs(); 843 } 844 845 (*I)->removePredecessor(this); 846 return Successors.erase(I); 847 } 848 849 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old, 850 MachineBasicBlock *New) { 851 if (Old == New) 852 return; 853 854 succ_iterator E = succ_end(); 855 succ_iterator NewI = E; 856 succ_iterator OldI = E; 857 for (succ_iterator I = succ_begin(); I != E; ++I) { 858 if (*I == Old) { 859 OldI = I; 860 if (NewI != E) 861 break; 862 } 863 if (*I == New) { 864 NewI = I; 865 if (OldI != E) 866 break; 867 } 868 } 869 assert(OldI != E && "Old is not a successor of this block"); 870 871 // If New isn't already a successor, let it take Old's place. 872 if (NewI == E) { 873 Old->removePredecessor(this); 874 New->addPredecessor(this); 875 *OldI = New; 876 return; 877 } 878 879 // New is already a successor. 880 // Update its probability instead of adding a duplicate edge. 881 if (!Probs.empty()) { 882 auto ProbIter = getProbabilityIterator(NewI); 883 if (!ProbIter->isUnknown()) 884 *ProbIter += *getProbabilityIterator(OldI); 885 } 886 removeSuccessor(OldI); 887 } 888 889 void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig, 890 succ_iterator I) { 891 if (!Orig->Probs.empty()) 892 addSuccessor(*I, Orig->getSuccProbability(I)); 893 else 894 addSuccessorWithoutProb(*I); 895 } 896 897 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) { 898 Predecessors.push_back(Pred); 899 } 900 901 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) { 902 pred_iterator I = find(Predecessors, Pred); 903 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); 904 Predecessors.erase(I); 905 } 906 907 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) { 908 if (this == FromMBB) 909 return; 910 911 while (!FromMBB->succ_empty()) { 912 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 913 914 // If probability list is empty it means we don't use it (disabled 915 // optimization). 916 if (!FromMBB->Probs.empty()) { 917 auto Prob = *FromMBB->Probs.begin(); 918 addSuccessor(Succ, Prob); 919 } else 920 addSuccessorWithoutProb(Succ); 921 922 FromMBB->removeSuccessor(Succ); 923 } 924 } 925 926 void 927 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) { 928 if (this == FromMBB) 929 return; 930 931 while (!FromMBB->succ_empty()) { 932 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 933 if (!FromMBB->Probs.empty()) { 934 auto Prob = *FromMBB->Probs.begin(); 935 addSuccessor(Succ, Prob); 936 } else 937 addSuccessorWithoutProb(Succ); 938 FromMBB->removeSuccessor(Succ); 939 940 // Fix up any PHI nodes in the successor. 941 Succ->replacePhiUsesWith(FromMBB, this); 942 } 943 normalizeSuccProbs(); 944 } 945 946 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const { 947 return is_contained(predecessors(), MBB); 948 } 949 950 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const { 951 return is_contained(successors(), MBB); 952 } 953 954 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const { 955 MachineFunction::const_iterator I(this); 956 return std::next(I) == MachineFunction::const_iterator(MBB); 957 } 958 959 const MachineBasicBlock *MachineBasicBlock::getSingleSuccessor() const { 960 return Successors.size() == 1 ? Successors[0] : nullptr; 961 } 962 963 const MachineBasicBlock *MachineBasicBlock::getSinglePredecessor() const { 964 return Predecessors.size() == 1 ? Predecessors[0] : nullptr; 965 } 966 967 MachineBasicBlock *MachineBasicBlock::getFallThrough(bool JumpToFallThrough) { 968 MachineFunction::iterator Fallthrough = getIterator(); 969 ++Fallthrough; 970 // If FallthroughBlock is off the end of the function, it can't fall through. 971 if (Fallthrough == getParent()->end()) 972 return nullptr; 973 974 // If FallthroughBlock isn't a successor, no fallthrough is possible. 975 if (!isSuccessor(&*Fallthrough)) 976 return nullptr; 977 978 // Analyze the branches, if any, at the end of the block. 979 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 980 SmallVector<MachineOperand, 4> Cond; 981 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 982 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) { 983 // If we couldn't analyze the branch, examine the last instruction. 984 // If the block doesn't end in a known control barrier, assume fallthrough 985 // is possible. The isPredicated check is needed because this code can be 986 // called during IfConversion, where an instruction which is normally a 987 // Barrier is predicated and thus no longer an actual control barrier. 988 return (empty() || !back().isBarrier() || TII->isPredicated(back())) 989 ? &*Fallthrough 990 : nullptr; 991 } 992 993 // If there is no branch, control always falls through. 994 if (!TBB) return &*Fallthrough; 995 996 // If there is some explicit branch to the fallthrough block, it can obviously 997 // reach, even though the branch should get folded to fall through implicitly. 998 if (JumpToFallThrough && (MachineFunction::iterator(TBB) == Fallthrough || 999 MachineFunction::iterator(FBB) == Fallthrough)) 1000 return &*Fallthrough; 1001 1002 // If it's an unconditional branch to some block not the fall through, it 1003 // doesn't fall through. 1004 if (Cond.empty()) return nullptr; 1005 1006 // Otherwise, if it is conditional and has no explicit false block, it falls 1007 // through. 1008 return (FBB == nullptr) ? &*Fallthrough : nullptr; 1009 } 1010 1011 bool MachineBasicBlock::canFallThrough() { 1012 return getFallThrough() != nullptr; 1013 } 1014 1015 MachineBasicBlock *MachineBasicBlock::splitAt(MachineInstr &MI, 1016 bool UpdateLiveIns, 1017 LiveIntervals *LIS) { 1018 MachineBasicBlock::iterator SplitPoint(&MI); 1019 ++SplitPoint; 1020 1021 if (SplitPoint == end()) { 1022 // Don't bother with a new block. 1023 return this; 1024 } 1025 1026 MachineFunction *MF = getParent(); 1027 1028 LivePhysRegs LiveRegs; 1029 if (UpdateLiveIns) { 1030 // Make sure we add any physregs we define in the block as liveins to the 1031 // new block. 1032 MachineBasicBlock::iterator Prev(&MI); 1033 LiveRegs.init(*MF->getSubtarget().getRegisterInfo()); 1034 LiveRegs.addLiveOuts(*this); 1035 for (auto I = rbegin(), E = Prev.getReverse(); I != E; ++I) 1036 LiveRegs.stepBackward(*I); 1037 } 1038 1039 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock()); 1040 1041 MF->insert(++MachineFunction::iterator(this), SplitBB); 1042 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end()); 1043 1044 SplitBB->transferSuccessorsAndUpdatePHIs(this); 1045 addSuccessor(SplitBB); 1046 1047 if (UpdateLiveIns) 1048 addLiveIns(*SplitBB, LiveRegs); 1049 1050 if (LIS) 1051 LIS->insertMBBInMaps(SplitBB); 1052 1053 return SplitBB; 1054 } 1055 1056 // Returns `true` if there are possibly other users of the jump table at 1057 // `JumpTableIndex` except for the ones in `IgnoreMBB`. 1058 static bool jumpTableHasOtherUses(const MachineFunction &MF, 1059 const MachineBasicBlock &IgnoreMBB, 1060 int JumpTableIndex) { 1061 assert(JumpTableIndex >= 0 && "need valid index"); 1062 const MachineJumpTableInfo &MJTI = *MF.getJumpTableInfo(); 1063 const MachineJumpTableEntry &MJTE = MJTI.getJumpTables()[JumpTableIndex]; 1064 // Take any basic block from the table; every user of the jump table must 1065 // show up in the predecessor list. 1066 const MachineBasicBlock *MBB = nullptr; 1067 for (MachineBasicBlock *B : MJTE.MBBs) { 1068 if (B != nullptr) { 1069 MBB = B; 1070 break; 1071 } 1072 } 1073 if (MBB == nullptr) 1074 return true; // can't rule out other users if there isn't any block. 1075 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1076 SmallVector<MachineOperand, 4> Cond; 1077 for (MachineBasicBlock *Pred : MBB->predecessors()) { 1078 if (Pred == &IgnoreMBB) 1079 continue; 1080 MachineBasicBlock *DummyT = nullptr; 1081 MachineBasicBlock *DummyF = nullptr; 1082 Cond.clear(); 1083 if (!TII.analyzeBranch(*Pred, DummyT, DummyF, Cond, 1084 /*AllowModify=*/false)) { 1085 // analyzable direct jump 1086 continue; 1087 } 1088 int PredJTI = findJumpTableIndex(*Pred); 1089 if (PredJTI >= 0) { 1090 if (PredJTI == JumpTableIndex) 1091 return true; 1092 continue; 1093 } 1094 // Be conservative for unanalyzable jumps. 1095 return true; 1096 } 1097 return false; 1098 } 1099 1100 class SlotIndexUpdateDelegate : public MachineFunction::Delegate { 1101 private: 1102 MachineFunction &MF; 1103 SlotIndexes *Indexes; 1104 SmallSetVector<MachineInstr *, 2> Insertions; 1105 1106 public: 1107 SlotIndexUpdateDelegate(MachineFunction &MF, SlotIndexes *Indexes) 1108 : MF(MF), Indexes(Indexes) { 1109 MF.setDelegate(this); 1110 } 1111 1112 ~SlotIndexUpdateDelegate() { 1113 MF.resetDelegate(this); 1114 for (auto MI : Insertions) 1115 Indexes->insertMachineInstrInMaps(*MI); 1116 } 1117 1118 void MF_HandleInsertion(MachineInstr &MI) override { 1119 // This is called before MI is inserted into block so defer index update. 1120 if (Indexes) 1121 Insertions.insert(&MI); 1122 } 1123 1124 void MF_HandleRemoval(MachineInstr &MI) override { 1125 if (Indexes && !Insertions.remove(&MI)) 1126 Indexes->removeMachineInstrFromMaps(MI); 1127 } 1128 }; 1129 1130 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge( 1131 MachineBasicBlock *Succ, Pass &P, 1132 std::vector<SparseBitVector<>> *LiveInSets) { 1133 if (!canSplitCriticalEdge(Succ)) 1134 return nullptr; 1135 1136 MachineFunction *MF = getParent(); 1137 MachineBasicBlock *PrevFallthrough = getNextNode(); 1138 DebugLoc DL; // FIXME: this is nowhere 1139 1140 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(); 1141 NMBB->setCallFrameSize(Succ->getCallFrameSize()); 1142 1143 // Is there an indirect jump with jump table? 1144 bool ChangedIndirectJump = false; 1145 int JTI = findJumpTableIndex(*this); 1146 if (JTI >= 0) { 1147 MachineJumpTableInfo &MJTI = *MF->getJumpTableInfo(); 1148 MJTI.ReplaceMBBInJumpTable(JTI, Succ, NMBB); 1149 ChangedIndirectJump = true; 1150 } 1151 1152 MF->insert(std::next(MachineFunction::iterator(this)), NMBB); 1153 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this) 1154 << " -- " << printMBBReference(*NMBB) << " -- " 1155 << printMBBReference(*Succ) << '\n'); 1156 1157 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>(); 1158 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>(); 1159 if (LIS) 1160 LIS->insertMBBInMaps(NMBB); 1161 else if (Indexes) 1162 Indexes->insertMBBInMaps(NMBB); 1163 1164 // On some targets like Mips, branches may kill virtual registers. Make sure 1165 // that LiveVariables is properly updated after updateTerminator replaces the 1166 // terminators. 1167 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>(); 1168 1169 // Collect a list of virtual registers killed by the terminators. 1170 SmallVector<Register, 4> KilledRegs; 1171 if (LV) 1172 for (MachineInstr &MI : 1173 llvm::make_range(getFirstInstrTerminator(), instr_end())) { 1174 for (MachineOperand &MO : MI.all_uses()) { 1175 if (MO.getReg() == 0 || !MO.isKill() || MO.isUndef()) 1176 continue; 1177 Register Reg = MO.getReg(); 1178 if (Reg.isPhysical() || LV->getVarInfo(Reg).removeKill(MI)) { 1179 KilledRegs.push_back(Reg); 1180 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << MI); 1181 MO.setIsKill(false); 1182 } 1183 } 1184 } 1185 1186 SmallVector<Register, 4> UsedRegs; 1187 if (LIS) { 1188 for (MachineInstr &MI : 1189 llvm::make_range(getFirstInstrTerminator(), instr_end())) { 1190 for (const MachineOperand &MO : MI.operands()) { 1191 if (!MO.isReg() || MO.getReg() == 0) 1192 continue; 1193 1194 Register Reg = MO.getReg(); 1195 if (!is_contained(UsedRegs, Reg)) 1196 UsedRegs.push_back(Reg); 1197 } 1198 } 1199 } 1200 1201 ReplaceUsesOfBlockWith(Succ, NMBB); 1202 1203 // Since we replaced all uses of Succ with NMBB, that should also be treated 1204 // as the fallthrough successor 1205 if (Succ == PrevFallthrough) 1206 PrevFallthrough = NMBB; 1207 1208 if (!ChangedIndirectJump) { 1209 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes); 1210 updateTerminator(PrevFallthrough); 1211 } 1212 1213 // Insert unconditional "jump Succ" instruction in NMBB if necessary. 1214 NMBB->addSuccessor(Succ); 1215 if (!NMBB->isLayoutSuccessor(Succ)) { 1216 SlotIndexUpdateDelegate SlotUpdater(*MF, Indexes); 1217 SmallVector<MachineOperand, 4> Cond; 1218 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 1219 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL); 1220 } 1221 1222 // Fix PHI nodes in Succ so they refer to NMBB instead of this. 1223 Succ->replacePhiUsesWith(this, NMBB); 1224 1225 // Inherit live-ins from the successor 1226 for (const auto &LI : Succ->liveins()) 1227 NMBB->addLiveIn(LI); 1228 1229 // Update LiveVariables. 1230 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1231 if (LV) { 1232 // Restore kills of virtual registers that were killed by the terminators. 1233 while (!KilledRegs.empty()) { 1234 Register Reg = KilledRegs.pop_back_val(); 1235 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) { 1236 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false)) 1237 continue; 1238 if (Reg.isVirtual()) 1239 LV->getVarInfo(Reg).Kills.push_back(&*I); 1240 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I); 1241 break; 1242 } 1243 } 1244 // Update relevant live-through information. 1245 if (LiveInSets != nullptr) 1246 LV->addNewBlock(NMBB, this, Succ, *LiveInSets); 1247 else 1248 LV->addNewBlock(NMBB, this, Succ); 1249 } 1250 1251 if (LIS) { 1252 // After splitting the edge and updating SlotIndexes, live intervals may be 1253 // in one of two situations, depending on whether this block was the last in 1254 // the function. If the original block was the last in the function, all 1255 // live intervals will end prior to the beginning of the new split block. If 1256 // the original block was not at the end of the function, all live intervals 1257 // will extend to the end of the new split block. 1258 1259 bool isLastMBB = 1260 std::next(MachineFunction::iterator(NMBB)) == getParent()->end(); 1261 1262 SlotIndex StartIndex = Indexes->getMBBEndIdx(this); 1263 SlotIndex PrevIndex = StartIndex.getPrevSlot(); 1264 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB); 1265 1266 // Find the registers used from NMBB in PHIs in Succ. 1267 SmallSet<Register, 8> PHISrcRegs; 1268 for (MachineBasicBlock::instr_iterator 1269 I = Succ->instr_begin(), E = Succ->instr_end(); 1270 I != E && I->isPHI(); ++I) { 1271 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) { 1272 if (I->getOperand(ni+1).getMBB() == NMBB) { 1273 MachineOperand &MO = I->getOperand(ni); 1274 Register Reg = MO.getReg(); 1275 PHISrcRegs.insert(Reg); 1276 if (MO.isUndef()) 1277 continue; 1278 1279 LiveInterval &LI = LIS->getInterval(Reg); 1280 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1281 assert(VNI && 1282 "PHI sources should be live out of their predecessors."); 1283 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1284 } 1285 } 1286 } 1287 1288 MachineRegisterInfo *MRI = &getParent()->getRegInfo(); 1289 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1290 Register Reg = Register::index2VirtReg(i); 1291 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg)) 1292 continue; 1293 1294 LiveInterval &LI = LIS->getInterval(Reg); 1295 if (!LI.liveAt(PrevIndex)) 1296 continue; 1297 1298 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ)); 1299 if (isLiveOut && isLastMBB) { 1300 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1301 assert(VNI && "LiveInterval should have VNInfo where it is live."); 1302 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1303 } else if (!isLiveOut && !isLastMBB) { 1304 LI.removeSegment(StartIndex, EndIndex); 1305 } 1306 } 1307 1308 // Update all intervals for registers whose uses may have been modified by 1309 // updateTerminator(). 1310 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs); 1311 } 1312 1313 if (MachineDominatorTree *MDT = 1314 P.getAnalysisIfAvailable<MachineDominatorTree>()) 1315 MDT->recordSplitCriticalEdge(this, Succ, NMBB); 1316 1317 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>()) 1318 if (MachineLoop *TIL = MLI->getLoopFor(this)) { 1319 // If one or the other blocks were not in a loop, the new block is not 1320 // either, and thus LI doesn't need to be updated. 1321 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) { 1322 if (TIL == DestLoop) { 1323 // Both in the same loop, the NMBB joins loop. 1324 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1325 } else if (TIL->contains(DestLoop)) { 1326 // Edge from an outer loop to an inner loop. Add to the outer loop. 1327 TIL->addBasicBlockToLoop(NMBB, MLI->getBase()); 1328 } else if (DestLoop->contains(TIL)) { 1329 // Edge from an inner loop to an outer loop. Add to the outer loop. 1330 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1331 } else { 1332 // Edge from two loops with no containment relation. Because these 1333 // are natural loops, we know that the destination block must be the 1334 // header of its loop (adding a branch into a loop elsewhere would 1335 // create an irreducible loop). 1336 assert(DestLoop->getHeader() == Succ && 1337 "Should not create irreducible loops!"); 1338 if (MachineLoop *P = DestLoop->getParentLoop()) 1339 P->addBasicBlockToLoop(NMBB, MLI->getBase()); 1340 } 1341 } 1342 } 1343 1344 return NMBB; 1345 } 1346 1347 bool MachineBasicBlock::canSplitCriticalEdge( 1348 const MachineBasicBlock *Succ) const { 1349 // Splitting the critical edge to a landing pad block is non-trivial. Don't do 1350 // it in this generic function. 1351 if (Succ->isEHPad()) 1352 return false; 1353 1354 // Splitting the critical edge to a callbr's indirect block isn't advised. 1355 // Don't do it in this generic function. 1356 if (Succ->isInlineAsmBrIndirectTarget()) 1357 return false; 1358 1359 const MachineFunction *MF = getParent(); 1360 // Performance might be harmed on HW that implements branching using exec mask 1361 // where both sides of the branches are always executed. 1362 if (MF->getTarget().requiresStructuredCFG()) 1363 return false; 1364 1365 // Do we have an Indirect jump with a jumptable that we can rewrite? 1366 int JTI = findJumpTableIndex(*this); 1367 if (JTI >= 0 && !jumpTableHasOtherUses(*MF, *this, JTI)) 1368 return true; 1369 1370 // We may need to update this's terminator, but we can't do that if 1371 // analyzeBranch fails. 1372 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1373 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1374 SmallVector<MachineOperand, 4> Cond; 1375 // AnalyzeBanch should modify this, since we did not allow modification. 1376 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond, 1377 /*AllowModify*/ false)) 1378 return false; 1379 1380 // Avoid bugpoint weirdness: A block may end with a conditional branch but 1381 // jumps to the same MBB is either case. We have duplicate CFG edges in that 1382 // case that we can't handle. Since this never happens in properly optimized 1383 // code, just skip those edges. 1384 if (TBB && TBB == FBB) { 1385 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate " 1386 << printMBBReference(*this) << '\n'); 1387 return false; 1388 } 1389 return true; 1390 } 1391 1392 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's 1393 /// neighboring instructions so the bundle won't be broken by removing MI. 1394 static void unbundleSingleMI(MachineInstr *MI) { 1395 // Removing the first instruction in a bundle. 1396 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) 1397 MI->unbundleFromSucc(); 1398 // Removing the last instruction in a bundle. 1399 if (MI->isBundledWithPred() && !MI->isBundledWithSucc()) 1400 MI->unbundleFromPred(); 1401 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags 1402 // are already fine. 1403 } 1404 1405 MachineBasicBlock::instr_iterator 1406 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) { 1407 unbundleSingleMI(&*I); 1408 return Insts.erase(I); 1409 } 1410 1411 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) { 1412 unbundleSingleMI(MI); 1413 MI->clearFlag(MachineInstr::BundledPred); 1414 MI->clearFlag(MachineInstr::BundledSucc); 1415 return Insts.remove(MI); 1416 } 1417 1418 MachineBasicBlock::instr_iterator 1419 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) { 1420 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() && 1421 "Cannot insert instruction with bundle flags"); 1422 // Set the bundle flags when inserting inside a bundle. 1423 if (I != instr_end() && I->isBundledWithPred()) { 1424 MI->setFlag(MachineInstr::BundledPred); 1425 MI->setFlag(MachineInstr::BundledSucc); 1426 } 1427 return Insts.insert(I, MI); 1428 } 1429 1430 /// This method unlinks 'this' from the containing function, and returns it, but 1431 /// does not delete it. 1432 MachineBasicBlock *MachineBasicBlock::removeFromParent() { 1433 assert(getParent() && "Not embedded in a function!"); 1434 getParent()->remove(this); 1435 return this; 1436 } 1437 1438 /// This method unlinks 'this' from the containing function, and deletes it. 1439 void MachineBasicBlock::eraseFromParent() { 1440 assert(getParent() && "Not embedded in a function!"); 1441 getParent()->erase(this); 1442 } 1443 1444 /// Given a machine basic block that branched to 'Old', change the code and CFG 1445 /// so that it branches to 'New' instead. 1446 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old, 1447 MachineBasicBlock *New) { 1448 assert(Old != New && "Cannot replace self with self!"); 1449 1450 MachineBasicBlock::instr_iterator I = instr_end(); 1451 while (I != instr_begin()) { 1452 --I; 1453 if (!I->isTerminator()) break; 1454 1455 // Scan the operands of this machine instruction, replacing any uses of Old 1456 // with New. 1457 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1458 if (I->getOperand(i).isMBB() && 1459 I->getOperand(i).getMBB() == Old) 1460 I->getOperand(i).setMBB(New); 1461 } 1462 1463 // Update the successor information. 1464 replaceSuccessor(Old, New); 1465 } 1466 1467 void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old, 1468 MachineBasicBlock *New) { 1469 for (MachineInstr &MI : phis()) 1470 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) { 1471 MachineOperand &MO = MI.getOperand(i); 1472 if (MO.getMBB() == Old) 1473 MO.setMBB(New); 1474 } 1475 } 1476 1477 /// Find the next valid DebugLoc starting at MBBI, skipping any debug 1478 /// instructions. Return UnknownLoc if there is none. 1479 DebugLoc 1480 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) { 1481 // Skip debug declarations, we don't want a DebugLoc from them. 1482 MBBI = skipDebugInstructionsForward(MBBI, instr_end()); 1483 if (MBBI != instr_end()) 1484 return MBBI->getDebugLoc(); 1485 return {}; 1486 } 1487 1488 DebugLoc MachineBasicBlock::rfindDebugLoc(reverse_instr_iterator MBBI) { 1489 if (MBBI == instr_rend()) 1490 return findDebugLoc(instr_begin()); 1491 // Skip debug declarations, we don't want a DebugLoc from them. 1492 MBBI = skipDebugInstructionsBackward(MBBI, instr_rbegin()); 1493 if (!MBBI->isDebugInstr()) 1494 return MBBI->getDebugLoc(); 1495 return {}; 1496 } 1497 1498 /// Find the previous valid DebugLoc preceding MBBI, skipping any debug 1499 /// instructions. Return UnknownLoc if there is none. 1500 DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) { 1501 if (MBBI == instr_begin()) 1502 return {}; 1503 // Skip debug instructions, we don't want a DebugLoc from them. 1504 MBBI = prev_nodbg(MBBI, instr_begin()); 1505 if (!MBBI->isDebugInstr()) 1506 return MBBI->getDebugLoc(); 1507 return {}; 1508 } 1509 1510 DebugLoc MachineBasicBlock::rfindPrevDebugLoc(reverse_instr_iterator MBBI) { 1511 if (MBBI == instr_rend()) 1512 return {}; 1513 // Skip debug declarations, we don't want a DebugLoc from them. 1514 MBBI = next_nodbg(MBBI, instr_rend()); 1515 if (MBBI != instr_rend()) 1516 return MBBI->getDebugLoc(); 1517 return {}; 1518 } 1519 1520 /// Find and return the merged DebugLoc of the branch instructions of the block. 1521 /// Return UnknownLoc if there is none. 1522 DebugLoc 1523 MachineBasicBlock::findBranchDebugLoc() { 1524 DebugLoc DL; 1525 auto TI = getFirstTerminator(); 1526 while (TI != end() && !TI->isBranch()) 1527 ++TI; 1528 1529 if (TI != end()) { 1530 DL = TI->getDebugLoc(); 1531 for (++TI ; TI != end() ; ++TI) 1532 if (TI->isBranch()) 1533 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc()); 1534 } 1535 return DL; 1536 } 1537 1538 /// Return probability of the edge from this block to MBB. 1539 BranchProbability 1540 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const { 1541 if (Probs.empty()) 1542 return BranchProbability(1, succ_size()); 1543 1544 const auto &Prob = *getProbabilityIterator(Succ); 1545 if (Prob.isUnknown()) { 1546 // For unknown probabilities, collect the sum of all known ones, and evenly 1547 // ditribute the complemental of the sum to each unknown probability. 1548 unsigned KnownProbNum = 0; 1549 auto Sum = BranchProbability::getZero(); 1550 for (const auto &P : Probs) { 1551 if (!P.isUnknown()) { 1552 Sum += P; 1553 KnownProbNum++; 1554 } 1555 } 1556 return Sum.getCompl() / (Probs.size() - KnownProbNum); 1557 } else 1558 return Prob; 1559 } 1560 1561 /// Set successor probability of a given iterator. 1562 void MachineBasicBlock::setSuccProbability(succ_iterator I, 1563 BranchProbability Prob) { 1564 assert(!Prob.isUnknown()); 1565 if (Probs.empty()) 1566 return; 1567 *getProbabilityIterator(I) = Prob; 1568 } 1569 1570 /// Return probability iterator corresonding to the I successor iterator 1571 MachineBasicBlock::const_probability_iterator 1572 MachineBasicBlock::getProbabilityIterator( 1573 MachineBasicBlock::const_succ_iterator I) const { 1574 assert(Probs.size() == Successors.size() && "Async probability list!"); 1575 const size_t index = std::distance(Successors.begin(), I); 1576 assert(index < Probs.size() && "Not a current successor!"); 1577 return Probs.begin() + index; 1578 } 1579 1580 /// Return probability iterator corresonding to the I successor iterator. 1581 MachineBasicBlock::probability_iterator 1582 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) { 1583 assert(Probs.size() == Successors.size() && "Async probability list!"); 1584 const size_t index = std::distance(Successors.begin(), I); 1585 assert(index < Probs.size() && "Not a current successor!"); 1586 return Probs.begin() + index; 1587 } 1588 1589 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed 1590 /// as of just before "MI". 1591 /// 1592 /// Search is localised to a neighborhood of 1593 /// Neighborhood instructions before (searching for defs or kills) and N 1594 /// instructions after (searching just for defs) MI. 1595 MachineBasicBlock::LivenessQueryResult 1596 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI, 1597 MCRegister Reg, const_iterator Before, 1598 unsigned Neighborhood) const { 1599 unsigned N = Neighborhood; 1600 1601 // Try searching forwards from Before, looking for reads or defs. 1602 const_iterator I(Before); 1603 for (; I != end() && N > 0; ++I) { 1604 if (I->isDebugOrPseudoInstr()) 1605 continue; 1606 1607 --N; 1608 1609 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI); 1610 1611 // Register is live when we read it here. 1612 if (Info.Read) 1613 return LQR_Live; 1614 // Register is dead if we can fully overwrite or clobber it here. 1615 if (Info.FullyDefined || Info.Clobbered) 1616 return LQR_Dead; 1617 } 1618 1619 // If we reached the end, it is safe to clobber Reg at the end of a block of 1620 // no successor has it live in. 1621 if (I == end()) { 1622 for (MachineBasicBlock *S : successors()) { 1623 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) { 1624 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1625 return LQR_Live; 1626 } 1627 } 1628 1629 return LQR_Dead; 1630 } 1631 1632 1633 N = Neighborhood; 1634 1635 // Start by searching backwards from Before, looking for kills, reads or defs. 1636 I = const_iterator(Before); 1637 // If this is the first insn in the block, don't search backwards. 1638 if (I != begin()) { 1639 do { 1640 --I; 1641 1642 if (I->isDebugOrPseudoInstr()) 1643 continue; 1644 1645 --N; 1646 1647 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI); 1648 1649 // Defs happen after uses so they take precedence if both are present. 1650 1651 // Register is dead after a dead def of the full register. 1652 if (Info.DeadDef) 1653 return LQR_Dead; 1654 // Register is (at least partially) live after a def. 1655 if (Info.Defined) { 1656 if (!Info.PartialDeadDef) 1657 return LQR_Live; 1658 // As soon as we saw a partial definition (dead or not), 1659 // we cannot tell if the value is partial live without 1660 // tracking the lanemasks. We are not going to do this, 1661 // so fall back on the remaining of the analysis. 1662 break; 1663 } 1664 // Register is dead after a full kill or clobber and no def. 1665 if (Info.Killed || Info.Clobbered) 1666 return LQR_Dead; 1667 // Register must be live if we read it. 1668 if (Info.Read) 1669 return LQR_Live; 1670 1671 } while (I != begin() && N > 0); 1672 } 1673 1674 // If all the instructions before this in the block are debug instructions, 1675 // skip over them. 1676 while (I != begin() && std::prev(I)->isDebugOrPseudoInstr()) 1677 --I; 1678 1679 // Did we get to the start of the block? 1680 if (I == begin()) { 1681 // If so, the register's state is definitely defined by the live-in state. 1682 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins()) 1683 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1684 return LQR_Live; 1685 1686 return LQR_Dead; 1687 } 1688 1689 // At this point we have no idea of the liveness of the register. 1690 return LQR_Unknown; 1691 } 1692 1693 const uint32_t * 1694 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const { 1695 // EH funclet entry does not preserve any registers. 1696 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr; 1697 } 1698 1699 const uint32_t * 1700 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const { 1701 // If we see a return block with successors, this must be a funclet return, 1702 // which does not preserve any registers. If there are no successors, we don't 1703 // care what kind of return it is, putting a mask after it is a no-op. 1704 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr; 1705 } 1706 1707 void MachineBasicBlock::clearLiveIns() { 1708 LiveIns.clear(); 1709 } 1710 1711 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const { 1712 assert(getParent()->getProperties().hasProperty( 1713 MachineFunctionProperties::Property::TracksLiveness) && 1714 "Liveness information is accurate"); 1715 return LiveIns.begin(); 1716 } 1717 1718 MachineBasicBlock::liveout_iterator MachineBasicBlock::liveout_begin() const { 1719 const MachineFunction &MF = *getParent(); 1720 assert(MF.getProperties().hasProperty( 1721 MachineFunctionProperties::Property::TracksLiveness) && 1722 "Liveness information is accurate"); 1723 1724 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering(); 1725 MCPhysReg ExceptionPointer = 0, ExceptionSelector = 0; 1726 if (MF.getFunction().hasPersonalityFn()) { 1727 auto PersonalityFn = MF.getFunction().getPersonalityFn(); 1728 ExceptionPointer = TLI.getExceptionPointerRegister(PersonalityFn); 1729 ExceptionSelector = TLI.getExceptionSelectorRegister(PersonalityFn); 1730 } 1731 1732 return liveout_iterator(*this, ExceptionPointer, ExceptionSelector, false); 1733 } 1734 1735 bool MachineBasicBlock::sizeWithoutDebugLargerThan(unsigned Limit) const { 1736 unsigned Cntr = 0; 1737 auto R = instructionsWithoutDebug(begin(), end()); 1738 for (auto I = R.begin(), E = R.end(); I != E; ++I) { 1739 if (++Cntr > Limit) 1740 return true; 1741 } 1742 return false; 1743 } 1744 1745 const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold); 1746 const MBBSectionID 1747 MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception); 1748