dd51d5f6f642ecba8c3659b147e044ff3eddd775
[oota-llvm.git] / lib / CodeGen / BranchFolding.cpp
1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block.  This pass often results in dead MBB's, which
12 // it then removes.
13 //
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "branchfolding"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 using namespace llvm;
37
38 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
39 STATISTIC(NumBranchOpts, "Number of branches optimized");
40 STATISTIC(NumTailMerge , "Number of block tails merged");
41 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge", 
42                               cl::init(cl::BOU_UNSET), cl::Hidden);
43 // Throttle for huge numbers of predecessors (compile speed problems)
44 static cl::opt<unsigned>
45 TailMergeThreshold("tail-merge-threshold", 
46           cl::desc("Max number of predecessors to consider tail merging"),
47           cl::init(150), cl::Hidden);
48
49 namespace {
50   struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
51     static char ID;
52     explicit BranchFolder(bool defaultEnableTailMerge) : 
53       MachineFunctionPass(&ID) {
54       switch (FlagEnableTailMerge) {
55         case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
56         case cl::BOU_TRUE: EnableTailMerge = true; break;
57         case cl::BOU_FALSE: EnableTailMerge = false; break;
58       }
59     }
60
61     virtual bool runOnMachineFunction(MachineFunction &MF);
62     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
63     const TargetInstrInfo *TII;
64     MachineModuleInfo *MMI;
65     bool MadeChange;
66   private:
67     // Tail Merging.
68     bool EnableTailMerge;
69     bool TailMergeBlocks(MachineFunction &MF);
70     bool TryMergeBlocks(MachineBasicBlock* SuccBB,
71                         MachineBasicBlock* PredBB);
72     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
73                                  MachineBasicBlock *NewDest);
74     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
75                                   MachineBasicBlock::iterator BBI1);
76     unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
77     void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
78                                                 MachineBasicBlock* PredBB);
79     unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
80                                        unsigned maxCommonTailLength);
81
82     typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
83     typedef std::vector<MergePotentialsElt>::iterator MPIterator;
84     std::vector<MergePotentialsElt> MergePotentials;
85
86     typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
87     std::vector<SameTailElt> SameTails;
88
89     const TargetRegisterInfo *RegInfo;
90     RegScavenger *RS;
91     // Branch optzn.
92     bool OptimizeBranches(MachineFunction &MF);
93     void OptimizeBlock(MachineBasicBlock *MBB);
94     void RemoveDeadBlock(MachineBasicBlock *MBB);
95     bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
96     
97     bool CanFallThrough(MachineBasicBlock *CurBB);
98     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
99                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
100                         const SmallVectorImpl<MachineOperand> &Cond);
101   };
102   char BranchFolder::ID = 0;
103 }
104
105 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) { 
106   return new BranchFolder(DefaultEnableTailMerge);
107 }
108
109 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
110 /// function, updating the CFG.
111 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
112   assert(MBB->pred_empty() && "MBB must be dead!");
113   DEBUG(errs() << "\nRemoving MBB: " << *MBB);
114   
115   MachineFunction *MF = MBB->getParent();
116   // drop all successors.
117   while (!MBB->succ_empty())
118     MBB->removeSuccessor(MBB->succ_end()-1);
119   
120   // If there are any labels in the basic block, unregister them from
121   // MachineModuleInfo.
122   if (MMI && !MBB->empty()) {
123     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
124          I != E; ++I) {
125       if (I->isLabel())
126         // The label ID # is always operand #0, an immediate.
127         MMI->InvalidateLabel(I->getOperand(0).getImm());
128     }
129   }
130   
131   // Remove the block.
132   MF->erase(MBB);
133 }
134
135 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
136 /// followed by terminators, and if the implicitly defined registers are not
137 /// used by the terminators, remove those implicit_def's. e.g.
138 /// BB1:
139 ///   r0 = implicit_def
140 ///   r1 = implicit_def
141 ///   br
142 /// This block can be optimized away later if the implicit instructions are
143 /// removed.
144 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
145   SmallSet<unsigned, 4> ImpDefRegs;
146   MachineBasicBlock::iterator I = MBB->begin();
147   while (I != MBB->end()) {
148     if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
149       break;
150     unsigned Reg = I->getOperand(0).getReg();
151     ImpDefRegs.insert(Reg);
152     for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
153          unsigned SubReg = *SubRegs; ++SubRegs)
154       ImpDefRegs.insert(SubReg);
155     ++I;
156   }
157   if (ImpDefRegs.empty())
158     return false;
159
160   MachineBasicBlock::iterator FirstTerm = I;
161   while (I != MBB->end()) {
162     if (!TII->isUnpredicatedTerminator(I))
163       return false;
164     // See if it uses any of the implicitly defined registers.
165     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
166       MachineOperand &MO = I->getOperand(i);
167       if (!MO.isReg() || !MO.isUse())
168         continue;
169       unsigned Reg = MO.getReg();
170       if (ImpDefRegs.count(Reg))
171         return false;
172     }
173     ++I;
174   }
175
176   I = MBB->begin();
177   while (I != FirstTerm) {
178     MachineInstr *ImpDefMI = &*I;
179     ++I;
180     MBB->erase(ImpDefMI);
181   }
182
183   return true;
184 }
185
186 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
187   TII = MF.getTarget().getInstrInfo();
188   if (!TII) return false;
189
190   RegInfo = MF.getTarget().getRegisterInfo();
191
192   // Fix CFG.  The later algorithms expect it to be right.
193   bool EverMadeChange = false;
194   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
195     MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
196     SmallVector<MachineOperand, 4> Cond;
197     if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
198       EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
199     EverMadeChange |= OptimizeImpDefsBlock(MBB);
200   }
201
202   RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
203
204   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
205
206   bool MadeChangeThisIteration = true;
207   while (MadeChangeThisIteration) {
208     MadeChangeThisIteration = false;
209     MadeChangeThisIteration |= TailMergeBlocks(MF);
210     MadeChangeThisIteration |= OptimizeBranches(MF);
211     EverMadeChange |= MadeChangeThisIteration;
212   }
213
214   // See if any jump tables have become mergable or dead as the code generator
215   // did its thing.
216   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
217   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
218   if (!JTs.empty()) {
219     // Figure out how these jump tables should be merged.
220     std::vector<unsigned> JTMapping;
221     JTMapping.reserve(JTs.size());
222     
223     // We always keep the 0th jump table.
224     JTMapping.push_back(0);
225
226     // Scan the jump tables, seeing if there are any duplicates.  Note that this
227     // is N^2, which should be fixed someday.
228     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
229       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
230     
231     // If a jump table was merge with another one, walk the function rewriting
232     // references to jump tables to reference the new JT ID's.  Keep track of
233     // whether we see a jump table idx, if not, we can delete the JT.
234     BitVector JTIsLive(JTs.size());
235     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
236          BB != E; ++BB) {
237       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
238            I != E; ++I)
239         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
240           MachineOperand &Op = I->getOperand(op);
241           if (!Op.isJTI()) continue;
242           unsigned NewIdx = JTMapping[Op.getIndex()];
243           Op.setIndex(NewIdx);
244
245           // Remember that this JT is live.
246           JTIsLive.set(NewIdx);
247         }
248     }
249    
250     // Finally, remove dead jump tables.  This happens either because the
251     // indirect jump was unreachable (and thus deleted) or because the jump
252     // table was merged with some other one.
253     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
254       if (!JTIsLive.test(i)) {
255         JTI->RemoveJumpTable(i);
256         EverMadeChange = true;
257       }
258   }
259   
260   delete RS;
261   return EverMadeChange;
262 }
263
264 //===----------------------------------------------------------------------===//
265 //  Tail Merging of Blocks
266 //===----------------------------------------------------------------------===//
267
268 /// HashMachineInstr - Compute a hash value for MI and its operands.
269 static unsigned HashMachineInstr(const MachineInstr *MI) {
270   unsigned Hash = MI->getOpcode();
271   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
272     const MachineOperand &Op = MI->getOperand(i);
273     
274     // Merge in bits from the operand if easy.
275     unsigned OperandHash = 0;
276     switch (Op.getType()) {
277     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
278     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
279     case MachineOperand::MO_MachineBasicBlock:
280       OperandHash = Op.getMBB()->getNumber();
281       break;
282     case MachineOperand::MO_FrameIndex:
283     case MachineOperand::MO_ConstantPoolIndex:
284     case MachineOperand::MO_JumpTableIndex:
285       OperandHash = Op.getIndex();
286       break;
287     case MachineOperand::MO_GlobalAddress:
288     case MachineOperand::MO_ExternalSymbol:
289       // Global address / external symbol are too hard, don't bother, but do
290       // pull in the offset.
291       OperandHash = Op.getOffset();
292       break;
293     default: break;
294     }
295     
296     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
297   }
298   return Hash;
299 }
300
301 /// HashEndOfMBB - Hash the last few instructions in the MBB.  For blocks
302 /// with no successors, we hash two instructions, because cross-jumping 
303 /// only saves code when at least two instructions are removed (since a 
304 /// branch must be inserted).  For blocks with a successor, one of the
305 /// two blocks to be tail-merged will end with a branch already, so
306 /// it gains to cross-jump even for one instruction.
307
308 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
309                              unsigned minCommonTailLength) {
310   MachineBasicBlock::const_iterator I = MBB->end();
311   if (I == MBB->begin())
312     return 0;   // Empty MBB.
313   
314   --I;
315   unsigned Hash = HashMachineInstr(I);
316     
317   if (I == MBB->begin() || minCommonTailLength == 1)
318     return Hash;   // Single instr MBB.
319   
320   --I;
321   // Hash in the second-to-last instruction.
322   Hash ^= HashMachineInstr(I) << 2;
323   return Hash;
324 }
325
326 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
327 /// of instructions they actually have in common together at their end.  Return
328 /// iterators for the first shared instruction in each block.
329 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
330                                         MachineBasicBlock *MBB2,
331                                         MachineBasicBlock::iterator &I1,
332                                         MachineBasicBlock::iterator &I2) {
333   I1 = MBB1->end();
334   I2 = MBB2->end();
335   
336   unsigned TailLen = 0;
337   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
338     --I1; --I2;
339     if (!I1->isIdenticalTo(I2) || 
340         // FIXME: This check is dubious. It's used to get around a problem where
341         // people incorrectly expect inline asm directives to remain in the same
342         // relative order. This is untenable because normal compiler
343         // optimizations (like this one) may reorder and/or merge these
344         // directives.
345         I1->getOpcode() == TargetInstrInfo::INLINEASM) {
346       ++I1; ++I2;
347       break;
348     }
349     ++TailLen;
350   }
351   return TailLen;
352 }
353
354 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
355 /// after it, replacing it with an unconditional branch to NewDest.  This
356 /// returns true if OldInst's block is modified, false if NewDest is modified.
357 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
358                                            MachineBasicBlock *NewDest) {
359   MachineBasicBlock *OldBB = OldInst->getParent();
360   
361   // Remove all the old successors of OldBB from the CFG.
362   while (!OldBB->succ_empty())
363     OldBB->removeSuccessor(OldBB->succ_begin());
364   
365   // Remove all the dead instructions from the end of OldBB.
366   OldBB->erase(OldInst, OldBB->end());
367
368   // If OldBB isn't immediately before OldBB, insert a branch to it.
369   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
370     TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
371   OldBB->addSuccessor(NewDest);
372   ++NumTailMerge;
373 }
374
375 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
376 /// MBB so that the part before the iterator falls into the part starting at the
377 /// iterator.  This returns the new MBB.
378 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
379                                             MachineBasicBlock::iterator BBI1) {
380   MachineFunction &MF = *CurMBB.getParent();
381
382   // Create the fall-through block.
383   MachineFunction::iterator MBBI = &CurMBB;
384   MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
385   CurMBB.getParent()->insert(++MBBI, NewMBB);
386
387   // Move all the successors of this block to the specified block.
388   NewMBB->transferSuccessors(&CurMBB);
389  
390   // Add an edge from CurMBB to NewMBB for the fall-through.
391   CurMBB.addSuccessor(NewMBB);
392   
393   // Splice the code over.
394   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
395
396   // For targets that use the register scavenger, we must maintain LiveIns.
397   if (RS) {
398     RS->enterBasicBlock(&CurMBB);
399     if (!CurMBB.empty())
400       RS->forward(prior(CurMBB.end()));
401     BitVector RegsLiveAtExit(RegInfo->getNumRegs());
402     RS->getRegsUsed(RegsLiveAtExit, false);
403     for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
404       if (RegsLiveAtExit[i])
405         NewMBB->addLiveIn(i);
406   }
407
408   return NewMBB;
409 }
410
411 /// EstimateRuntime - Make a rough estimate for how long it will take to run
412 /// the specified code.
413 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
414                                 MachineBasicBlock::iterator E) {
415   unsigned Time = 0;
416   for (; I != E; ++I) {
417     const TargetInstrDesc &TID = I->getDesc();
418     if (TID.isCall())
419       Time += 10;
420     else if (TID.mayLoad() || TID.mayStore())
421       Time += 2;
422     else
423       ++Time;
424   }
425   return Time;
426 }
427
428 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
429 // branches temporarily for tail merging).  In the case where CurMBB ends
430 // with a conditional branch to the next block, optimize by reversing the
431 // test and conditionally branching to SuccMBB instead.
432
433 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
434                     const TargetInstrInfo *TII) {
435   MachineFunction *MF = CurMBB->getParent();
436   MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
437   MachineBasicBlock *TBB = 0, *FBB = 0;
438   SmallVector<MachineOperand, 4> Cond;
439   if (I != MF->end() &&
440       !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
441     MachineBasicBlock *NextBB = I;
442     if (TBB == NextBB && !Cond.empty() && !FBB) {
443       if (!TII->ReverseBranchCondition(Cond)) {
444         TII->RemoveBranch(*CurMBB);
445         TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
446         return;
447       }
448     }
449   }
450   TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
451 }
452
453 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
454                          const std::pair<unsigned,MachineBasicBlock*> &q) {
455     if (p.first < q.first)
456       return true;
457      else if (p.first > q.first)
458       return false;
459     else if (p.second->getNumber() < q.second->getNumber())
460       return true;
461     else if (p.second->getNumber() > q.second->getNumber())
462       return false;
463     else {
464       // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
465       // an object with itself.
466 #ifndef _GLIBCXX_DEBUG
467       llvm_unreachable("Predecessor appears twice");
468 #endif
469       return false;
470     }
471 }
472
473 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
474 /// hash CurHash (guaranteed to match the last element).   Build the vector 
475 /// SameTails of all those that have the (same) largest number of instructions
476 /// in common of any pair of these blocks.  SameTails entries contain an
477 /// iterator into MergePotentials (from which the MachineBasicBlock can be 
478 /// found) and a MachineBasicBlock::iterator into that MBB indicating the 
479 /// instruction where the matching code sequence begins.
480 /// Order of elements in SameTails is the reverse of the order in which
481 /// those blocks appear in MergePotentials (where they are not necessarily
482 /// consecutive).
483 unsigned BranchFolder::ComputeSameTails(unsigned CurHash, 
484                                         unsigned minCommonTailLength) {
485   unsigned maxCommonTailLength = 0U;
486   SameTails.clear();
487   MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
488   MPIterator HighestMPIter = prior(MergePotentials.end());
489   for (MPIterator CurMPIter = prior(MergePotentials.end()),
490                   B = MergePotentials.begin(); 
491        CurMPIter!=B && CurMPIter->first==CurHash;
492        --CurMPIter) {
493     for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
494       unsigned CommonTailLen = ComputeCommonTailLength(
495                                         CurMPIter->second,
496                                         I->second,
497                                         TrialBBI1, TrialBBI2);
498       // If we will have to split a block, there should be at least
499       // minCommonTailLength instructions in common; if not, at worst
500       // we will be replacing a fallthrough into the common tail with a
501       // branch, which at worst breaks even with falling through into
502       // the duplicated common tail, so 1 instruction in common is enough.
503       // We will always pick a block we do not have to split as the common
504       // tail if there is one.
505       // (Empty blocks will get forwarded and need not be considered.)
506       if (CommonTailLen >= minCommonTailLength ||
507           (CommonTailLen > 0 &&
508            (TrialBBI1==CurMPIter->second->begin() ||
509             TrialBBI2==I->second->begin()))) {
510         if (CommonTailLen > maxCommonTailLength) {
511           SameTails.clear();
512           maxCommonTailLength = CommonTailLen;
513           HighestMPIter = CurMPIter;
514           SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
515         }
516         if (HighestMPIter == CurMPIter &&
517             CommonTailLen == maxCommonTailLength)
518           SameTails.push_back(std::make_pair(I, TrialBBI2));
519       }
520       if (I==B)
521         break;
522     }
523   }
524   return maxCommonTailLength;
525 }
526
527 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
528 /// MergePotentials, restoring branches at ends of blocks as appropriate.
529 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash, 
530                                         MachineBasicBlock* SuccBB,
531                                         MachineBasicBlock* PredBB) {
532   MPIterator CurMPIter, B;
533   for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin(); 
534        CurMPIter->first==CurHash;
535        --CurMPIter) {
536     // Put the unconditional branch back, if we need one.
537     MachineBasicBlock *CurMBB = CurMPIter->second;
538     if (SuccBB && CurMBB != PredBB)
539       FixTail(CurMBB, SuccBB, TII);
540     if (CurMPIter==B)
541       break;
542   }
543   if (CurMPIter->first!=CurHash)
544     CurMPIter++;
545   MergePotentials.erase(CurMPIter, MergePotentials.end());
546 }
547
548 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
549 /// only of the common tail.  Create a block that does by splitting one.
550 unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
551                                              unsigned maxCommonTailLength) {
552   unsigned i, commonTailIndex;
553   unsigned TimeEstimate = ~0U;
554   for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
555     // Use PredBB if possible; that doesn't require a new branch.
556     if (SameTails[i].first->second==PredBB) {
557       commonTailIndex = i;
558       break;
559     }
560     // Otherwise, make a (fairly bogus) choice based on estimate of
561     // how long it will take the various blocks to execute.
562     unsigned t = EstimateRuntime(SameTails[i].first->second->begin(), 
563                                  SameTails[i].second);
564     if (t<=TimeEstimate) {
565       TimeEstimate = t;
566       commonTailIndex = i;
567     }
568   }
569
570   MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
571   MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
572
573   DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
574                << maxCommonTailLength);
575
576   MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
577   SameTails[commonTailIndex].first->second = newMBB;
578   SameTails[commonTailIndex].second = newMBB->begin();
579   // If we split PredBB, newMBB is the new predecessor.
580   if (PredBB==MBB)
581     PredBB = newMBB;
582
583   return commonTailIndex;
584 }
585
586 // See if any of the blocks in MergePotentials (which all have a common single
587 // successor, or all have no successor) can be tail-merged.  If there is a
588 // successor, any blocks in MergePotentials that are not tail-merged and
589 // are not immediately before Succ must have an unconditional branch to
590 // Succ added (but the predecessor/successor lists need no adjustment).  
591 // The lone predecessor of Succ that falls through into Succ,
592 // if any, is given in PredBB.
593
594 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
595                                   MachineBasicBlock* PredBB) {
596   // It doesn't make sense to save a single instruction since tail merging
597   // will add a jump.
598   // FIXME: Ask the target to provide the threshold?
599   unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
600   MadeChange = false;
601   
602   DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
603
604   // Sort by hash value so that blocks with identical end sequences sort
605   // together.
606   std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
607
608   // Walk through equivalence sets looking for actual exact matches.
609   while (MergePotentials.size() > 1) {
610     unsigned CurHash  = prior(MergePotentials.end())->first;
611     
612     // Build SameTails, identifying the set of blocks with this hash code
613     // and with the maximum number of instructions in common.
614     unsigned maxCommonTailLength = ComputeSameTails(CurHash, 
615                                                     minCommonTailLength);
616
617     // If we didn't find any pair that has at least minCommonTailLength 
618     // instructions in common, remove all blocks with this hash code and retry.
619     if (SameTails.empty()) {
620       RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
621       continue;
622     }
623
624     // If one of the blocks is the entire common tail (and not the entry
625     // block, which we can't jump to), we can treat all blocks with this same
626     // tail at once.  Use PredBB if that is one of the possibilities, as that
627     // will not introduce any extra branches.
628     MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
629                                 getParent()->begin();
630     unsigned int commonTailIndex, i;
631     for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
632       MachineBasicBlock *MBB = SameTails[i].first->second;
633       if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
634         commonTailIndex = i;
635         if (MBB==PredBB)
636           break;
637       }
638     }
639
640     if (commonTailIndex==SameTails.size()) {
641       // None of the blocks consist entirely of the common tail.
642       // Split a block so that one does.
643       commonTailIndex = CreateCommonTailOnlyBlock(PredBB,  maxCommonTailLength);
644     }
645
646     MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
647     // MBB is common tail.  Adjust all other BB's to jump to this one.
648     // Traversal must be forwards so erases work.
649     DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
650     for (unsigned int i=0; i<SameTails.size(); ++i) {
651       if (commonTailIndex==i)
652         continue;
653       DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
654       // Hack the end off BB i, making it jump to BB commonTailIndex instead.
655       ReplaceTailWithBranchTo(SameTails[i].second, MBB);
656       // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
657       MergePotentials.erase(SameTails[i].first);
658     }
659     DEBUG(errs() << "\n");
660     // We leave commonTailIndex in the worklist in case there are other blocks
661     // that match it with a smaller number of instructions.
662     MadeChange = true;
663   }
664   return MadeChange;
665 }
666
667 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
668
669   if (!EnableTailMerge) return false;
670  
671   MadeChange = false;
672
673   // First find blocks with no successors.
674   MergePotentials.clear();
675   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
676     if (I->succ_empty())
677       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
678   }
679   // See if we can do any tail merging on those.
680   if (MergePotentials.size() < TailMergeThreshold &&
681       MergePotentials.size() >= 2)
682     MadeChange |= TryMergeBlocks(NULL, NULL);
683
684   // Look at blocks (IBB) with multiple predecessors (PBB).
685   // We change each predecessor to a canonical form, by
686   // (1) temporarily removing any unconditional branch from the predecessor
687   // to IBB, and
688   // (2) alter conditional branches so they branch to the other block
689   // not IBB; this may require adding back an unconditional branch to IBB 
690   // later, where there wasn't one coming in.  E.g.
691   //   Bcc IBB
692   //   fallthrough to QBB
693   // here becomes
694   //   Bncc QBB
695   // with a conceptual B to IBB after that, which never actually exists.
696   // With those changes, we see whether the predecessors' tails match,
697   // and merge them if so.  We change things out of canonical form and
698   // back to the way they were later in the process.  (OptimizeBranches
699   // would undo some of this, but we can't use it, because we'd get into
700   // a compile-time infinite loop repeatedly doing and undoing the same
701   // transformations.)
702
703   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
704     if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
705       SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
706       MachineBasicBlock *IBB = I;
707       MachineBasicBlock *PredBB = prior(I);
708       MergePotentials.clear();
709       for (MachineBasicBlock::pred_iterator P = I->pred_begin(), 
710                                             E2 = I->pred_end();
711            P != E2; ++P) {
712         MachineBasicBlock* PBB = *P;
713         // Skip blocks that loop to themselves, can't tail merge these.
714         if (PBB==IBB)
715           continue;
716         // Visit each predecessor only once.
717         if (!UniquePreds.insert(PBB))
718           continue;
719         MachineBasicBlock *TBB = 0, *FBB = 0;
720         SmallVector<MachineOperand, 4> Cond;
721         if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
722           // Failing case:  IBB is the target of a cbr, and
723           // we cannot reverse the branch.
724           SmallVector<MachineOperand, 4> NewCond(Cond);
725           if (!Cond.empty() && TBB==IBB) {
726             if (TII->ReverseBranchCondition(NewCond))
727               continue;
728             // This is the QBB case described above
729             if (!FBB)
730               FBB = next(MachineFunction::iterator(PBB));
731           }
732           // Failing case:  the only way IBB can be reached from PBB is via
733           // exception handling.  Happens for landing pads.  Would be nice
734           // to have a bit in the edge so we didn't have to do all this.
735           if (IBB->isLandingPad()) {
736             MachineFunction::iterator IP = PBB;  IP++;
737             MachineBasicBlock* PredNextBB = NULL;
738             if (IP!=MF.end())
739               PredNextBB = IP;
740             if (TBB==NULL) {
741               if (IBB!=PredNextBB)      // fallthrough
742                 continue;
743             } else if (FBB) {
744               if (TBB!=IBB && FBB!=IBB)   // cbr then ubr
745                 continue;
746             } else if (Cond.empty()) {
747               if (TBB!=IBB)               // ubr
748                 continue;
749             } else {
750               if (TBB!=IBB && IBB!=PredNextBB)  // cbr
751                 continue;
752             }
753           }
754           // Remove the unconditional branch at the end, if any.
755           if (TBB && (Cond.empty() || FBB)) {
756             TII->RemoveBranch(*PBB);
757             if (!Cond.empty())
758               // reinsert conditional branch only, for now
759               TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
760           }
761           MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
762         }
763       }
764     if (MergePotentials.size() >= 2)
765       MadeChange |= TryMergeBlocks(I, PredBB);
766     // Reinsert an unconditional branch if needed.
767     // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
768     PredBB = prior(I);      // this may have been changed in TryMergeBlocks
769     if (MergePotentials.size()==1 && 
770         MergePotentials.begin()->second != PredBB)
771       FixTail(MergePotentials.begin()->second, I, TII);
772     }
773   }
774   return MadeChange;
775 }
776
777 //===----------------------------------------------------------------------===//
778 //  Branch Optimization
779 //===----------------------------------------------------------------------===//
780
781 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
782   MadeChange = false;
783   
784   // Make sure blocks are numbered in order
785   MF.RenumberBlocks();
786
787   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
788     MachineBasicBlock *MBB = I++;
789     OptimizeBlock(MBB);
790     
791     // If it is dead, remove it.
792     if (MBB->pred_empty()) {
793       RemoveDeadBlock(MBB);
794       MadeChange = true;
795       ++NumDeadBlocks;
796     }
797   }
798   return MadeChange;
799 }
800
801
802 /// CanFallThrough - Return true if the specified block (with the specified
803 /// branch condition) can implicitly transfer control to the block after it by
804 /// falling off the end of it.  This should return false if it can reach the
805 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
806 ///
807 /// True is a conservative answer.
808 ///
809 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
810                                   bool BranchUnAnalyzable,
811                                   MachineBasicBlock *TBB, 
812                                   MachineBasicBlock *FBB,
813                                   const SmallVectorImpl<MachineOperand> &Cond) {
814   MachineFunction::iterator Fallthrough = CurBB;
815   ++Fallthrough;
816   // If FallthroughBlock is off the end of the function, it can't fall through.
817   if (Fallthrough == CurBB->getParent()->end())
818     return false;
819   
820   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
821   if (!CurBB->isSuccessor(Fallthrough))
822     return false;
823   
824   // If we couldn't analyze the branch, assume it could fall through.
825   if (BranchUnAnalyzable) return true;
826   
827   // If there is no branch, control always falls through.
828   if (TBB == 0) return true;
829
830   // If there is some explicit branch to the fallthrough block, it can obviously
831   // reach, even though the branch should get folded to fall through implicitly.
832   if (MachineFunction::iterator(TBB) == Fallthrough ||
833       MachineFunction::iterator(FBB) == Fallthrough)
834     return true;
835   
836   // If it's an unconditional branch to some block not the fall through, it 
837   // doesn't fall through.
838   if (Cond.empty()) return false;
839   
840   // Otherwise, if it is conditional and has no explicit false block, it falls
841   // through.
842   return FBB == 0;
843 }
844
845 /// CanFallThrough - Return true if the specified can implicitly transfer
846 /// control to the block after it by falling off the end of it.  This should
847 /// return false if it can reach the block after it, but it uses an explicit
848 /// branch to do so (e.g. a table jump).
849 ///
850 /// True is a conservative answer.
851 ///
852 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
853   MachineBasicBlock *TBB = 0, *FBB = 0;
854   SmallVector<MachineOperand, 4> Cond;
855   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
856   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
857 }
858
859 /// IsBetterFallthrough - Return true if it would be clearly better to
860 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
861 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
862 /// result in infinite loops.
863 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
864                                 MachineBasicBlock *MBB2) {
865   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
866   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
867   // optimize branches that branch to either a return block or an assert block
868   // into a fallthrough to the return.
869   if (MBB1->empty() || MBB2->empty()) return false;
870  
871   // If there is a clear successor ordering we make sure that one block
872   // will fall through to the next
873   if (MBB1->isSuccessor(MBB2)) return true;
874   if (MBB2->isSuccessor(MBB1)) return false;
875
876   MachineInstr *MBB1I = --MBB1->end();
877   MachineInstr *MBB2I = --MBB2->end();
878   return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
879 }
880
881 /// OptimizeBlock - Analyze and optimize control flow related to the specified
882 /// block.  This is never called on the entry block.
883 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
884   MachineFunction::iterator FallThrough = MBB;
885   ++FallThrough;
886   
887   // If this block is empty, make everyone use its fall-through, not the block
888   // explicitly.  Landing pads should not do this since the landing-pad table
889   // points to this block.
890   if (MBB->empty() && !MBB->isLandingPad()) {
891     // Dead block?  Leave for cleanup later.
892     if (MBB->pred_empty()) return;
893     
894     if (FallThrough == MBB->getParent()->end()) {
895       // TODO: Simplify preds to not branch here if possible!
896     } else {
897       // Rewrite all predecessors of the old block to go to the fallthrough
898       // instead.
899       while (!MBB->pred_empty()) {
900         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
901         Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
902       }
903       // If MBB was the target of a jump table, update jump tables to go to the
904       // fallthrough instead.
905       MBB->getParent()->getJumpTableInfo()->
906         ReplaceMBBInJumpTables(MBB, FallThrough);
907       MadeChange = true;
908     }
909     return;
910   }
911
912   // Check to see if we can simplify the terminator of the block before this
913   // one.
914   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
915
916   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
917   SmallVector<MachineOperand, 4> PriorCond;
918   bool PriorUnAnalyzable =
919     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
920   if (!PriorUnAnalyzable) {
921     // If the CFG for the prior block has extra edges, remove them.
922     MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
923                                               !PriorCond.empty());
924     
925     // If the previous branch is conditional and both conditions go to the same
926     // destination, remove the branch, replacing it with an unconditional one or
927     // a fall-through.
928     if (PriorTBB && PriorTBB == PriorFBB) {
929       TII->RemoveBranch(PrevBB);
930       PriorCond.clear(); 
931       if (PriorTBB != MBB)
932         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
933       MadeChange = true;
934       ++NumBranchOpts;
935       return OptimizeBlock(MBB);
936     }
937     
938     // If the previous branch *only* branches to *this* block (conditional or
939     // not) remove the branch.
940     if (PriorTBB == MBB && PriorFBB == 0) {
941       TII->RemoveBranch(PrevBB);
942       MadeChange = true;
943       ++NumBranchOpts;
944       return OptimizeBlock(MBB);
945     }
946     
947     // If the prior block branches somewhere else on the condition and here if
948     // the condition is false, remove the uncond second branch.
949     if (PriorFBB == MBB) {
950       TII->RemoveBranch(PrevBB);
951       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
952       MadeChange = true;
953       ++NumBranchOpts;
954       return OptimizeBlock(MBB);
955     }
956     
957     // If the prior block branches here on true and somewhere else on false, and
958     // if the branch condition is reversible, reverse the branch to create a
959     // fall-through.
960     if (PriorTBB == MBB) {
961       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
962       if (!TII->ReverseBranchCondition(NewPriorCond)) {
963         TII->RemoveBranch(PrevBB);
964         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
965         MadeChange = true;
966         ++NumBranchOpts;
967         return OptimizeBlock(MBB);
968       }
969     }
970     
971     // If this block doesn't fall through (e.g. it ends with an uncond branch or
972     // has no successors) and if the pred falls through into this block, and if
973     // it would otherwise fall through into the block after this, move this
974     // block to the end of the function.
975     //
976     // We consider it more likely that execution will stay in the function (e.g.
977     // due to loops) than it is to exit it.  This asserts in loops etc, moving
978     // the assert condition out of the loop body.
979     if (!PriorCond.empty() && PriorFBB == 0 &&
980         MachineFunction::iterator(PriorTBB) == FallThrough &&
981         !CanFallThrough(MBB)) {
982       bool DoTransform = true;
983       
984       // We have to be careful that the succs of PredBB aren't both no-successor
985       // blocks.  If neither have successors and if PredBB is the second from
986       // last block in the function, we'd just keep swapping the two blocks for
987       // last.  Only do the swap if one is clearly better to fall through than
988       // the other.
989       if (FallThrough == --MBB->getParent()->end() &&
990           !IsBetterFallthrough(PriorTBB, MBB))
991         DoTransform = false;
992
993       // We don't want to do this transformation if we have control flow like:
994       //   br cond BB2
995       // BB1:
996       //   ..
997       //   jmp BBX
998       // BB2:
999       //   ..
1000       //   ret
1001       //
1002       // In this case, we could actually be moving the return block *into* a
1003       // loop!
1004       if (DoTransform && !MBB->succ_empty() &&
1005           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1006         DoTransform = false;
1007       
1008       
1009       if (DoTransform) {
1010         // Reverse the branch so we will fall through on the previous true cond.
1011         SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1012         if (!TII->ReverseBranchCondition(NewPriorCond)) {
1013           DEBUG(errs() << "\nMoving MBB: " << *MBB
1014                        << "To make fallthrough to: " << *PriorTBB << "\n");
1015           
1016           TII->RemoveBranch(PrevBB);
1017           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1018
1019           // Move this block to the end of the function.
1020           MBB->moveAfter(--MBB->getParent()->end());
1021           MadeChange = true;
1022           ++NumBranchOpts;
1023           return;
1024         }
1025       }
1026     }
1027   }
1028   
1029   // Analyze the branch in the current block.
1030   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1031   SmallVector<MachineOperand, 4> CurCond;
1032   bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1033   if (!CurUnAnalyzable) {
1034     // If the CFG for the prior block has extra edges, remove them.
1035     MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1036
1037     // If this is a two-way branch, and the FBB branches to this block, reverse 
1038     // the condition so the single-basic-block loop is faster.  Instead of:
1039     //    Loop: xxx; jcc Out; jmp Loop
1040     // we want:
1041     //    Loop: xxx; jncc Loop; jmp Out
1042     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1043       SmallVector<MachineOperand, 4> NewCond(CurCond);
1044       if (!TII->ReverseBranchCondition(NewCond)) {
1045         TII->RemoveBranch(*MBB);
1046         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1047         MadeChange = true;
1048         ++NumBranchOpts;
1049         return OptimizeBlock(MBB);
1050       }
1051     }
1052     
1053     
1054     // If this branch is the only thing in its block, see if we can forward
1055     // other blocks across it.
1056     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
1057         MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
1058       // This block may contain just an unconditional branch.  Because there can
1059       // be 'non-branch terminators' in the block, try removing the branch and
1060       // then seeing if the block is empty.
1061       TII->RemoveBranch(*MBB);
1062
1063       // If this block is just an unconditional branch to CurTBB, we can
1064       // usually completely eliminate the block.  The only case we cannot
1065       // completely eliminate the block is when the block before this one
1066       // falls through into MBB and we can't understand the prior block's branch
1067       // condition.
1068       if (MBB->empty()) {
1069         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1070         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1071             !PrevBB.isSuccessor(MBB)) {
1072           // If the prior block falls through into us, turn it into an
1073           // explicit branch to us to make updates simpler.
1074           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
1075               PriorTBB != MBB && PriorFBB != MBB) {
1076             if (PriorTBB == 0) {
1077               assert(PriorCond.empty() && PriorFBB == 0 &&
1078                      "Bad branch analysis");
1079               PriorTBB = MBB;
1080             } else {
1081               assert(PriorFBB == 0 && "Machine CFG out of date!");
1082               PriorFBB = MBB;
1083             }
1084             TII->RemoveBranch(PrevBB);
1085             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1086           }
1087
1088           // Iterate through all the predecessors, revectoring each in-turn.
1089           size_t PI = 0;
1090           bool DidChange = false;
1091           bool HasBranchToSelf = false;
1092           while(PI != MBB->pred_size()) {
1093             MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1094             if (PMBB == MBB) {
1095               // If this block has an uncond branch to itself, leave it.
1096               ++PI;
1097               HasBranchToSelf = true;
1098             } else {
1099               DidChange = true;
1100               PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1101               // If this change resulted in PMBB ending in a conditional
1102               // branch where both conditions go to the same destination,
1103               // change this to an unconditional branch (and fix the CFG).
1104               MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1105               SmallVector<MachineOperand, 4> NewCurCond;
1106               bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1107                       NewCurFBB, NewCurCond, true);
1108               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1109                 TII->RemoveBranch(*PMBB);
1110                 NewCurCond.clear(); 
1111                 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1112                 MadeChange = true;
1113                 ++NumBranchOpts;
1114                 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1115               }
1116             }
1117           }
1118
1119           // Change any jumptables to go to the new MBB.
1120           MBB->getParent()->getJumpTableInfo()->
1121             ReplaceMBBInJumpTables(MBB, CurTBB);
1122           if (DidChange) {
1123             ++NumBranchOpts;
1124             MadeChange = true;
1125             if (!HasBranchToSelf) return;
1126           }
1127         }
1128       }
1129       
1130       // Add the branch back if the block is more than just an uncond branch.
1131       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1132     }
1133   }
1134
1135   // If the prior block doesn't fall through into this block, and if this
1136   // block doesn't fall through into some other block, see if we can find a
1137   // place to move this block where a fall-through will happen.
1138   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1139                       PriorTBB, PriorFBB, PriorCond)) {
1140     // Now we know that there was no fall-through into this block, check to
1141     // see if it has a fall-through into its successor.
1142     bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, 
1143                                        CurCond);
1144
1145     if (!MBB->isLandingPad()) {
1146       // Check all the predecessors of this block.  If one of them has no fall
1147       // throughs, move this block right after it.
1148       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1149            E = MBB->pred_end(); PI != E; ++PI) {
1150         // Analyze the branch at the end of the pred.
1151         MachineBasicBlock *PredBB = *PI;
1152         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1153         if (PredBB != MBB && !CanFallThrough(PredBB)
1154             && (!CurFallsThru || !CurTBB || !CurFBB)
1155             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1156           // If the current block doesn't fall through, just move it.
1157           // If the current block can fall through and does not end with a
1158           // conditional branch, we need to append an unconditional jump to 
1159           // the (current) next block.  To avoid a possible compile-time
1160           // infinite loop, move blocks only backward in this case.
1161           // Also, if there are already 2 branches here, we cannot add a third;
1162           // this means we have the case
1163           // Bcc next
1164           // B elsewhere
1165           // next:
1166           if (CurFallsThru) {
1167             MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1168             CurCond.clear();
1169             TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1170           }
1171           MBB->moveAfter(PredBB);
1172           MadeChange = true;
1173           return OptimizeBlock(MBB);
1174         }
1175       }
1176     }
1177         
1178     if (!CurFallsThru) {
1179       // Check all successors to see if we can move this block before it.
1180       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1181            E = MBB->succ_end(); SI != E; ++SI) {
1182         // Analyze the branch at the end of the block before the succ.
1183         MachineBasicBlock *SuccBB = *SI;
1184         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1185         std::vector<MachineOperand> SuccPrevCond;
1186         
1187         // If this block doesn't already fall-through to that successor, and if
1188         // the succ doesn't already have a block that can fall through into it,
1189         // and if the successor isn't an EH destination, we can arrange for the
1190         // fallthrough to happen.
1191         if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1192             !SuccBB->isLandingPad()) {
1193           MBB->moveBefore(SuccBB);
1194           MadeChange = true;
1195           return OptimizeBlock(MBB);
1196         }
1197       }
1198       
1199       // Okay, there is no really great place to put this block.  If, however,
1200       // the block before this one would be a fall-through if this block were
1201       // removed, move this block to the end of the function.
1202       if (FallThrough != MBB->getParent()->end() &&
1203           PrevBB.isSuccessor(FallThrough)) {
1204         MBB->moveAfter(--MBB->getParent()->end());
1205         MadeChange = true;
1206         return;
1207       }
1208     }
1209   }
1210 }