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