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