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