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