LLVM API Documentation

BranchFolding.cpp

Go to the documentation of this file.
00001 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
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 // This pass forwards branches to unconditional branches to make them branch
00011 // directly to the target block.  This pass often results in dead MBB's, which
00012 // it then removes.
00013 //
00014 // Note that this pass must be run after register allocation, it cannot handle
00015 // SSA form.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "branchfolding"
00020 #include "llvm/CodeGen/Passes.h"
00021 #include "llvm/CodeGen/MachineModuleInfo.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00024 #include "llvm/CodeGen/RegisterScavenging.h"
00025 #include "llvm/Target/TargetInstrInfo.h"
00026 #include "llvm/Target/TargetMachine.h"
00027 #include "llvm/Target/TargetRegisterInfo.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/ADT/SmallSet.h"
00031 #include "llvm/ADT/Statistic.h"
00032 #include "llvm/ADT/STLExtras.h"
00033 #include <algorithm>
00034 using namespace llvm;
00035 
00036 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
00037 STATISTIC(NumBranchOpts, "Number of branches optimized");
00038 STATISTIC(NumTailMerge , "Number of block tails merged");
00039 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", 
00040                               cl::init(cl::BOU_UNSET), cl::Hidden);
00041 // Throttle for huge numbers of predecessors (compile speed problems)
00042 static cl::opt<unsigned>
00043 TailMergeThreshold("tail-merge-threshold", 
00044           cl::desc("Max number of predecessors to consider tail merging"),
00045           cl::init(150), cl::Hidden);
00046 
00047 namespace {
00048   struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
00049     static char ID;
00050     explicit BranchFolder(bool defaultEnableTailMerge) : 
00051       MachineFunctionPass(&ID) {
00052       switch (FlagEnableTailMerge) {
00053         case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
00054         case cl::BOU_TRUE: EnableTailMerge = true; break;
00055         case cl::BOU_FALSE: EnableTailMerge = false; break;
00056       }
00057     }
00058 
00059     virtual bool runOnMachineFunction(MachineFunction &MF);
00060     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
00061     const TargetInstrInfo *TII;
00062     MachineModuleInfo *MMI;
00063     bool MadeChange;
00064   private:
00065     // Tail Merging.
00066     bool EnableTailMerge;
00067     bool TailMergeBlocks(MachineFunction &MF);
00068     bool TryMergeBlocks(MachineBasicBlock* SuccBB,
00069                         MachineBasicBlock* PredBB);
00070     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
00071                                  MachineBasicBlock *NewDest);
00072     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
00073                                   MachineBasicBlock::iterator BBI1);
00074     unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
00075     void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
00076                                                 MachineBasicBlock* PredBB);
00077     unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
00078                                        unsigned maxCommonTailLength);
00079 
00080     typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
00081     typedef std::vector<MergePotentialsElt>::iterator MPIterator;
00082     std::vector<MergePotentialsElt> MergePotentials;
00083 
00084     typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
00085     std::vector<SameTailElt> SameTails;
00086 
00087     const TargetRegisterInfo *RegInfo;
00088     RegScavenger *RS;
00089     // Branch optzn.
00090     bool OptimizeBranches(MachineFunction &MF);
00091     void OptimizeBlock(MachineBasicBlock *MBB);
00092     void RemoveDeadBlock(MachineBasicBlock *MBB);
00093     bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
00094     
00095     bool CanFallThrough(MachineBasicBlock *CurBB);
00096     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
00097                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
00098                         const SmallVectorImpl<MachineOperand> &Cond);
00099   };
00100   char BranchFolder::ID = 0;
00101 }
00102 
00103 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) { 
00104       return new BranchFolder(DefaultEnableTailMerge); }
00105 
00106 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
00107 /// function, updating the CFG.
00108 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
00109   assert(MBB->pred_empty() && "MBB must be dead!");
00110   DOUT << "\nRemoving MBB: " << *MBB;
00111   
00112   MachineFunction *MF = MBB->getParent();
00113   // drop all successors.
00114   while (!MBB->succ_empty())
00115     MBB->removeSuccessor(MBB->succ_end()-1);
00116   
00117   // If there are any labels in the basic block, unregister them from
00118   // MachineModuleInfo.
00119   if (MMI && !MBB->empty()) {
00120     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
00121          I != E; ++I) {
00122       if (I->isLabel())
00123         // The label ID # is always operand #0, an immediate.
00124         MMI->InvalidateLabel(I->getOperand(0).getImm());
00125     }
00126   }
00127   
00128   // Remove the block.
00129   MF->erase(MBB);
00130 }
00131 
00132 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
00133 /// followed by terminators, and if the implicitly defined registers are not
00134 /// used by the terminators, remove those implicit_def's. e.g.
00135 /// BB1:
00136 ///   r0 = implicit_def
00137 ///   r1 = implicit_def
00138 ///   br
00139 /// This block can be optimized away later if the implicit instructions are
00140 /// removed.
00141 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
00142   SmallSet<unsigned, 4> ImpDefRegs;
00143   MachineBasicBlock::iterator I = MBB->begin();
00144   while (I != MBB->end()) {
00145     if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
00146       break;
00147     unsigned Reg = I->getOperand(0).getReg();
00148     ImpDefRegs.insert(Reg);
00149     for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
00150          unsigned SubReg = *SubRegs; ++SubRegs)
00151       ImpDefRegs.insert(SubReg);
00152     ++I;
00153   }
00154   if (ImpDefRegs.empty())
00155     return false;
00156 
00157   MachineBasicBlock::iterator FirstTerm = I;
00158   while (I != MBB->end()) {
00159     if (!TII->isUnpredicatedTerminator(I))
00160       return false;
00161     // See if it uses any of the implicitly defined registers.
00162     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00163       MachineOperand &MO = I->getOperand(i);
00164       if (!MO.isReg() || !MO.isUse())
00165         continue;
00166       unsigned Reg = MO.getReg();
00167       if (ImpDefRegs.count(Reg))
00168         return false;
00169     }
00170     ++I;
00171   }
00172 
00173   I = MBB->begin();
00174   while (I != FirstTerm) {
00175     MachineInstr *ImpDefMI = &*I;
00176     ++I;
00177     MBB->erase(ImpDefMI);
00178   }
00179 
00180   return true;
00181 }
00182 
00183 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
00184   TII = MF.getTarget().getInstrInfo();
00185   if (!TII) return false;
00186 
00187   RegInfo = MF.getTarget().getRegisterInfo();
00188 
00189   // Fix CFG.  The later algorithms expect it to be right.
00190   bool EverMadeChange = false;
00191   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
00192     MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
00193     SmallVector<MachineOperand, 4> Cond;
00194     if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
00195       EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
00196     EverMadeChange |= OptimizeImpDefsBlock(MBB);
00197   }
00198 
00199   RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
00200 
00201   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00202 
00203   bool MadeChangeThisIteration = true;
00204   while (MadeChangeThisIteration) {
00205     MadeChangeThisIteration = false;
00206     MadeChangeThisIteration |= TailMergeBlocks(MF);
00207     MadeChangeThisIteration |= OptimizeBranches(MF);
00208     EverMadeChange |= MadeChangeThisIteration;
00209   }
00210 
00211   // See if any jump tables have become mergable or dead as the code generator
00212   // did its thing.
00213   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
00214   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
00215   if (!JTs.empty()) {
00216     // Figure out how these jump tables should be merged.
00217     std::vector<unsigned> JTMapping;
00218     JTMapping.reserve(JTs.size());
00219     
00220     // We always keep the 0th jump table.
00221     JTMapping.push_back(0);
00222 
00223     // Scan the jump tables, seeing if there are any duplicates.  Note that this
00224     // is N^2, which should be fixed someday.
00225     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
00226       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
00227     
00228     // If a jump table was merge with another one, walk the function rewriting
00229     // references to jump tables to reference the new JT ID's.  Keep track of
00230     // whether we see a jump table idx, if not, we can delete the JT.
00231     BitVector JTIsLive(JTs.size());
00232     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
00233          BB != E; ++BB) {
00234       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
00235            I != E; ++I)
00236         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
00237           MachineOperand &Op = I->getOperand(op);
00238           if (!Op.isJTI()) continue;
00239           unsigned NewIdx = JTMapping[Op.getIndex()];
00240           Op.setIndex(NewIdx);
00241 
00242           // Remember that this JT is live.
00243           JTIsLive.set(NewIdx);
00244         }
00245     }
00246    
00247     // Finally, remove dead jump tables.  This happens either because the
00248     // indirect jump was unreachable (and thus deleted) or because the jump
00249     // table was merged with some other one.
00250     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
00251       if (!JTIsLive.test(i)) {
00252         JTI->RemoveJumpTable(i);
00253         EverMadeChange = true;
00254       }
00255   }
00256   
00257   delete RS;
00258   return EverMadeChange;
00259 }
00260 
00261 //===----------------------------------------------------------------------===//
00262 //  Tail Merging of Blocks
00263 //===----------------------------------------------------------------------===//
00264 
00265 /// HashMachineInstr - Compute a hash value for MI and its operands.
00266 static unsigned HashMachineInstr(const MachineInstr *MI) {
00267   unsigned Hash = MI->getOpcode();
00268   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00269     const MachineOperand &Op = MI->getOperand(i);
00270     
00271     // Merge in bits from the operand if easy.
00272     unsigned OperandHash = 0;
00273     switch (Op.getType()) {
00274     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
00275     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
00276     case MachineOperand::MO_MachineBasicBlock:
00277       OperandHash = Op.getMBB()->getNumber();
00278       break;
00279     case MachineOperand::MO_FrameIndex:
00280     case MachineOperand::MO_ConstantPoolIndex:
00281     case MachineOperand::MO_JumpTableIndex:
00282       OperandHash = Op.getIndex();
00283       break;
00284     case MachineOperand::MO_GlobalAddress:
00285     case MachineOperand::MO_ExternalSymbol:
00286       // Global address / external symbol are too hard, don't bother, but do
00287       // pull in the offset.
00288       OperandHash = Op.getOffset();
00289       break;
00290     default: break;
00291     }
00292     
00293     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
00294   }
00295   return Hash;
00296 }
00297 
00298 /// HashEndOfMBB - Hash the last few instructions in the MBB.  For blocks
00299 /// with no successors, we hash two instructions, because cross-jumping 
00300 /// only saves code when at least two instructions are removed (since a 
00301 /// branch must be inserted).  For blocks with a successor, one of the
00302 /// two blocks to be tail-merged will end with a branch already, so
00303 /// it gains to cross-jump even for one instruction.
00304 
00305 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
00306                              unsigned minCommonTailLength) {
00307   MachineBasicBlock::const_iterator I = MBB->end();
00308   if (I == MBB->begin())
00309     return 0;   // Empty MBB.
00310   
00311   --I;
00312   unsigned Hash = HashMachineInstr(I);
00313     
00314   if (I == MBB->begin() || minCommonTailLength == 1)
00315     return Hash;   // Single instr MBB.
00316   
00317   --I;
00318   // Hash in the second-to-last instruction.
00319   Hash ^= HashMachineInstr(I) << 2;
00320   return Hash;
00321 }
00322 
00323 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
00324 /// of instructions they actually have in common together at their end.  Return
00325 /// iterators for the first shared instruction in each block.
00326 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
00327                                         MachineBasicBlock *MBB2,
00328                                         MachineBasicBlock::iterator &I1,
00329                                         MachineBasicBlock::iterator &I2) {
00330   I1 = MBB1->end();
00331   I2 = MBB2->end();
00332   
00333   unsigned TailLen = 0;
00334   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
00335     --I1; --I2;
00336     if (!I1->isIdenticalTo(I2) || 
00337         // FIXME: This check is dubious. It's used to get around a problem where
00338         // people incorrectly expect inline asm directives to remain in the same
00339         // relative order. This is untenable because normal compiler
00340         // optimizations (like this one) may reorder and/or merge these
00341         // directives.
00342         I1->getOpcode() == TargetInstrInfo::INLINEASM) {
00343       ++I1; ++I2;
00344       break;
00345     }
00346     ++TailLen;
00347   }
00348   return TailLen;
00349 }
00350 
00351 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
00352 /// after it, replacing it with an unconditional branch to NewDest.  This
00353 /// returns true if OldInst's block is modified, false if NewDest is modified.
00354 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
00355                                            MachineBasicBlock *NewDest) {
00356   MachineBasicBlock *OldBB = OldInst->getParent();
00357   
00358   // Remove all the old successors of OldBB from the CFG.
00359   while (!OldBB->succ_empty())
00360     OldBB->removeSuccessor(OldBB->succ_begin());
00361   
00362   // Remove all the dead instructions from the end of OldBB.
00363   OldBB->erase(OldInst, OldBB->end());
00364 
00365   // If OldBB isn't immediately before OldBB, insert a branch to it.
00366   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
00367     TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
00368   OldBB->addSuccessor(NewDest);
00369   ++NumTailMerge;
00370 }
00371 
00372 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
00373 /// MBB so that the part before the iterator falls into the part starting at the
00374 /// iterator.  This returns the new MBB.
00375 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
00376                                             MachineBasicBlock::iterator BBI1) {
00377   MachineFunction &MF = *CurMBB.getParent();
00378 
00379   // Create the fall-through block.
00380   MachineFunction::iterator MBBI = &CurMBB;
00381   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
00382   CurMBB.getParent()->insert(++MBBI, NewMBB);
00383 
00384   // Move all the successors of this block to the specified block.
00385   NewMBB->transferSuccessors(&CurMBB);
00386  
00387   // Add an edge from CurMBB to NewMBB for the fall-through.
00388   CurMBB.addSuccessor(NewMBB);
00389   
00390   // Splice the code over.
00391   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
00392 
00393   // For targets that use the register scavenger, we must maintain LiveIns.
00394   if (RS) {
00395     RS->enterBasicBlock(&CurMBB);
00396     if (!CurMBB.empty())
00397       RS->forward(prior(CurMBB.end()));
00398     BitVector RegsLiveAtExit(RegInfo->getNumRegs());
00399     RS->getRegsUsed(RegsLiveAtExit, false);
00400     for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
00401       if (RegsLiveAtExit[i])
00402         NewMBB->addLiveIn(i);
00403   }
00404 
00405   return NewMBB;
00406 }
00407 
00408 /// EstimateRuntime - Make a rough estimate for how long it will take to run
00409 /// the specified code.
00410 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
00411                                 MachineBasicBlock::iterator E) {
00412   unsigned Time = 0;
00413   for (; I != E; ++I) {
00414     const TargetInstrDesc &TID = I->getDesc();
00415     if (TID.isCall())
00416       Time += 10;
00417     else if (TID.mayLoad() || TID.mayStore())
00418       Time += 2;
00419     else
00420       ++Time;
00421   }
00422   return Time;
00423 }
00424 
00425 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
00426 // branches temporarily for tail merging).  In the case where CurMBB ends
00427 // with a conditional branch to the next block, optimize by reversing the
00428 // test and conditionally branching to SuccMBB instead.
00429 
00430 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
00431                     const TargetInstrInfo *TII) {
00432   MachineFunction *MF = CurMBB->getParent();
00433   MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
00434   MachineBasicBlock *TBB = 0, *FBB = 0;
00435   SmallVector<MachineOperand, 4> Cond;
00436   if (I != MF->end() &&
00437       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
00438     MachineBasicBlock *NextBB = I;
00439     if (TBB == NextBB && !Cond.empty() && !FBB) {
00440       if (!TII->ReverseBranchCondition(Cond)) {
00441         TII->RemoveBranch(*CurMBB);
00442         TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
00443         return;
00444       }
00445     }
00446   }
00447   TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
00448 }
00449 
00450 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
00451                          const std::pair<unsigned,MachineBasicBlock*> &q) {
00452     if (p.first < q.first)
00453       return true;
00454      else if (p.first > q.first)
00455       return false;
00456     else if (p.second->getNumber() < q.second->getNumber())
00457       return true;
00458     else if (p.second->getNumber() > q.second->getNumber())
00459       return false;
00460     else {
00461       // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
00462       // an object with itself.
00463 #ifndef _GLIBCXX_DEBUG
00464       assert(0 && "Predecessor appears twice");
00465 #endif
00466       return false;
00467     }
00468 }
00469 
00470 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
00471 /// hash CurHash (guaranteed to match the last element).   Build the vector 
00472 /// SameTails of all those that have the (same) largest number of instructions
00473 /// in common of any pair of these blocks.  SameTails entries contain an
00474 /// iterator into MergePotentials (from which the MachineBasicBlock can be 
00475 /// found) and a MachineBasicBlock::iterator into that MBB indicating the 
00476 /// instruction where the matching code sequence begins.
00477 /// Order of elements in SameTails is the reverse of the order in which
00478 /// those blocks appear in MergePotentials (where they are not necessarily
00479 /// consecutive).
00480 unsigned BranchFolder::ComputeSameTails(unsigned CurHash, 
00481                                         unsigned minCommonTailLength) {
00482   unsigned maxCommonTailLength = 0U;
00483   SameTails.clear();
00484   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
00485   MPIterator HighestMPIter = prior(MergePotentials.end());
00486   for (MPIterator CurMPIter = prior(MergePotentials.end()),
00487                   B = MergePotentials.begin(); 
00488        CurMPIter!=B && CurMPIter->first==CurHash;
00489        --CurMPIter) {
00490     for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
00491       unsigned CommonTailLen = ComputeCommonTailLength(
00492                                         CurMPIter->second,
00493                                         I->second,
00494                                         TrialBBI1, TrialBBI2);
00495       // If we will have to split a block, there should be at least
00496       // minCommonTailLength instructions in common; if not, at worst
00497       // we will be replacing a fallthrough into the common tail with a
00498       // branch, which at worst breaks even with falling through into
00499       // the duplicated common tail, so 1 instruction in common is enough.
00500       // We will always pick a block we do not have to split as the common
00501       // tail if there is one.
00502       // (Empty blocks will get forwarded and need not be considered.)
00503       if (CommonTailLen >= minCommonTailLength ||
00504           (CommonTailLen > 0 &&
00505            (TrialBBI1==CurMPIter->second->begin() ||
00506             TrialBBI2==I->second->begin()))) {
00507         if (CommonTailLen > maxCommonTailLength) {
00508           SameTails.clear();
00509           maxCommonTailLength = CommonTailLen;
00510           HighestMPIter = CurMPIter;
00511           SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
00512         }
00513         if (HighestMPIter == CurMPIter &&
00514             CommonTailLen == maxCommonTailLength)
00515           SameTails.push_back(std::make_pair(I, TrialBBI2));
00516       }
00517       if (I==B)
00518         break;
00519     }
00520   }
00521   return maxCommonTailLength;
00522 }
00523 
00524 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
00525 /// MergePotentials, restoring branches at ends of blocks as appropriate.
00526 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash, 
00527                                         MachineBasicBlock* SuccBB,
00528                                         MachineBasicBlock* PredBB) {
00529   MPIterator CurMPIter, B;
00530   for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin(); 
00531        CurMPIter->first==CurHash;
00532        --CurMPIter) {
00533     // Put the unconditional branch back, if we need one.
00534     MachineBasicBlock *CurMBB = CurMPIter->second;
00535     if (SuccBB && CurMBB != PredBB)
00536       FixTail(CurMBB, SuccBB, TII);
00537     if (CurMPIter==B)
00538       break;
00539   }
00540   if (CurMPIter->first!=CurHash)
00541     CurMPIter++;
00542   MergePotentials.erase(CurMPIter, MergePotentials.end());
00543 }
00544 
00545 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
00546 /// only of the common tail.  Create a block that does by splitting one.
00547 unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
00548                                              unsigned maxCommonTailLength) {
00549   unsigned i, commonTailIndex;
00550   unsigned TimeEstimate = ~0U;
00551   for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
00552     // Use PredBB if possible; that doesn't require a new branch.
00553     if (SameTails[i].first->second==PredBB) {
00554       commonTailIndex = i;
00555       break;
00556     }
00557     // Otherwise, make a (fairly bogus) choice based on estimate of
00558     // how long it will take the various blocks to execute.
00559     unsigned t = EstimateRuntime(SameTails[i].first->second->begin(), 
00560                                  SameTails[i].second);
00561     if (t<=TimeEstimate) {
00562       TimeEstimate = t;
00563       commonTailIndex = i;
00564     }
00565   }
00566 
00567   MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
00568   MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
00569 
00570   DOUT << "\nSplitting " << MBB->getNumber() << ", size " << 
00571           maxCommonTailLength;
00572 
00573   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
00574   SameTails[commonTailIndex].first->second = newMBB;
00575   SameTails[commonTailIndex].second = newMBB->begin();
00576   // If we split PredBB, newMBB is the new predecessor.
00577   if (PredBB==MBB)
00578     PredBB = newMBB;
00579 
00580   return commonTailIndex;
00581 }
00582 
00583 // See if any of the blocks in MergePotentials (which all have a common single
00584 // successor, or all have no successor) can be tail-merged.  If there is a
00585 // successor, any blocks in MergePotentials that are not tail-merged and
00586 // are not immediately before Succ must have an unconditional branch to
00587 // Succ added (but the predecessor/successor lists need no adjustment).  
00588 // The lone predecessor of Succ that falls through into Succ,
00589 // if any, is given in PredBB.
00590 
00591 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
00592                                   MachineBasicBlock* PredBB) {
00593   // It doesn't make sense to save a single instruction since tail merging
00594   // will add a jump.
00595   // FIXME: Ask the target to provide the threshold?
00596   unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
00597   MadeChange = false;
00598   
00599   DOUT << "\nTryMergeBlocks " << MergePotentials.size() << '\n';
00600 
00601   // Sort by hash value so that blocks with identical end sequences sort
00602   // together.
00603   std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
00604 
00605   // Walk through equivalence sets looking for actual exact matches.
00606   while (MergePotentials.size() > 1) {
00607     unsigned CurHash  = prior(MergePotentials.end())->first;
00608     
00609     // Build SameTails, identifying the set of blocks with this hash code
00610     // and with the maximum number of instructions in common.
00611     unsigned maxCommonTailLength = ComputeSameTails(CurHash, 
00612                                                     minCommonTailLength);
00613 
00614     // If we didn't find any pair that has at least minCommonTailLength 
00615     // instructions in common, remove all blocks with this hash code and retry.
00616     if (SameTails.empty()) {
00617       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
00618       continue;
00619     }
00620 
00621     // If one of the blocks is the entire common tail (and not the entry
00622     // block, which we can't jump to), we can treat all blocks with this same
00623     // tail at once.  Use PredBB if that is one of the possibilities, as that
00624     // will not introduce any extra branches.
00625     MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
00626                                 getParent()->begin();
00627     unsigned int commonTailIndex, i;
00628     for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
00629       MachineBasicBlock *MBB = SameTails[i].first->second;
00630       if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
00631         commonTailIndex = i;
00632         if (MBB==PredBB)
00633           break;
00634       }
00635     }
00636 
00637     if (commonTailIndex==SameTails.size()) {
00638       // None of the blocks consist entirely of the common tail.
00639       // Split a block so that one does.
00640       commonTailIndex = CreateCommonTailOnlyBlock(PredBB,  maxCommonTailLength);
00641     }
00642 
00643     MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
00644     // MBB is common tail.  Adjust all other BB's to jump to this one.
00645     // Traversal must be forwards so erases work.
00646     DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
00647     for (unsigned int i=0; i<SameTails.size(); ++i) {
00648       if (commonTailIndex==i)
00649         continue;
00650       DOUT << SameTails[i].first->second->getNumber() << ",";
00651       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
00652       ReplaceTailWithBranchTo(SameTails[i].second, MBB);
00653       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
00654       MergePotentials.erase(SameTails[i].first);
00655     }
00656     DOUT << "\n";
00657     // We leave commonTailIndex in the worklist in case there are other blocks
00658     // that match it with a smaller number of instructions.
00659     MadeChange = true;
00660   }
00661   return MadeChange;
00662 }
00663 
00664 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
00665 
00666   if (!EnableTailMerge) return false;
00667  
00668   MadeChange = false;
00669 
00670   // First find blocks with no successors.
00671   MergePotentials.clear();
00672   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
00673     if (I->succ_empty())
00674       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
00675   }
00676   // See if we can do any tail merging on those.
00677   if (MergePotentials.size() < TailMergeThreshold &&
00678       MergePotentials.size() >= 2)
00679     MadeChange |= TryMergeBlocks(NULL, NULL);
00680 
00681   // Look at blocks (IBB) with multiple predecessors (PBB).
00682   // We change each predecessor to a canonical form, by
00683   // (1) temporarily removing any unconditional branch from the predecessor
00684   // to IBB, and
00685   // (2) alter conditional branches so they branch to the other block
00686   // not IBB; this may require adding back an unconditional branch to IBB 
00687   // later, where there wasn't one coming in.  E.g.
00688   //   Bcc IBB
00689   //   fallthrough to QBB
00690   // here becomes
00691   //   Bncc QBB
00692   // with a conceptual B to IBB after that, which never actually exists.
00693   // With those changes, we see whether the predecessors' tails match,
00694   // and merge them if so.  We change things out of canonical form and
00695   // back to the way they were later in the process.  (OptimizeBranches
00696   // would undo some of this, but we can't use it, because we'd get into
00697   // a compile-time infinite loop repeatedly doing and undoing the same
00698   // transformations.)
00699 
00700   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
00701     if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
00702       MachineBasicBlock *IBB = I;
00703       MachineBasicBlock *PredBB = prior(I);
00704       MergePotentials.clear();
00705       for (MachineBasicBlock::pred_iterator P = I->pred_begin(), 
00706                                             E2 = I->pred_end();
00707            P != E2; ++P) {
00708         MachineBasicBlock* PBB = *P;
00709         // Skip blocks that loop to themselves, can't tail merge these.
00710         if (PBB==IBB)
00711           continue;
00712         MachineBasicBlock *TBB = 0, *FBB = 0;
00713         SmallVector<MachineOperand, 4> Cond;
00714         if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
00715           // Failing case:  IBB is the target of a cbr, and
00716           // we cannot reverse the branch.
00717           SmallVector<MachineOperand, 4> NewCond(Cond);
00718           if (!Cond.empty() && TBB==IBB) {
00719             if (TII->ReverseBranchCondition(NewCond))
00720               continue;
00721             // This is the QBB case described above
00722             if (!FBB)
00723               FBB = next(MachineFunction::iterator(PBB));
00724           }
00725           // Failing case:  the only way IBB can be reached from PBB is via
00726           // exception handling.  Happens for landing pads.  Would be nice
00727           // to have a bit in the edge so we didn't have to do all this.
00728           if (IBB->isLandingPad()) {
00729             MachineFunction::iterator IP = PBB;  IP++;
00730             MachineBasicBlock* PredNextBB = NULL;
00731             if (IP!=MF.end())
00732               PredNextBB = IP;
00733             if (TBB==NULL) {
00734               if (IBB!=PredNextBB)      // fallthrough
00735                 continue;
00736             } else if (FBB) {
00737               if (TBB!=IBB && FBB!=IBB)   // cbr then ubr
00738                 continue;
00739             } else if (Cond.empty()) {
00740               if (TBB!=IBB)               // ubr
00741                 continue;
00742             } else {
00743               if (TBB!=IBB && IBB!=PredNextBB)  // cbr
00744                 continue;
00745             }
00746           }
00747           // Remove the unconditional branch at the end, if any.
00748           if (TBB && (Cond.empty() || FBB)) {
00749             TII->RemoveBranch(*PBB);
00750             if (!Cond.empty())
00751               // reinsert conditional branch only, for now
00752               TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
00753           }
00754           MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
00755         }
00756       }
00757     if (MergePotentials.size() >= 2)
00758       MadeChange |= TryMergeBlocks(I, PredBB);
00759     // Reinsert an unconditional branch if needed.
00760     // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
00761     PredBB = prior(I);      // this may have been changed in TryMergeBlocks
00762     if (MergePotentials.size()==1 && 
00763         MergePotentials.begin()->second != PredBB)
00764       FixTail(MergePotentials.begin()->second, I, TII);
00765     }
00766   }
00767   return MadeChange;
00768 }
00769 
00770 //===----------------------------------------------------------------------===//
00771 //  Branch Optimization
00772 //===----------------------------------------------------------------------===//
00773 
00774 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
00775   MadeChange = false;
00776   
00777   // Make sure blocks are numbered in order
00778   MF.RenumberBlocks();
00779 
00780   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
00781     MachineBasicBlock *MBB = I++;
00782     OptimizeBlock(MBB);
00783     
00784     // If it is dead, remove it.
00785     if (MBB->pred_empty()) {
00786       RemoveDeadBlock(MBB);
00787       MadeChange = true;
00788       ++NumDeadBlocks;
00789     }
00790   }
00791   return MadeChange;
00792 }
00793 
00794 
00795 /// CanFallThrough - Return true if the specified block (with the specified
00796 /// branch condition) can implicitly transfer control to the block after it by
00797 /// falling off the end of it.  This should return false if it can reach the
00798 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
00799 ///
00800 /// True is a conservative answer.
00801 ///
00802 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
00803                                   bool BranchUnAnalyzable,
00804                                   MachineBasicBlock *TBB, 
00805                                   MachineBasicBlock *FBB,
00806                                   const SmallVectorImpl<MachineOperand> &Cond) {
00807   MachineFunction::iterator Fallthrough = CurBB;
00808   ++Fallthrough;
00809   // If FallthroughBlock is off the end of the function, it can't fall through.
00810   if (Fallthrough == CurBB->getParent()->end())
00811     return false;
00812   
00813   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
00814   if (!CurBB->isSuccessor(Fallthrough))
00815     return false;
00816   
00817   // If we couldn't analyze the branch, assume it could fall through.
00818   if (BranchUnAnalyzable) return true;
00819   
00820   // If there is no branch, control always falls through.
00821   if (TBB == 0) return true;
00822 
00823   // If there is some explicit branch to the fallthrough block, it can obviously
00824   // reach, even though the branch should get folded to fall through implicitly.
00825   if (MachineFunction::iterator(TBB) == Fallthrough ||
00826       MachineFunction::iterator(FBB) == Fallthrough)
00827     return true;
00828   
00829   // If it's an unconditional branch to some block not the fall through, it 
00830   // doesn't fall through.
00831   if (Cond.empty()) return false;
00832   
00833   // Otherwise, if it is conditional and has no explicit false block, it falls
00834   // through.
00835   return FBB == 0;
00836 }
00837 
00838 /// CanFallThrough - Return true if the specified can implicitly transfer
00839 /// control to the block after it by falling off the end of it.  This should
00840 /// return false if it can reach the block after it, but it uses an explicit
00841 /// branch to do so (e.g. a table jump).
00842 ///
00843 /// True is a conservative answer.
00844 ///
00845 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
00846   MachineBasicBlock *TBB = 0, *FBB = 0;
00847   SmallVector<MachineOperand, 4> Cond;
00848   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
00849   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
00850 }
00851 
00852 /// IsBetterFallthrough - Return true if it would be clearly better to
00853 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
00854 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
00855 /// result in infinite loops.
00856 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
00857                                 MachineBasicBlock *MBB2) {
00858   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
00859   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
00860   // optimize branches that branch to either a return block or an assert block
00861   // into a fallthrough to the return.
00862   if (MBB1->empty() || MBB2->empty()) return false;
00863  
00864   // If there is a clear successor ordering we make sure that one block
00865   // will fall through to the next
00866   if (MBB1->isSuccessor(MBB2)) return true;
00867   if (MBB2->isSuccessor(MBB1)) return false;
00868 
00869   MachineInstr *MBB1I = --MBB1->end();
00870   MachineInstr *MBB2I = --MBB2->end();
00871   return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
00872 }
00873 
00874 /// OptimizeBlock - Analyze and optimize control flow related to the specified
00875 /// block.  This is never called on the entry block.
00876 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
00877   MachineFunction::iterator FallThrough = MBB;
00878   ++FallThrough;
00879   
00880   // If this block is empty, make everyone use its fall-through, not the block
00881   // explicitly.  Landing pads should not do this since the landing-pad table
00882   // points to this block.
00883   if (MBB->empty() && !MBB->isLandingPad()) {
00884     // Dead block?  Leave for cleanup later.
00885     if (MBB->pred_empty()) return;
00886     
00887     if (FallThrough == MBB->getParent()->end()) {
00888       // TODO: Simplify preds to not branch here if possible!
00889     } else {
00890       // Rewrite all predecessors of the old block to go to the fallthrough
00891       // instead.
00892       while (!MBB->pred_empty()) {
00893         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
00894         Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
00895       }
00896       
00897       // If MBB was the target of a jump table, update jump tables to go to the
00898       // fallthrough instead.
00899       MBB->getParent()->getJumpTableInfo()->
00900         ReplaceMBBInJumpTables(MBB, FallThrough);
00901       MadeChange = true;
00902     }
00903     return;
00904   }
00905 
00906   // Check to see if we can simplify the terminator of the block before this
00907   // one.
00908   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
00909 
00910   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
00911   SmallVector<MachineOperand, 4> PriorCond;
00912   bool PriorUnAnalyzable =
00913     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
00914   if (!PriorUnAnalyzable) {
00915     // If the CFG for the prior block has extra edges, remove them.
00916     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
00917                                               !PriorCond.empty());
00918     
00919     // If the previous branch is conditional and both conditions go to the same
00920     // destination, remove the branch, replacing it with an unconditional one or
00921     // a fall-through.
00922     if (PriorTBB && PriorTBB == PriorFBB) {
00923       TII->RemoveBranch(PrevBB);
00924       PriorCond.clear(); 
00925       if (PriorTBB != MBB)
00926         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
00927       MadeChange = true;
00928       ++NumBranchOpts;
00929       return OptimizeBlock(MBB);
00930     }
00931     
00932     // If the previous branch *only* branches to *this* block (conditional or
00933     // not) remove the branch.
00934     if (PriorTBB == MBB && PriorFBB == 0) {
00935       TII->RemoveBranch(PrevBB);
00936       MadeChange = true;
00937       ++NumBranchOpts;
00938       return OptimizeBlock(MBB);
00939     }
00940     
00941     // If the prior block branches somewhere else on the condition and here if
00942     // the condition is false, remove the uncond second branch.
00943     if (PriorFBB == MBB) {
00944       TII->RemoveBranch(PrevBB);
00945       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
00946       MadeChange = true;
00947       ++NumBranchOpts;
00948       return OptimizeBlock(MBB);
00949     }
00950     
00951     // If the prior block branches here on true and somewhere else on false, and
00952     // if the branch condition is reversible, reverse the branch to create a
00953     // fall-through.
00954     if (PriorTBB == MBB) {
00955       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
00956       if (!TII->ReverseBranchCondition(NewPriorCond)) {
00957         TII->RemoveBranch(PrevBB);
00958         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
00959         MadeChange = true;
00960         ++NumBranchOpts;
00961         return OptimizeBlock(MBB);
00962       }
00963     }
00964     
00965     // If this block doesn't fall through (e.g. it ends with an uncond branch or
00966     // has no successors) and if the pred falls through into this block, and if
00967     // it would otherwise fall through into the block after this, move this
00968     // block to the end of the function.
00969     //
00970     // We consider it more likely that execution will stay in the function (e.g.
00971     // due to loops) than it is to exit it.  This asserts in loops etc, moving
00972     // the assert condition out of the loop body.
00973     if (!PriorCond.empty() && PriorFBB == 0 &&
00974         MachineFunction::iterator(PriorTBB) == FallThrough &&
00975         !CanFallThrough(MBB)) {
00976       bool DoTransform = true;
00977       
00978       // We have to be careful that the succs of PredBB aren't both no-successor
00979       // blocks.  If neither have successors and if PredBB is the second from
00980       // last block in the function, we'd just keep swapping the two blocks for
00981       // last.  Only do the swap if one is clearly better to fall through than
00982       // the other.
00983       if (FallThrough == --MBB->getParent()->end() &&
00984           !IsBetterFallthrough(PriorTBB, MBB))
00985         DoTransform = false;
00986 
00987       // We don't want to do this transformation if we have control flow like:
00988       //   br cond BB2
00989       // BB1:
00990       //   ..
00991       //   jmp BBX
00992       // BB2:
00993       //   ..
00994       //   ret
00995       //
00996       // In this case, we could actually be moving the return block *into* a
00997       // loop!
00998       if (DoTransform && !MBB->succ_empty() &&
00999           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
01000         DoTransform = false;
01001       
01002       
01003       if (DoTransform) {
01004         // Reverse the branch so we will fall through on the previous true cond.
01005         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
01006         if (!TII->ReverseBranchCondition(NewPriorCond)) {
01007           DOUT << "\nMoving MBB: " << *MBB;
01008           DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
01009           
01010           TII->RemoveBranch(PrevBB);
01011           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
01012 
01013           // Move this block to the end of the function.
01014           MBB->moveAfter(--MBB->getParent()->end());
01015           MadeChange = true;
01016           ++NumBranchOpts;
01017           return;
01018         }
01019       }
01020     }
01021   }
01022   
01023   // Analyze the branch in the current block.
01024   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
01025   SmallVector<MachineOperand, 4> CurCond;
01026   bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
01027   if (!CurUnAnalyzable) {
01028     // If the CFG for the prior block has extra edges, remove them.
01029     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
01030 
01031     // If this is a two-way branch, and the FBB branches to this block, reverse 
01032     // the condition so the single-basic-block loop is faster.  Instead of:
01033     //    Loop: xxx; jcc Out; jmp Loop
01034     // we want:
01035     //    Loop: xxx; jncc Loop; jmp Out
01036     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
01037       SmallVector<MachineOperand, 4> NewCond(CurCond);
01038       if (!TII->ReverseBranchCondition(NewCond)) {
01039         TII->RemoveBranch(*MBB);
01040         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
01041         MadeChange = true;
01042         ++NumBranchOpts;
01043         return OptimizeBlock(MBB);
01044       }
01045     }
01046     
01047     
01048     // If this branch is the only thing in its block, see if we can forward
01049     // other blocks across it.
01050     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
01051         MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
01052       // This block may contain just an unconditional branch.  Because there can
01053       // be 'non-branch terminators' in the block, try removing the branch and
01054       // then seeing if the block is empty.
01055       TII->RemoveBranch(*MBB);
01056 
01057       // If this block is just an unconditional branch to CurTBB, we can
01058       // usually completely eliminate the block.  The only case we cannot
01059       // completely eliminate the block is when the block before this one
01060       // falls through into MBB and we can't understand the prior block's branch
01061       // condition.
01062       if (MBB->empty()) {
01063         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
01064         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
01065             !PrevBB.isSuccessor(MBB)) {
01066           // If the prior block falls through into us, turn it into an
01067           // explicit branch to us to make updates simpler.
01068           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
01069               PriorTBB != MBB && PriorFBB != MBB) {
01070             if (PriorTBB == 0) {
01071               assert(PriorCond.empty() && PriorFBB == 0 &&
01072                      "Bad branch analysis");
01073               PriorTBB = MBB;
01074             } else {
01075               assert(PriorFBB == 0 && "Machine CFG out of date!");
01076               PriorFBB = MBB;
01077             }
01078             TII->RemoveBranch(PrevBB);
01079             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
01080           }
01081 
01082           // Iterate through all the predecessors, revectoring each in-turn.
01083           size_t PI = 0;
01084           bool DidChange = false;
01085           bool HasBranchToSelf = false;
01086           while(PI != MBB->pred_size()) {
01087             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
01088             if (PMBB == MBB) {
01089               // If this block has an uncond branch to itself, leave it.
01090               ++PI;
01091               HasBranchToSelf = true;
01092             } else {
01093               DidChange = true;
01094               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
01095             }
01096           }
01097 
01098           // Change any jumptables to go to the new MBB.
01099           MBB->getParent()->getJumpTableInfo()->
01100             ReplaceMBBInJumpTables(MBB, CurTBB);
01101           if (DidChange) {
01102             ++NumBranchOpts;
01103             MadeChange = true;
01104             if (!HasBranchToSelf) return;
01105           }
01106         }
01107       }
01108       
01109       // Add the branch back if the block is more than just an uncond branch.
01110       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
01111     }
01112   }
01113 
01114   // If the prior block doesn't fall through into this block, and if this
01115   // block doesn't fall through into some other block, see if we can find a
01116   // place to move this block where a fall-through will happen.
01117   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
01118                       PriorTBB, PriorFBB, PriorCond)) {
01119     // Now we know that there was no fall-through into this block, check to
01120     // see if it has a fall-through into its successor.
01121     bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, 
01122                                        CurCond);
01123 
01124     if (!MBB->isLandingPad()) {
01125       // Check all the predecessors of this block.  If one of them has no fall
01126       // throughs, move this block right after it.
01127       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
01128            E = MBB->pred_end(); PI != E; ++PI) {
01129         // Analyze the branch at the end of the pred.
01130         MachineBasicBlock *PredBB = *PI;
01131         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
01132         if (PredBB != MBB && !CanFallThrough(PredBB)
01133             && (!CurFallsThru || !CurTBB || !CurFBB)
01134             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
01135           // If the current block doesn't fall through, just move it.
01136           // If the current block can fall through and does not end with a
01137           // conditional branch, we need to append an unconditional jump to 
01138           // the (current) next block.  To avoid a possible compile-time
01139           // infinite loop, move blocks only backward in this case.
01140           // Also, if there are already 2 branches here, we cannot add a third;
01141           // this means we have the case
01142           // Bcc next
01143           // B elsewhere
01144           // next:
01145           if (CurFallsThru) {
01146             MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
01147             CurCond.clear();
01148             TII->InsertBranch(*MBB, NextBB, 0, CurCond);
01149           }
01150           MBB->moveAfter(PredBB);
01151           MadeChange = true;
01152           return OptimizeBlock(MBB);
01153         }
01154       }
01155     }
01156         
01157     if (!CurFallsThru) {
01158       // Check all successors to see if we can move this block before it.
01159       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
01160            E = MBB->succ_end(); SI != E; ++SI) {
01161         // Analyze the branch at the end of the block before the succ.
01162         MachineBasicBlock *SuccBB = *SI;
01163         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
01164         std::vector<MachineOperand> SuccPrevCond;
01165         
01166         // If this block doesn't already fall-through to that successor, and if
01167         // the succ doesn't already have a block that can fall through into it,
01168         // and if the successor isn't an EH destination, we can arrange for the
01169         // fallthrough to happen.
01170         if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
01171             !SuccBB->isLandingPad()) {
01172           MBB->moveBefore(SuccBB);
01173           MadeChange = true;
01174           return OptimizeBlock(MBB);
01175         }
01176       }
01177       
01178       // Okay, there is no really great place to put this block.  If, however,
01179       // the block before this one would be a fall-through if this block were
01180       // removed, move this block to the end of the function.
01181       if (FallThrough != MBB->getParent()->end() &&
01182           PrevBB.isSuccessor(FallThrough)) {
01183         MBB->moveAfter(--MBB->getParent()->end());
01184         MadeChange = true;
01185         return;
01186       }
01187     }
01188   }
01189 }