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