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