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