LLVM API Documentation

MachineBasicBlock.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Collect the sequence of machine instructions for a basic block.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/MachineBasicBlock.h"
00015 #include "llvm/ADT/SmallPtrSet.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00018 #include "llvm/CodeGen/LiveVariables.h"
00019 #include "llvm/CodeGen/MachineDominators.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/MachineLoopInfo.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/SlotIndexes.h"
00025 #include "llvm/IR/BasicBlock.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/MC/MCAsmInfo.h"
00028 #include "llvm/MC/MCContext.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <algorithm>
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "codegen"
00039 
00040 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
00041   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
00042     AddressTaken(false), CachedMCSymbol(nullptr) {
00043   Insts.Parent = this;
00044 }
00045 
00046 MachineBasicBlock::~MachineBasicBlock() {
00047 }
00048 
00049 /// getSymbol - Return the MCSymbol for this basic block.
00050 ///
00051 MCSymbol *MachineBasicBlock::getSymbol() const {
00052   if (!CachedMCSymbol) {
00053     const MachineFunction *MF = getParent();
00054     MCContext &Ctx = MF->getContext();
00055     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
00056     CachedMCSymbol = Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
00057                                            Twine(MF->getFunctionNumber()) +
00058                                            "_" + Twine(getNumber()));
00059   }
00060 
00061   return CachedMCSymbol;
00062 }
00063 
00064 
00065 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
00066   MBB.print(OS);
00067   return OS;
00068 }
00069 
00070 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
00071 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
00072 /// MBB to be on the right operand list for registers.
00073 ///
00074 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
00075 /// gets the next available unique MBB number. If it is removed from a
00076 /// MachineFunction, it goes back to being #-1.
00077 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
00078   MachineFunction &MF = *N->getParent();
00079   N->Number = MF.addToMBBNumbering(N);
00080 
00081   // Make sure the instructions have their operands in the reginfo lists.
00082   MachineRegisterInfo &RegInfo = MF.getRegInfo();
00083   for (MachineBasicBlock::instr_iterator
00084          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
00085     I->AddRegOperandsToUseLists(RegInfo);
00086 }
00087 
00088 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
00089   N->getParent()->removeFromMBBNumbering(N->Number);
00090   N->Number = -1;
00091 }
00092 
00093 
00094 /// addNodeToList (MI) - When we add an instruction to a basic block
00095 /// list, we update its parent pointer and add its operands from reg use/def
00096 /// lists if appropriate.
00097 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
00098   assert(!N->getParent() && "machine instruction already in a basic block");
00099   N->setParent(Parent);
00100 
00101   // Add the instruction's register operands to their corresponding
00102   // use/def lists.
00103   MachineFunction *MF = Parent->getParent();
00104   N->AddRegOperandsToUseLists(MF->getRegInfo());
00105 }
00106 
00107 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
00108 /// list, we update its parent pointer and remove its operands from reg use/def
00109 /// lists if appropriate.
00110 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
00111   assert(N->getParent() && "machine instruction not in a basic block");
00112 
00113   // Remove from the use/def lists.
00114   if (MachineFunction *MF = N->getParent()->getParent())
00115     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
00116 
00117   N->setParent(nullptr);
00118 }
00119 
00120 /// transferNodesFromList (MI) - When moving a range of instructions from one
00121 /// MBB list to another, we need to update the parent pointers and the use/def
00122 /// lists.
00123 void ilist_traits<MachineInstr>::
00124 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
00125                       ilist_iterator<MachineInstr> first,
00126                       ilist_iterator<MachineInstr> last) {
00127   assert(Parent->getParent() == fromList.Parent->getParent() &&
00128         "MachineInstr parent mismatch!");
00129 
00130   // Splice within the same MBB -> no change.
00131   if (Parent == fromList.Parent) return;
00132 
00133   // If splicing between two blocks within the same function, just update the
00134   // parent pointers.
00135   for (; first != last; ++first)
00136     first->setParent(Parent);
00137 }
00138 
00139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
00140   assert(!MI->getParent() && "MI is still in a block!");
00141   Parent->getParent()->DeleteMachineInstr(MI);
00142 }
00143 
00144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
00145   instr_iterator I = instr_begin(), E = instr_end();
00146   while (I != E && I->isPHI())
00147     ++I;
00148   assert((I == E || !I->isInsideBundle()) &&
00149          "First non-phi MI cannot be inside a bundle!");
00150   return I;
00151 }
00152 
00153 MachineBasicBlock::iterator
00154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
00155   iterator E = end();
00156   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
00157     ++I;
00158   // FIXME: This needs to change if we wish to bundle labels / dbg_values
00159   // inside the bundle.
00160   assert((I == E || !I->isInsideBundle()) &&
00161          "First non-phi / non-label instruction is inside a bundle!");
00162   return I;
00163 }
00164 
00165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
00166   iterator B = begin(), E = end(), I = E;
00167   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
00168     ; /*noop */
00169   while (I != E && !I->isTerminator())
00170     ++I;
00171   return I;
00172 }
00173 
00174 MachineBasicBlock::const_iterator
00175 MachineBasicBlock::getFirstTerminator() const {
00176   const_iterator B = begin(), E = end(), I = E;
00177   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
00178     ; /*noop */
00179   while (I != E && !I->isTerminator())
00180     ++I;
00181   return I;
00182 }
00183 
00184 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
00185   instr_iterator B = instr_begin(), E = instr_end(), I = E;
00186   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
00187     ; /*noop */
00188   while (I != E && !I->isTerminator())
00189     ++I;
00190   return I;
00191 }
00192 
00193 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
00194   // Skip over end-of-block dbg_value instructions.
00195   instr_iterator B = instr_begin(), I = instr_end();
00196   while (I != B) {
00197     --I;
00198     // Return instruction that starts a bundle.
00199     if (I->isDebugValue() || I->isInsideBundle())
00200       continue;
00201     return I;
00202   }
00203   // The block is all debug values.
00204   return end();
00205 }
00206 
00207 MachineBasicBlock::const_iterator
00208 MachineBasicBlock::getLastNonDebugInstr() const {
00209   // Skip over end-of-block dbg_value instructions.
00210   const_instr_iterator B = instr_begin(), I = instr_end();
00211   while (I != B) {
00212     --I;
00213     // Return instruction that starts a bundle.
00214     if (I->isDebugValue() || I->isInsideBundle())
00215       continue;
00216     return I;
00217   }
00218   // The block is all debug values.
00219   return end();
00220 }
00221 
00222 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
00223   // A block with a landing pad successor only has one other successor.
00224   if (succ_size() > 2)
00225     return nullptr;
00226   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
00227     if ((*I)->isLandingPad())
00228       return *I;
00229   return nullptr;
00230 }
00231 
00232 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00233 void MachineBasicBlock::dump() const {
00234   print(dbgs());
00235 }
00236 #endif
00237 
00238 StringRef MachineBasicBlock::getName() const {
00239   if (const BasicBlock *LBB = getBasicBlock())
00240     return LBB->getName();
00241   else
00242     return "(null)";
00243 }
00244 
00245 /// Return a hopefully unique identifier for this block.
00246 std::string MachineBasicBlock::getFullName() const {
00247   std::string Name;
00248   if (getParent())
00249     Name = (getParent()->getName() + ":").str();
00250   if (getBasicBlock())
00251     Name += getBasicBlock()->getName();
00252   else
00253     Name += (Twine("BB") + Twine(getNumber())).str();
00254   return Name;
00255 }
00256 
00257 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
00258   const MachineFunction *MF = getParent();
00259   if (!MF) {
00260     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
00261        << " is null\n";
00262     return;
00263   }
00264 
00265   if (Indexes)
00266     OS << Indexes->getMBBStartIdx(this) << '\t';
00267 
00268   OS << "BB#" << getNumber() << ": ";
00269 
00270   const char *Comma = "";
00271   if (const BasicBlock *LBB = getBasicBlock()) {
00272     OS << Comma << "derived from LLVM BB ";
00273     LBB->printAsOperand(OS, /*PrintType=*/false);
00274     Comma = ", ";
00275   }
00276   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
00277   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
00278   if (Alignment)
00279     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
00280        << " bytes)";
00281 
00282   OS << '\n';
00283 
00284   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00285   if (!livein_empty()) {
00286     if (Indexes) OS << '\t';
00287     OS << "    Live Ins:";
00288     for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
00289       OS << ' ' << PrintReg(*I, TRI);
00290     OS << '\n';
00291   }
00292   // Print the preds of this block according to the CFG.
00293   if (!pred_empty()) {
00294     if (Indexes) OS << '\t';
00295     OS << "    Predecessors according to CFG:";
00296     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
00297       OS << " BB#" << (*PI)->getNumber();
00298     OS << '\n';
00299   }
00300 
00301   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
00302     if (Indexes) {
00303       if (Indexes->hasIndex(I))
00304         OS << Indexes->getInstructionIndex(I);
00305       OS << '\t';
00306     }
00307     OS << '\t';
00308     if (I->isInsideBundle())
00309       OS << "  * ";
00310     I->print(OS, &getParent()->getTarget());
00311   }
00312 
00313   // Print the successors of this block according to the CFG.
00314   if (!succ_empty()) {
00315     if (Indexes) OS << '\t';
00316     OS << "    Successors according to CFG:";
00317     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
00318       OS << " BB#" << (*SI)->getNumber();
00319       if (!Weights.empty())
00320         OS << '(' << *getWeightIterator(SI) << ')';
00321     }
00322     OS << '\n';
00323   }
00324 }
00325 
00326 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
00327   OS << "BB#" << getNumber();
00328 }
00329 
00330 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
00331   std::vector<unsigned>::iterator I =
00332     std::find(LiveIns.begin(), LiveIns.end(), Reg);
00333   if (I != LiveIns.end())
00334     LiveIns.erase(I);
00335 }
00336 
00337 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
00338   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
00339   return I != livein_end();
00340 }
00341 
00342 unsigned
00343 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
00344   assert(getParent() && "MBB must be inserted in function");
00345   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
00346   assert(RC && "Register class is required");
00347   assert((isLandingPad() || this == &getParent()->front()) &&
00348          "Only the entry block and landing pads can have physreg live ins");
00349 
00350   bool LiveIn = isLiveIn(PhysReg);
00351   iterator I = SkipPHIsAndLabels(begin()), E = end();
00352   MachineRegisterInfo &MRI = getParent()->getRegInfo();
00353   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
00354 
00355   // Look for an existing copy.
00356   if (LiveIn)
00357     for (;I != E && I->isCopy(); ++I)
00358       if (I->getOperand(1).getReg() == PhysReg) {
00359         unsigned VirtReg = I->getOperand(0).getReg();
00360         if (!MRI.constrainRegClass(VirtReg, RC))
00361           llvm_unreachable("Incompatible live-in register class.");
00362         return VirtReg;
00363       }
00364 
00365   // No luck, create a virtual register.
00366   unsigned VirtReg = MRI.createVirtualRegister(RC);
00367   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
00368     .addReg(PhysReg, RegState::Kill);
00369   if (!LiveIn)
00370     addLiveIn(PhysReg);
00371   return VirtReg;
00372 }
00373 
00374 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
00375   getParent()->splice(NewAfter, this);
00376 }
00377 
00378 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
00379   MachineFunction::iterator BBI = NewBefore;
00380   getParent()->splice(++BBI, this);
00381 }
00382 
00383 void MachineBasicBlock::updateTerminator() {
00384   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
00385   // A block with no successors has no concerns with fall-through edges.
00386   if (this->succ_empty()) return;
00387 
00388   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00389   SmallVector<MachineOperand, 4> Cond;
00390   DebugLoc dl;  // FIXME: this is nowhere
00391   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
00392   (void) B;
00393   assert(!B && "UpdateTerminators requires analyzable predecessors!");
00394   if (Cond.empty()) {
00395     if (TBB) {
00396       // The block has an unconditional branch. If its successor is now
00397       // its layout successor, delete the branch.
00398       if (isLayoutSuccessor(TBB))
00399         TII->RemoveBranch(*this);
00400     } else {
00401       // The block has an unconditional fallthrough. If its successor is not
00402       // its layout successor, insert a branch. First we have to locate the
00403       // only non-landing-pad successor, as that is the fallthrough block.
00404       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
00405         if ((*SI)->isLandingPad())
00406           continue;
00407         assert(!TBB && "Found more than one non-landing-pad successor!");
00408         TBB = *SI;
00409       }
00410 
00411       // If there is no non-landing-pad successor, the block has no
00412       // fall-through edges to be concerned with.
00413       if (!TBB)
00414         return;
00415 
00416       // Finally update the unconditional successor to be reached via a branch
00417       // if it would not be reached by fallthrough.
00418       if (!isLayoutSuccessor(TBB))
00419         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00420     }
00421   } else {
00422     if (FBB) {
00423       // The block has a non-fallthrough conditional branch. If one of its
00424       // successors is its layout successor, rewrite it to a fallthrough
00425       // conditional branch.
00426       if (isLayoutSuccessor(TBB)) {
00427         if (TII->ReverseBranchCondition(Cond))
00428           return;
00429         TII->RemoveBranch(*this);
00430         TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
00431       } else if (isLayoutSuccessor(FBB)) {
00432         TII->RemoveBranch(*this);
00433         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00434       }
00435     } else {
00436       // Walk through the successors and find the successor which is not
00437       // a landing pad and is not the conditional branch destination (in TBB)
00438       // as the fallthrough successor.
00439       MachineBasicBlock *FallthroughBB = nullptr;
00440       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
00441         if ((*SI)->isLandingPad() || *SI == TBB)
00442           continue;
00443         assert(!FallthroughBB && "Found more than one fallthrough successor.");
00444         FallthroughBB = *SI;
00445       }
00446       if (!FallthroughBB && canFallThrough()) {
00447         // We fallthrough to the same basic block as the conditional jump
00448         // targets. Remove the conditional jump, leaving unconditional
00449         // fallthrough.
00450         // FIXME: This does not seem like a reasonable pattern to support, but it
00451         // has been seen in the wild coming out of degenerate ARM test cases.
00452         TII->RemoveBranch(*this);
00453 
00454         // Finally update the unconditional successor to be reached via a branch
00455         // if it would not be reached by fallthrough.
00456         if (!isLayoutSuccessor(TBB))
00457           TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00458         return;
00459       }
00460 
00461       // The block has a fallthrough conditional branch.
00462       if (isLayoutSuccessor(TBB)) {
00463         if (TII->ReverseBranchCondition(Cond)) {
00464           // We can't reverse the condition, add an unconditional branch.
00465           Cond.clear();
00466           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
00467           return;
00468         }
00469         TII->RemoveBranch(*this);
00470         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
00471       } else if (!isLayoutSuccessor(FallthroughBB)) {
00472         TII->RemoveBranch(*this);
00473         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
00474       }
00475     }
00476   }
00477 }
00478 
00479 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
00480 
00481   // If we see non-zero value for the first time it means we actually use Weight
00482   // list, so we fill all Weights with 0's.
00483   if (weight != 0 && Weights.empty())
00484     Weights.resize(Successors.size());
00485 
00486   if (weight != 0 || !Weights.empty())
00487     Weights.push_back(weight);
00488 
00489    Successors.push_back(succ);
00490    succ->addPredecessor(this);
00491  }
00492 
00493 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
00494   succ->removePredecessor(this);
00495   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
00496   assert(I != Successors.end() && "Not a current successor!");
00497 
00498   // If Weight list is empty it means we don't use it (disabled optimization).
00499   if (!Weights.empty()) {
00500     weight_iterator WI = getWeightIterator(I);
00501     Weights.erase(WI);
00502   }
00503 
00504   Successors.erase(I);
00505 }
00506 
00507 MachineBasicBlock::succ_iterator
00508 MachineBasicBlock::removeSuccessor(succ_iterator I) {
00509   assert(I != Successors.end() && "Not a current successor!");
00510 
00511   // If Weight list is empty it means we don't use it (disabled optimization).
00512   if (!Weights.empty()) {
00513     weight_iterator WI = getWeightIterator(I);
00514     Weights.erase(WI);
00515   }
00516 
00517   (*I)->removePredecessor(this);
00518   return Successors.erase(I);
00519 }
00520 
00521 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
00522                                          MachineBasicBlock *New) {
00523   if (Old == New)
00524     return;
00525 
00526   succ_iterator E = succ_end();
00527   succ_iterator NewI = E;
00528   succ_iterator OldI = E;
00529   for (succ_iterator I = succ_begin(); I != E; ++I) {
00530     if (*I == Old) {
00531       OldI = I;
00532       if (NewI != E)
00533         break;
00534     }
00535     if (*I == New) {
00536       NewI = I;
00537       if (OldI != E)
00538         break;
00539     }
00540   }
00541   assert(OldI != E && "Old is not a successor of this block");
00542   Old->removePredecessor(this);
00543 
00544   // If New isn't already a successor, let it take Old's place.
00545   if (NewI == E) {
00546     New->addPredecessor(this);
00547     *OldI = New;
00548     return;
00549   }
00550 
00551   // New is already a successor.
00552   // Update its weight instead of adding a duplicate edge.
00553   if (!Weights.empty()) {
00554     weight_iterator OldWI = getWeightIterator(OldI);
00555     *getWeightIterator(NewI) += *OldWI;
00556     Weights.erase(OldWI);
00557   }
00558   Successors.erase(OldI);
00559 }
00560 
00561 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
00562   Predecessors.push_back(pred);
00563 }
00564 
00565 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
00566   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
00567   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
00568   Predecessors.erase(I);
00569 }
00570 
00571 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
00572   if (this == fromMBB)
00573     return;
00574 
00575   while (!fromMBB->succ_empty()) {
00576     MachineBasicBlock *Succ = *fromMBB->succ_begin();
00577     uint32_t Weight = 0;
00578 
00579     // If Weight list is empty it means we don't use it (disabled optimization).
00580     if (!fromMBB->Weights.empty())
00581       Weight = *fromMBB->Weights.begin();
00582 
00583     addSuccessor(Succ, Weight);
00584     fromMBB->removeSuccessor(Succ);
00585   }
00586 }
00587 
00588 void
00589 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
00590   if (this == fromMBB)
00591     return;
00592 
00593   while (!fromMBB->succ_empty()) {
00594     MachineBasicBlock *Succ = *fromMBB->succ_begin();
00595     uint32_t Weight = 0;
00596     if (!fromMBB->Weights.empty())
00597       Weight = *fromMBB->Weights.begin();
00598     addSuccessor(Succ, Weight);
00599     fromMBB->removeSuccessor(Succ);
00600 
00601     // Fix up any PHI nodes in the successor.
00602     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
00603            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
00604       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
00605         MachineOperand &MO = MI->getOperand(i);
00606         if (MO.getMBB() == fromMBB)
00607           MO.setMBB(this);
00608       }
00609   }
00610 }
00611 
00612 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
00613   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
00614 }
00615 
00616 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
00617   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
00618 }
00619 
00620 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
00621   MachineFunction::const_iterator I(this);
00622   return std::next(I) == MachineFunction::const_iterator(MBB);
00623 }
00624 
00625 bool MachineBasicBlock::canFallThrough() {
00626   MachineFunction::iterator Fallthrough = this;
00627   ++Fallthrough;
00628   // If FallthroughBlock is off the end of the function, it can't fall through.
00629   if (Fallthrough == getParent()->end())
00630     return false;
00631 
00632   // If FallthroughBlock isn't a successor, no fallthrough is possible.
00633   if (!isSuccessor(Fallthrough))
00634     return false;
00635 
00636   // Analyze the branches, if any, at the end of the block.
00637   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00638   SmallVector<MachineOperand, 4> Cond;
00639   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
00640   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
00641     // If we couldn't analyze the branch, examine the last instruction.
00642     // If the block doesn't end in a known control barrier, assume fallthrough
00643     // is possible. The isPredicated check is needed because this code can be
00644     // called during IfConversion, where an instruction which is normally a
00645     // Barrier is predicated and thus no longer an actual control barrier.
00646     return empty() || !back().isBarrier() || TII->isPredicated(&back());
00647   }
00648 
00649   // If there is no branch, control always falls through.
00650   if (!TBB) return true;
00651 
00652   // If there is some explicit branch to the fallthrough block, it can obviously
00653   // reach, even though the branch should get folded to fall through implicitly.
00654   if (MachineFunction::iterator(TBB) == Fallthrough ||
00655       MachineFunction::iterator(FBB) == Fallthrough)
00656     return true;
00657 
00658   // If it's an unconditional branch to some block not the fall through, it
00659   // doesn't fall through.
00660   if (Cond.empty()) return false;
00661 
00662   // Otherwise, if it is conditional and has no explicit false block, it falls
00663   // through.
00664   return FBB == nullptr;
00665 }
00666 
00667 MachineBasicBlock *
00668 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
00669   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
00670   // it in this generic function.
00671   if (Succ->isLandingPad())
00672     return nullptr;
00673 
00674   MachineFunction *MF = getParent();
00675   DebugLoc dl;  // FIXME: this is nowhere
00676 
00677   // Performance might be harmed on HW that implements branching using exec mask
00678   // where both sides of the branches are always executed.
00679   if (MF->getTarget().requiresStructuredCFG())
00680     return nullptr;
00681 
00682   // We may need to update this's terminator, but we can't do that if
00683   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
00684   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00685   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00686   SmallVector<MachineOperand, 4> Cond;
00687   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
00688     return nullptr;
00689 
00690   // Avoid bugpoint weirdness: A block may end with a conditional branch but
00691   // jumps to the same MBB is either case. We have duplicate CFG edges in that
00692   // case that we can't handle. Since this never happens in properly optimized
00693   // code, just skip those edges.
00694   if (TBB && TBB == FBB) {
00695     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
00696                  << getNumber() << '\n');
00697     return nullptr;
00698   }
00699 
00700   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
00701   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
00702   DEBUG(dbgs() << "Splitting critical edge:"
00703         " BB#" << getNumber()
00704         << " -- BB#" << NMBB->getNumber()
00705         << " -- BB#" << Succ->getNumber() << '\n');
00706 
00707   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
00708   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
00709   if (LIS)
00710     LIS->insertMBBInMaps(NMBB);
00711   else if (Indexes)
00712     Indexes->insertMBBInMaps(NMBB);
00713 
00714   // On some targets like Mips, branches may kill virtual registers. Make sure
00715   // that LiveVariables is properly updated after updateTerminator replaces the
00716   // terminators.
00717   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
00718 
00719   // Collect a list of virtual registers killed by the terminators.
00720   SmallVector<unsigned, 4> KilledRegs;
00721   if (LV)
00722     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00723          I != E; ++I) {
00724       MachineInstr *MI = I;
00725       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
00726            OE = MI->operands_end(); OI != OE; ++OI) {
00727         if (!OI->isReg() || OI->getReg() == 0 ||
00728             !OI->isUse() || !OI->isKill() || OI->isUndef())
00729           continue;
00730         unsigned Reg = OI->getReg();
00731         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
00732             LV->getVarInfo(Reg).removeKill(MI)) {
00733           KilledRegs.push_back(Reg);
00734           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
00735           OI->setIsKill(false);
00736         }
00737       }
00738     }
00739 
00740   SmallVector<unsigned, 4> UsedRegs;
00741   if (LIS) {
00742     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00743          I != E; ++I) {
00744       MachineInstr *MI = I;
00745 
00746       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
00747            OE = MI->operands_end(); OI != OE; ++OI) {
00748         if (!OI->isReg() || OI->getReg() == 0)
00749           continue;
00750 
00751         unsigned Reg = OI->getReg();
00752         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
00753           UsedRegs.push_back(Reg);
00754       }
00755     }
00756   }
00757 
00758   ReplaceUsesOfBlockWith(Succ, NMBB);
00759 
00760   // If updateTerminator() removes instructions, we need to remove them from
00761   // SlotIndexes.
00762   SmallVector<MachineInstr*, 4> Terminators;
00763   if (Indexes) {
00764     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00765          I != E; ++I)
00766       Terminators.push_back(I);
00767   }
00768 
00769   updateTerminator();
00770 
00771   if (Indexes) {
00772     SmallVector<MachineInstr*, 4> NewTerminators;
00773     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00774          I != E; ++I)
00775       NewTerminators.push_back(I);
00776 
00777     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
00778         E = Terminators.end(); I != E; ++I) {
00779       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
00780           NewTerminators.end())
00781        Indexes->removeMachineInstrFromMaps(*I);
00782     }
00783   }
00784 
00785   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
00786   NMBB->addSuccessor(Succ);
00787   if (!NMBB->isLayoutSuccessor(Succ)) {
00788     Cond.clear();
00789     MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
00790                                                     dl);
00791 
00792     if (Indexes) {
00793       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
00794            I != E; ++I) {
00795         // Some instructions may have been moved to NMBB by updateTerminator(),
00796         // so we first remove any instruction that already has an index.
00797         if (Indexes->hasIndex(I))
00798           Indexes->removeMachineInstrFromMaps(I);
00799         Indexes->insertMachineInstrInMaps(I);
00800       }
00801     }
00802   }
00803 
00804   // Fix PHI nodes in Succ so they refer to NMBB instead of this
00805   for (MachineBasicBlock::instr_iterator
00806          i = Succ->instr_begin(),e = Succ->instr_end();
00807        i != e && i->isPHI(); ++i)
00808     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
00809       if (i->getOperand(ni+1).getMBB() == this)
00810         i->getOperand(ni+1).setMBB(NMBB);
00811 
00812   // Inherit live-ins from the successor
00813   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
00814          E = Succ->livein_end(); I != E; ++I)
00815     NMBB->addLiveIn(*I);
00816 
00817   // Update LiveVariables.
00818   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00819   if (LV) {
00820     // Restore kills of virtual registers that were killed by the terminators.
00821     while (!KilledRegs.empty()) {
00822       unsigned Reg = KilledRegs.pop_back_val();
00823       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
00824         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
00825           continue;
00826         if (TargetRegisterInfo::isVirtualRegister(Reg))
00827           LV->getVarInfo(Reg).Kills.push_back(I);
00828         DEBUG(dbgs() << "Restored terminator kill: " << *I);
00829         break;
00830       }
00831     }
00832     // Update relevant live-through information.
00833     LV->addNewBlock(NMBB, this, Succ);
00834   }
00835 
00836   if (LIS) {
00837     // After splitting the edge and updating SlotIndexes, live intervals may be
00838     // in one of two situations, depending on whether this block was the last in
00839     // the function. If the original block was the last in the function, all live
00840     // intervals will end prior to the beginning of the new split block. If the
00841     // original block was not at the end of the function, all live intervals will
00842     // extend to the end of the new split block.
00843 
00844     bool isLastMBB =
00845       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
00846 
00847     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
00848     SlotIndex PrevIndex = StartIndex.getPrevSlot();
00849     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
00850 
00851     // Find the registers used from NMBB in PHIs in Succ.
00852     SmallSet<unsigned, 8> PHISrcRegs;
00853     for (MachineBasicBlock::instr_iterator
00854          I = Succ->instr_begin(), E = Succ->instr_end();
00855          I != E && I->isPHI(); ++I) {
00856       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
00857         if (I->getOperand(ni+1).getMBB() == NMBB) {
00858           MachineOperand &MO = I->getOperand(ni);
00859           unsigned Reg = MO.getReg();
00860           PHISrcRegs.insert(Reg);
00861           if (MO.isUndef())
00862             continue;
00863 
00864           LiveInterval &LI = LIS->getInterval(Reg);
00865           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
00866           assert(VNI && "PHI sources should be live out of their predecessors.");
00867           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
00868         }
00869       }
00870     }
00871 
00872     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
00873     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00874       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00875       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
00876         continue;
00877 
00878       LiveInterval &LI = LIS->getInterval(Reg);
00879       if (!LI.liveAt(PrevIndex))
00880         continue;
00881 
00882       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
00883       if (isLiveOut && isLastMBB) {
00884         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
00885         assert(VNI && "LiveInterval should have VNInfo where it is live.");
00886         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
00887       } else if (!isLiveOut && !isLastMBB) {
00888         LI.removeSegment(StartIndex, EndIndex);
00889       }
00890     }
00891 
00892     // Update all intervals for registers whose uses may have been modified by
00893     // updateTerminator().
00894     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
00895   }
00896 
00897   if (MachineDominatorTree *MDT =
00898       P->getAnalysisIfAvailable<MachineDominatorTree>())
00899     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
00900 
00901   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
00902     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
00903       // If one or the other blocks were not in a loop, the new block is not
00904       // either, and thus LI doesn't need to be updated.
00905       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
00906         if (TIL == DestLoop) {
00907           // Both in the same loop, the NMBB joins loop.
00908           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
00909         } else if (TIL->contains(DestLoop)) {
00910           // Edge from an outer loop to an inner loop.  Add to the outer loop.
00911           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
00912         } else if (DestLoop->contains(TIL)) {
00913           // Edge from an inner loop to an outer loop.  Add to the outer loop.
00914           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
00915         } else {
00916           // Edge from two loops with no containment relation.  Because these
00917           // are natural loops, we know that the destination block must be the
00918           // header of its loop (adding a branch into a loop elsewhere would
00919           // create an irreducible loop).
00920           assert(DestLoop->getHeader() == Succ &&
00921                  "Should not create irreducible loops!");
00922           if (MachineLoop *P = DestLoop->getParentLoop())
00923             P->addBasicBlockToLoop(NMBB, MLI->getBase());
00924         }
00925       }
00926     }
00927 
00928   return NMBB;
00929 }
00930 
00931 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
00932 /// neighboring instructions so the bundle won't be broken by removing MI.
00933 static void unbundleSingleMI(MachineInstr *MI) {
00934   // Removing the first instruction in a bundle.
00935   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
00936     MI->unbundleFromSucc();
00937   // Removing the last instruction in a bundle.
00938   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
00939     MI->unbundleFromPred();
00940   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
00941   // are already fine.
00942 }
00943 
00944 MachineBasicBlock::instr_iterator
00945 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
00946   unbundleSingleMI(I);
00947   return Insts.erase(I);
00948 }
00949 
00950 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
00951   unbundleSingleMI(MI);
00952   MI->clearFlag(MachineInstr::BundledPred);
00953   MI->clearFlag(MachineInstr::BundledSucc);
00954   return Insts.remove(MI);
00955 }
00956 
00957 MachineBasicBlock::instr_iterator
00958 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
00959   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
00960          "Cannot insert instruction with bundle flags");
00961   // Set the bundle flags when inserting inside a bundle.
00962   if (I != instr_end() && I->isBundledWithPred()) {
00963     MI->setFlag(MachineInstr::BundledPred);
00964     MI->setFlag(MachineInstr::BundledSucc);
00965   }
00966   return Insts.insert(I, MI);
00967 }
00968 
00969 /// removeFromParent - This method unlinks 'this' from the containing function,
00970 /// and returns it, but does not delete it.
00971 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
00972   assert(getParent() && "Not embedded in a function!");
00973   getParent()->remove(this);
00974   return this;
00975 }
00976 
00977 
00978 /// eraseFromParent - This method unlinks 'this' from the containing function,
00979 /// and deletes it.
00980 void MachineBasicBlock::eraseFromParent() {
00981   assert(getParent() && "Not embedded in a function!");
00982   getParent()->erase(this);
00983 }
00984 
00985 
00986 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
00987 /// 'Old', change the code and CFG so that it branches to 'New' instead.
00988 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
00989                                                MachineBasicBlock *New) {
00990   assert(Old != New && "Cannot replace self with self!");
00991 
00992   MachineBasicBlock::instr_iterator I = instr_end();
00993   while (I != instr_begin()) {
00994     --I;
00995     if (!I->isTerminator()) break;
00996 
00997     // Scan the operands of this machine instruction, replacing any uses of Old
00998     // with New.
00999     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01000       if (I->getOperand(i).isMBB() &&
01001           I->getOperand(i).getMBB() == Old)
01002         I->getOperand(i).setMBB(New);
01003   }
01004 
01005   // Update the successor information.
01006   replaceSuccessor(Old, New);
01007 }
01008 
01009 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
01010 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
01011 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
01012 /// null.
01013 ///
01014 /// Besides DestA and DestB, retain other edges leading to LandingPads
01015 /// (currently there can be only one; we don't check or require that here).
01016 /// Note it is possible that DestA and/or DestB are LandingPads.
01017 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
01018                                              MachineBasicBlock *DestB,
01019                                              bool isCond) {
01020   // The values of DestA and DestB frequently come from a call to the
01021   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
01022   // values from there.
01023   //
01024   // 1. If both DestA and DestB are null, then the block ends with no branches
01025   //    (it falls through to its successor).
01026   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
01027   //    with only an unconditional branch.
01028   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
01029   //    with a conditional branch that falls through to a successor (DestB).
01030   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
01031   //    conditional branch followed by an unconditional branch. DestA is the
01032   //    'true' destination and DestB is the 'false' destination.
01033 
01034   bool Changed = false;
01035 
01036   MachineFunction::iterator FallThru =
01037     std::next(MachineFunction::iterator(this));
01038 
01039   if (!DestA && !DestB) {
01040     // Block falls through to successor.
01041     DestA = FallThru;
01042     DestB = FallThru;
01043   } else if (DestA && !DestB) {
01044     if (isCond)
01045       // Block ends in conditional jump that falls through to successor.
01046       DestB = FallThru;
01047   } else {
01048     assert(DestA && DestB && isCond &&
01049            "CFG in a bad state. Cannot correct CFG edges");
01050   }
01051 
01052   // Remove superfluous edges. I.e., those which aren't destinations of this
01053   // basic block, duplicate edges, or landing pads.
01054   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
01055   MachineBasicBlock::succ_iterator SI = succ_begin();
01056   while (SI != succ_end()) {
01057     const MachineBasicBlock *MBB = *SI;
01058     if (!SeenMBBs.insert(MBB).second ||
01059         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
01060       // This is a superfluous edge, remove it.
01061       SI = removeSuccessor(SI);
01062       Changed = true;
01063     } else {
01064       ++SI;
01065     }
01066   }
01067 
01068   return Changed;
01069 }
01070 
01071 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
01072 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
01073 DebugLoc
01074 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
01075   DebugLoc DL;
01076   instr_iterator E = instr_end();
01077   if (MBBI == E)
01078     return DL;
01079 
01080   // Skip debug declarations, we don't want a DebugLoc from them.
01081   while (MBBI != E && MBBI->isDebugValue())
01082     MBBI++;
01083   if (MBBI != E)
01084     DL = MBBI->getDebugLoc();
01085   return DL;
01086 }
01087 
01088 /// getSuccWeight - Return weight of the edge from this block to MBB.
01089 ///
01090 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
01091   if (Weights.empty())
01092     return 0;
01093 
01094   return *getWeightIterator(Succ);
01095 }
01096 
01097 /// Set successor weight of a given iterator.
01098 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
01099   if (Weights.empty())
01100     return;
01101   *getWeightIterator(I) = weight;
01102 }
01103 
01104 /// getWeightIterator - Return wight iterator corresonding to the I successor
01105 /// iterator
01106 MachineBasicBlock::weight_iterator MachineBasicBlock::
01107 getWeightIterator(MachineBasicBlock::succ_iterator I) {
01108   assert(Weights.size() == Successors.size() && "Async weight list!");
01109   size_t index = std::distance(Successors.begin(), I);
01110   assert(index < Weights.size() && "Not a current successor!");
01111   return Weights.begin() + index;
01112 }
01113 
01114 /// getWeightIterator - Return wight iterator corresonding to the I successor
01115 /// iterator
01116 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
01117 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
01118   assert(Weights.size() == Successors.size() && "Async weight list!");
01119   const size_t index = std::distance(Successors.begin(), I);
01120   assert(index < Weights.size() && "Not a current successor!");
01121   return Weights.begin() + index;
01122 }
01123 
01124 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
01125 /// as of just before "MI".
01126 /// 
01127 /// Search is localised to a neighborhood of
01128 /// Neighborhood instructions before (searching for defs or kills) and N
01129 /// instructions after (searching just for defs) MI.
01130 MachineBasicBlock::LivenessQueryResult
01131 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
01132                                            unsigned Reg, MachineInstr *MI,
01133                                            unsigned Neighborhood) {
01134   unsigned N = Neighborhood;
01135   MachineBasicBlock *MBB = MI->getParent();
01136 
01137   // Start by searching backwards from MI, looking for kills, reads or defs.
01138 
01139   MachineBasicBlock::iterator I(MI);
01140   // If this is the first insn in the block, don't search backwards.
01141   if (I != MBB->begin()) {
01142     do {
01143       --I;
01144 
01145       MachineOperandIteratorBase::PhysRegInfo Analysis =
01146         MIOperands(I).analyzePhysReg(Reg, TRI);
01147 
01148       if (Analysis.Defines)
01149         // Outputs happen after inputs so they take precedence if both are
01150         // present.
01151         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
01152 
01153       if (Analysis.Kills || Analysis.Clobbers)
01154         // Register killed, so isn't live.
01155         return LQR_Dead;
01156 
01157       else if (Analysis.ReadsOverlap)
01158         // Defined or read without a previous kill - live.
01159         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
01160 
01161     } while (I != MBB->begin() && --N > 0);
01162   }
01163 
01164   // Did we get to the start of the block?
01165   if (I == MBB->begin()) {
01166     // If so, the register's state is definitely defined by the live-in state.
01167     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
01168          RAI.isValid(); ++RAI) {
01169       if (MBB->isLiveIn(*RAI))
01170         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
01171     }
01172 
01173     return LQR_Dead;
01174   }
01175 
01176   N = Neighborhood;
01177 
01178   // Try searching forwards from MI, looking for reads or defs.
01179   I = MachineBasicBlock::iterator(MI);
01180   // If this is the last insn in the block, don't search forwards.
01181   if (I != MBB->end()) {
01182     for (++I; I != MBB->end() && N > 0; ++I, --N) {
01183       MachineOperandIteratorBase::PhysRegInfo Analysis =
01184         MIOperands(I).analyzePhysReg(Reg, TRI);
01185 
01186       if (Analysis.ReadsOverlap)
01187         // Used, therefore must have been live.
01188         return (Analysis.Reads) ?
01189           LQR_Live : LQR_OverlappingLive;
01190 
01191       else if (Analysis.Clobbers || Analysis.Defines)
01192         // Defined (but not read) therefore cannot have been live.
01193         return LQR_Dead;
01194     }
01195   }
01196 
01197   // At this point we have no idea of the liveness of the register.
01198   return LQR_Unknown;
01199 }