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::splitAt(MachineInstr &MI, 948 bool UpdateLiveIns, 949 LiveIntervals *LIS) { 950 MachineBasicBlock::iterator SplitPoint(&MI); 951 ++SplitPoint; 952 953 if (SplitPoint == end()) { 954 // Don't bother with a new block. 955 return this; 956 } 957 958 MachineFunction *MF = getParent(); 959 960 LivePhysRegs LiveRegs; 961 if (UpdateLiveIns) { 962 // Make sure we add any physregs we define in the block as liveins to the 963 // new block. 964 LiveRegs.init(*MF->getSubtarget().getRegisterInfo()); 965 LiveRegs.addLiveOuts(*this); 966 for (auto I = rbegin(), E = SplitPoint.getReverse(); I != E; ++I) 967 LiveRegs.stepBackward(*I); 968 } 969 970 MachineBasicBlock *SplitBB = MF->CreateMachineBasicBlock(getBasicBlock()); 971 972 MF->insert(++MachineFunction::iterator(this), SplitBB); 973 SplitBB->splice(SplitBB->begin(), this, SplitPoint, end()); 974 975 SplitBB->transferSuccessorsAndUpdatePHIs(this); 976 addSuccessor(SplitBB); 977 978 if (UpdateLiveIns) 979 addLiveIns(*SplitBB, LiveRegs); 980 981 if (LIS) 982 LIS->insertMBBInMaps(SplitBB, &MI); 983 984 return SplitBB; 985 } 986 987 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge( 988 MachineBasicBlock *Succ, Pass &P, 989 std::vector<SparseBitVector<>> *LiveInSets) { 990 if (!canSplitCriticalEdge(Succ)) 991 return nullptr; 992 993 MachineFunction *MF = getParent(); 994 MachineBasicBlock *PrevFallthrough = getNextNode(); 995 DebugLoc DL; // FIXME: this is nowhere 996 997 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(); 998 MF->insert(std::next(MachineFunction::iterator(this)), NMBB); 999 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this) 1000 << " -- " << printMBBReference(*NMBB) << " -- " 1001 << printMBBReference(*Succ) << '\n'); 1002 1003 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>(); 1004 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>(); 1005 if (LIS) 1006 LIS->insertMBBInMaps(NMBB); 1007 else if (Indexes) 1008 Indexes->insertMBBInMaps(NMBB); 1009 1010 // On some targets like Mips, branches may kill virtual registers. Make sure 1011 // that LiveVariables is properly updated after updateTerminator replaces the 1012 // terminators. 1013 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>(); 1014 1015 // Collect a list of virtual registers killed by the terminators. 1016 SmallVector<Register, 4> KilledRegs; 1017 if (LV) 1018 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 1019 I != E; ++I) { 1020 MachineInstr *MI = &*I; 1021 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 1022 OE = MI->operands_end(); OI != OE; ++OI) { 1023 if (!OI->isReg() || OI->getReg() == 0 || 1024 !OI->isUse() || !OI->isKill() || OI->isUndef()) 1025 continue; 1026 Register Reg = OI->getReg(); 1027 if (Register::isPhysicalRegister(Reg) || 1028 LV->getVarInfo(Reg).removeKill(*MI)) { 1029 KilledRegs.push_back(Reg); 1030 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << *MI); 1031 OI->setIsKill(false); 1032 } 1033 } 1034 } 1035 1036 SmallVector<Register, 4> UsedRegs; 1037 if (LIS) { 1038 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 1039 I != E; ++I) { 1040 MachineInstr *MI = &*I; 1041 1042 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 1043 OE = MI->operands_end(); OI != OE; ++OI) { 1044 if (!OI->isReg() || OI->getReg() == 0) 1045 continue; 1046 1047 Register Reg = OI->getReg(); 1048 if (!is_contained(UsedRegs, Reg)) 1049 UsedRegs.push_back(Reg); 1050 } 1051 } 1052 } 1053 1054 ReplaceUsesOfBlockWith(Succ, NMBB); 1055 1056 // If updateTerminator() removes instructions, we need to remove them from 1057 // SlotIndexes. 1058 SmallVector<MachineInstr*, 4> Terminators; 1059 if (Indexes) { 1060 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 1061 I != E; ++I) 1062 Terminators.push_back(&*I); 1063 } 1064 1065 // Since we replaced all uses of Succ with NMBB, that should also be treated 1066 // as the fallthrough successor 1067 if (Succ == PrevFallthrough) 1068 PrevFallthrough = NMBB; 1069 updateTerminator(PrevFallthrough); 1070 1071 if (Indexes) { 1072 SmallVector<MachineInstr*, 4> NewTerminators; 1073 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 1074 I != E; ++I) 1075 NewTerminators.push_back(&*I); 1076 1077 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(), 1078 E = Terminators.end(); I != E; ++I) { 1079 if (!is_contained(NewTerminators, *I)) 1080 Indexes->removeMachineInstrFromMaps(**I); 1081 } 1082 } 1083 1084 // Insert unconditional "jump Succ" instruction in NMBB if necessary. 1085 NMBB->addSuccessor(Succ); 1086 if (!NMBB->isLayoutSuccessor(Succ)) { 1087 SmallVector<MachineOperand, 4> Cond; 1088 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 1089 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL); 1090 1091 if (Indexes) { 1092 for (MachineInstr &MI : NMBB->instrs()) { 1093 // Some instructions may have been moved to NMBB by updateTerminator(), 1094 // so we first remove any instruction that already has an index. 1095 if (Indexes->hasIndex(MI)) 1096 Indexes->removeMachineInstrFromMaps(MI); 1097 Indexes->insertMachineInstrInMaps(MI); 1098 } 1099 } 1100 } 1101 1102 // Fix PHI nodes in Succ so they refer to NMBB instead of this. 1103 Succ->replacePhiUsesWith(this, NMBB); 1104 1105 // Inherit live-ins from the successor 1106 for (const auto &LI : Succ->liveins()) 1107 NMBB->addLiveIn(LI); 1108 1109 // Update LiveVariables. 1110 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1111 if (LV) { 1112 // Restore kills of virtual registers that were killed by the terminators. 1113 while (!KilledRegs.empty()) { 1114 Register Reg = KilledRegs.pop_back_val(); 1115 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) { 1116 if (!(--I)->addRegisterKilled(Reg, TRI, /* AddIfNotFound= */ false)) 1117 continue; 1118 if (Register::isVirtualRegister(Reg)) 1119 LV->getVarInfo(Reg).Kills.push_back(&*I); 1120 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I); 1121 break; 1122 } 1123 } 1124 // Update relevant live-through information. 1125 if (LiveInSets != nullptr) 1126 LV->addNewBlock(NMBB, this, Succ, *LiveInSets); 1127 else 1128 LV->addNewBlock(NMBB, this, Succ); 1129 } 1130 1131 if (LIS) { 1132 // After splitting the edge and updating SlotIndexes, live intervals may be 1133 // in one of two situations, depending on whether this block was the last in 1134 // the function. If the original block was the last in the function, all 1135 // live intervals will end prior to the beginning of the new split block. If 1136 // the original block was not at the end of the function, all live intervals 1137 // will extend to the end of the new split block. 1138 1139 bool isLastMBB = 1140 std::next(MachineFunction::iterator(NMBB)) == getParent()->end(); 1141 1142 SlotIndex StartIndex = Indexes->getMBBEndIdx(this); 1143 SlotIndex PrevIndex = StartIndex.getPrevSlot(); 1144 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB); 1145 1146 // Find the registers used from NMBB in PHIs in Succ. 1147 SmallSet<Register, 8> PHISrcRegs; 1148 for (MachineBasicBlock::instr_iterator 1149 I = Succ->instr_begin(), E = Succ->instr_end(); 1150 I != E && I->isPHI(); ++I) { 1151 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) { 1152 if (I->getOperand(ni+1).getMBB() == NMBB) { 1153 MachineOperand &MO = I->getOperand(ni); 1154 Register Reg = MO.getReg(); 1155 PHISrcRegs.insert(Reg); 1156 if (MO.isUndef()) 1157 continue; 1158 1159 LiveInterval &LI = LIS->getInterval(Reg); 1160 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1161 assert(VNI && 1162 "PHI sources should be live out of their predecessors."); 1163 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1164 } 1165 } 1166 } 1167 1168 MachineRegisterInfo *MRI = &getParent()->getRegInfo(); 1169 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1170 Register Reg = Register::index2VirtReg(i); 1171 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg)) 1172 continue; 1173 1174 LiveInterval &LI = LIS->getInterval(Reg); 1175 if (!LI.liveAt(PrevIndex)) 1176 continue; 1177 1178 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ)); 1179 if (isLiveOut && isLastMBB) { 1180 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1181 assert(VNI && "LiveInterval should have VNInfo where it is live."); 1182 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1183 } else if (!isLiveOut && !isLastMBB) { 1184 LI.removeSegment(StartIndex, EndIndex); 1185 } 1186 } 1187 1188 // Update all intervals for registers whose uses may have been modified by 1189 // updateTerminator(). 1190 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs); 1191 } 1192 1193 if (MachineDominatorTree *MDT = 1194 P.getAnalysisIfAvailable<MachineDominatorTree>()) 1195 MDT->recordSplitCriticalEdge(this, Succ, NMBB); 1196 1197 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>()) 1198 if (MachineLoop *TIL = MLI->getLoopFor(this)) { 1199 // If one or the other blocks were not in a loop, the new block is not 1200 // either, and thus LI doesn't need to be updated. 1201 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) { 1202 if (TIL == DestLoop) { 1203 // Both in the same loop, the NMBB joins loop. 1204 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1205 } else if (TIL->contains(DestLoop)) { 1206 // Edge from an outer loop to an inner loop. Add to the outer loop. 1207 TIL->addBasicBlockToLoop(NMBB, MLI->getBase()); 1208 } else if (DestLoop->contains(TIL)) { 1209 // Edge from an inner loop to an outer loop. Add to the outer loop. 1210 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1211 } else { 1212 // Edge from two loops with no containment relation. Because these 1213 // are natural loops, we know that the destination block must be the 1214 // header of its loop (adding a branch into a loop elsewhere would 1215 // create an irreducible loop). 1216 assert(DestLoop->getHeader() == Succ && 1217 "Should not create irreducible loops!"); 1218 if (MachineLoop *P = DestLoop->getParentLoop()) 1219 P->addBasicBlockToLoop(NMBB, MLI->getBase()); 1220 } 1221 } 1222 } 1223 1224 return NMBB; 1225 } 1226 1227 bool MachineBasicBlock::canSplitCriticalEdge( 1228 const MachineBasicBlock *Succ) const { 1229 // Splitting the critical edge to a landing pad block is non-trivial. Don't do 1230 // it in this generic function. 1231 if (Succ->isEHPad()) 1232 return false; 1233 1234 // Splitting the critical edge to a callbr's indirect block isn't advised. 1235 // Don't do it in this generic function. 1236 if (Succ->isInlineAsmBrIndirectTarget()) 1237 return false; 1238 1239 const MachineFunction *MF = getParent(); 1240 // Performance might be harmed on HW that implements branching using exec mask 1241 // where both sides of the branches are always executed. 1242 if (MF->getTarget().requiresStructuredCFG()) 1243 return false; 1244 1245 // We may need to update this's terminator, but we can't do that if 1246 // analyzeBranch fails. If this uses a jump table, we won't touch it. 1247 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1248 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1249 SmallVector<MachineOperand, 4> Cond; 1250 // AnalyzeBanch should modify this, since we did not allow modification. 1251 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond, 1252 /*AllowModify*/ false)) 1253 return false; 1254 1255 // Avoid bugpoint weirdness: A block may end with a conditional branch but 1256 // jumps to the same MBB is either case. We have duplicate CFG edges in that 1257 // case that we can't handle. Since this never happens in properly optimized 1258 // code, just skip those edges. 1259 if (TBB && TBB == FBB) { 1260 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate " 1261 << printMBBReference(*this) << '\n'); 1262 return false; 1263 } 1264 return true; 1265 } 1266 1267 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's 1268 /// neighboring instructions so the bundle won't be broken by removing MI. 1269 static void unbundleSingleMI(MachineInstr *MI) { 1270 // Removing the first instruction in a bundle. 1271 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) 1272 MI->unbundleFromSucc(); 1273 // Removing the last instruction in a bundle. 1274 if (MI->isBundledWithPred() && !MI->isBundledWithSucc()) 1275 MI->unbundleFromPred(); 1276 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags 1277 // are already fine. 1278 } 1279 1280 MachineBasicBlock::instr_iterator 1281 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) { 1282 unbundleSingleMI(&*I); 1283 return Insts.erase(I); 1284 } 1285 1286 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) { 1287 unbundleSingleMI(MI); 1288 MI->clearFlag(MachineInstr::BundledPred); 1289 MI->clearFlag(MachineInstr::BundledSucc); 1290 return Insts.remove(MI); 1291 } 1292 1293 MachineBasicBlock::instr_iterator 1294 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) { 1295 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() && 1296 "Cannot insert instruction with bundle flags"); 1297 // Set the bundle flags when inserting inside a bundle. 1298 if (I != instr_end() && I->isBundledWithPred()) { 1299 MI->setFlag(MachineInstr::BundledPred); 1300 MI->setFlag(MachineInstr::BundledSucc); 1301 } 1302 return Insts.insert(I, MI); 1303 } 1304 1305 /// This method unlinks 'this' from the containing function, and returns it, but 1306 /// does not delete it. 1307 MachineBasicBlock *MachineBasicBlock::removeFromParent() { 1308 assert(getParent() && "Not embedded in a function!"); 1309 getParent()->remove(this); 1310 return this; 1311 } 1312 1313 /// This method unlinks 'this' from the containing function, and deletes it. 1314 void MachineBasicBlock::eraseFromParent() { 1315 assert(getParent() && "Not embedded in a function!"); 1316 getParent()->erase(this); 1317 } 1318 1319 /// Given a machine basic block that branched to 'Old', change the code and CFG 1320 /// so that it branches to 'New' instead. 1321 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old, 1322 MachineBasicBlock *New) { 1323 assert(Old != New && "Cannot replace self with self!"); 1324 1325 MachineBasicBlock::instr_iterator I = instr_end(); 1326 while (I != instr_begin()) { 1327 --I; 1328 if (!I->isTerminator()) break; 1329 1330 // Scan the operands of this machine instruction, replacing any uses of Old 1331 // with New. 1332 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1333 if (I->getOperand(i).isMBB() && 1334 I->getOperand(i).getMBB() == Old) 1335 I->getOperand(i).setMBB(New); 1336 } 1337 1338 // Update the successor information. 1339 replaceSuccessor(Old, New); 1340 } 1341 1342 void MachineBasicBlock::replacePhiUsesWith(MachineBasicBlock *Old, 1343 MachineBasicBlock *New) { 1344 for (MachineInstr &MI : phis()) 1345 for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) { 1346 MachineOperand &MO = MI.getOperand(i); 1347 if (MO.getMBB() == Old) 1348 MO.setMBB(New); 1349 } 1350 } 1351 1352 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE 1353 /// instructions. Return UnknownLoc if there is none. 1354 DebugLoc 1355 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) { 1356 // Skip debug declarations, we don't want a DebugLoc from them. 1357 MBBI = skipDebugInstructionsForward(MBBI, instr_end()); 1358 if (MBBI != instr_end()) 1359 return MBBI->getDebugLoc(); 1360 return {}; 1361 } 1362 1363 /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE 1364 /// instructions. Return UnknownLoc if there is none. 1365 DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) { 1366 if (MBBI == instr_begin()) return {}; 1367 // Skip debug instructions, we don't want a DebugLoc from them. 1368 MBBI = prev_nodbg(MBBI, instr_begin()); 1369 if (!MBBI->isDebugInstr()) return MBBI->getDebugLoc(); 1370 return {}; 1371 } 1372 1373 /// Find and return the merged DebugLoc of the branch instructions of the block. 1374 /// Return UnknownLoc if there is none. 1375 DebugLoc 1376 MachineBasicBlock::findBranchDebugLoc() { 1377 DebugLoc DL; 1378 auto TI = getFirstTerminator(); 1379 while (TI != end() && !TI->isBranch()) 1380 ++TI; 1381 1382 if (TI != end()) { 1383 DL = TI->getDebugLoc(); 1384 for (++TI ; TI != end() ; ++TI) 1385 if (TI->isBranch()) 1386 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc()); 1387 } 1388 return DL; 1389 } 1390 1391 /// Return probability of the edge from this block to MBB. 1392 BranchProbability 1393 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const { 1394 if (Probs.empty()) 1395 return BranchProbability(1, succ_size()); 1396 1397 const auto &Prob = *getProbabilityIterator(Succ); 1398 if (Prob.isUnknown()) { 1399 // For unknown probabilities, collect the sum of all known ones, and evenly 1400 // ditribute the complemental of the sum to each unknown probability. 1401 unsigned KnownProbNum = 0; 1402 auto Sum = BranchProbability::getZero(); 1403 for (auto &P : Probs) { 1404 if (!P.isUnknown()) { 1405 Sum += P; 1406 KnownProbNum++; 1407 } 1408 } 1409 return Sum.getCompl() / (Probs.size() - KnownProbNum); 1410 } else 1411 return Prob; 1412 } 1413 1414 /// Set successor probability of a given iterator. 1415 void MachineBasicBlock::setSuccProbability(succ_iterator I, 1416 BranchProbability Prob) { 1417 assert(!Prob.isUnknown()); 1418 if (Probs.empty()) 1419 return; 1420 *getProbabilityIterator(I) = Prob; 1421 } 1422 1423 /// Return probability iterator corresonding to the I successor iterator 1424 MachineBasicBlock::const_probability_iterator 1425 MachineBasicBlock::getProbabilityIterator( 1426 MachineBasicBlock::const_succ_iterator I) const { 1427 assert(Probs.size() == Successors.size() && "Async probability list!"); 1428 const size_t index = std::distance(Successors.begin(), I); 1429 assert(index < Probs.size() && "Not a current successor!"); 1430 return Probs.begin() + index; 1431 } 1432 1433 /// Return probability iterator corresonding to the I successor iterator. 1434 MachineBasicBlock::probability_iterator 1435 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) { 1436 assert(Probs.size() == Successors.size() && "Async probability list!"); 1437 const size_t index = std::distance(Successors.begin(), I); 1438 assert(index < Probs.size() && "Not a current successor!"); 1439 return Probs.begin() + index; 1440 } 1441 1442 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed 1443 /// as of just before "MI". 1444 /// 1445 /// Search is localised to a neighborhood of 1446 /// Neighborhood instructions before (searching for defs or kills) and N 1447 /// instructions after (searching just for defs) MI. 1448 MachineBasicBlock::LivenessQueryResult 1449 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI, 1450 MCRegister Reg, const_iterator Before, 1451 unsigned Neighborhood) const { 1452 unsigned N = Neighborhood; 1453 1454 // Try searching forwards from Before, looking for reads or defs. 1455 const_iterator I(Before); 1456 for (; I != end() && N > 0; ++I) { 1457 if (I->isDebugInstr()) 1458 continue; 1459 1460 --N; 1461 1462 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI); 1463 1464 // Register is live when we read it here. 1465 if (Info.Read) 1466 return LQR_Live; 1467 // Register is dead if we can fully overwrite or clobber it here. 1468 if (Info.FullyDefined || Info.Clobbered) 1469 return LQR_Dead; 1470 } 1471 1472 // If we reached the end, it is safe to clobber Reg at the end of a block of 1473 // no successor has it live in. 1474 if (I == end()) { 1475 for (MachineBasicBlock *S : successors()) { 1476 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) { 1477 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1478 return LQR_Live; 1479 } 1480 } 1481 1482 return LQR_Dead; 1483 } 1484 1485 1486 N = Neighborhood; 1487 1488 // Start by searching backwards from Before, looking for kills, reads or defs. 1489 I = const_iterator(Before); 1490 // If this is the first insn in the block, don't search backwards. 1491 if (I != begin()) { 1492 do { 1493 --I; 1494 1495 if (I->isDebugInstr()) 1496 continue; 1497 1498 --N; 1499 1500 PhysRegInfo Info = AnalyzePhysRegInBundle(*I, Reg, TRI); 1501 1502 // Defs happen after uses so they take precedence if both are present. 1503 1504 // Register is dead after a dead def of the full register. 1505 if (Info.DeadDef) 1506 return LQR_Dead; 1507 // Register is (at least partially) live after a def. 1508 if (Info.Defined) { 1509 if (!Info.PartialDeadDef) 1510 return LQR_Live; 1511 // As soon as we saw a partial definition (dead or not), 1512 // we cannot tell if the value is partial live without 1513 // tracking the lanemasks. We are not going to do this, 1514 // so fall back on the remaining of the analysis. 1515 break; 1516 } 1517 // Register is dead after a full kill or clobber and no def. 1518 if (Info.Killed || Info.Clobbered) 1519 return LQR_Dead; 1520 // Register must be live if we read it. 1521 if (Info.Read) 1522 return LQR_Live; 1523 1524 } while (I != begin() && N > 0); 1525 } 1526 1527 // If all the instructions before this in the block are debug instructions, 1528 // skip over them. 1529 while (I != begin() && std::prev(I)->isDebugInstr()) 1530 --I; 1531 1532 // Did we get to the start of the block? 1533 if (I == begin()) { 1534 // If so, the register's state is definitely defined by the live-in state. 1535 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins()) 1536 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1537 return LQR_Live; 1538 1539 return LQR_Dead; 1540 } 1541 1542 // At this point we have no idea of the liveness of the register. 1543 return LQR_Unknown; 1544 } 1545 1546 const uint32_t * 1547 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const { 1548 // EH funclet entry does not preserve any registers. 1549 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr; 1550 } 1551 1552 const uint32_t * 1553 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const { 1554 // If we see a return block with successors, this must be a funclet return, 1555 // which does not preserve any registers. If there are no successors, we don't 1556 // care what kind of return it is, putting a mask after it is a no-op. 1557 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr; 1558 } 1559 1560 void MachineBasicBlock::clearLiveIns() { 1561 LiveIns.clear(); 1562 } 1563 1564 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const { 1565 assert(getParent()->getProperties().hasProperty( 1566 MachineFunctionProperties::Property::TracksLiveness) && 1567 "Liveness information is accurate"); 1568 return LiveIns.begin(); 1569 } 1570 1571 const MBBSectionID MBBSectionID::ColdSectionID(MBBSectionID::SectionType::Cold); 1572 const MBBSectionID 1573 MBBSectionID::ExceptionSectionID(MBBSectionID::SectionType::Exception); 1574