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