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