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