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