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