9ca0091d20358226b4b1e0d3a883e45485f12705
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
28 using namespace llvm;
29
30 static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
31 static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
32 static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
33
34 namespace {
35   struct BranchFolder : public MachineFunctionPass {
36     virtual bool runOnMachineFunction(MachineFunction &MF);
37     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
38     const TargetInstrInfo *TII;
39     MachineDebugInfo *MDI;
40     bool MadeChange;
41   private:
42     // Tail Merging.
43     bool TailMergeBlocks(MachineFunction &MF);
44     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
45                                  MachineBasicBlock *NewDest);
46
47     // Branch optzn.
48     bool OptimizeBranches(MachineFunction &MF);
49     void OptimizeBlock(MachineBasicBlock *MBB);
50     void RemoveDeadBlock(MachineBasicBlock *MBB);
51     
52     bool CanFallThrough(MachineBasicBlock *CurBB);
53     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
54                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
55                         const std::vector<MachineOperand> &Cond);
56   };
57 }
58
59 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
60
61 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
62 /// function, updating the CFG.
63 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
64   assert(MBB->pred_empty() && "MBB must be dead!");
65   
66   MachineFunction *MF = MBB->getParent();
67   // drop all successors.
68   while (!MBB->succ_empty())
69     MBB->removeSuccessor(MBB->succ_end()-1);
70   
71   // If there is DWARF info to active, check to see if there are any DWARF_LABEL
72   // records in the basic block.  If so, unregister them from MachineDebugInfo.
73   if (MDI && !MBB->empty()) {
74     unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
75     assert(DWARF_LABELOpc &&
76            "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
77     
78     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
79          I != E; ++I) {
80       if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
81         // The label ID # is always operand #0, an immediate.
82         MDI->InvalidateLabel(I->getOperand(0).getImm());
83       }
84     }
85   }
86   
87   // Remove the block.
88   MF->getBasicBlockList().erase(MBB);
89 }
90
91 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
92   TII = MF.getTarget().getInstrInfo();
93   if (!TII) return false;
94
95   MDI = getAnalysisToUpdate<MachineDebugInfo>();
96   
97   bool EverMadeChange = false;
98   bool MadeChangeThisIteration = true;
99   while (MadeChangeThisIteration) {
100     MadeChangeThisIteration = false;
101     MadeChangeThisIteration |= TailMergeBlocks(MF);
102     MadeChangeThisIteration |= OptimizeBranches(MF);
103     EverMadeChange |= MadeChangeThisIteration;
104   }
105
106   // See if any jump tables have become mergable or dead as the code generator
107   // did its thing.
108   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
109   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
110   if (!JTs.empty()) {
111     // Figure out how these jump tables should be merged.
112     std::vector<unsigned> JTMapping;
113     JTMapping.reserve(JTs.size());
114     
115     // We always keep the 0th jump table.
116     JTMapping.push_back(0);
117
118     // Scan the jump tables, seeing if there are any duplicates.  Note that this
119     // is N^2, which should be fixed someday.
120     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
121       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
122     
123     // If a jump table was merge with another one, walk the function rewriting
124     // references to jump tables to reference the new JT ID's.  Keep track of
125     // whether we see a jump table idx, if not, we can delete the JT.
126     std::vector<bool> JTIsLive;
127     JTIsLive.resize(JTs.size());
128     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
129          BB != E; ++BB) {
130       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
131            I != E; ++I)
132         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
133           MachineOperand &Op = I->getOperand(op);
134           if (!Op.isJumpTableIndex()) continue;
135           unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
136           Op.setJumpTableIndex(NewIdx);
137
138           // Remember that this JT is live.
139           JTIsLive[NewIdx] = true;
140         }
141     }
142    
143     // Finally, remove dead jump tables.  This happens either because the
144     // indirect jump was unreachable (and thus deleted) or because the jump
145     // table was merged with some other one.
146     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
147       if (!JTIsLive[i]) {
148         JTI->RemoveJumpTable(i);
149         EverMadeChange = true;
150       }
151   }
152   
153   return EverMadeChange;
154 }
155
156 //===----------------------------------------------------------------------===//
157 //  Tail Merging of Blocks
158 //===----------------------------------------------------------------------===//
159
160 /// HashMachineInstr - Compute a hash value for MI and its operands.
161 static unsigned HashMachineInstr(const MachineInstr *MI) {
162   unsigned Hash = MI->getOpcode();
163   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
164     const MachineOperand &Op = MI->getOperand(i);
165     
166     // Merge in bits from the operand if easy.
167     unsigned OperandHash = 0;
168     switch (Op.getType()) {
169     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
170     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
171     case MachineOperand::MO_MachineBasicBlock:
172       OperandHash = Op.getMachineBasicBlock()->getNumber();
173       break;
174     case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
175     case MachineOperand::MO_ConstantPoolIndex:
176       OperandHash = Op.getConstantPoolIndex();
177       break;
178     case MachineOperand::MO_JumpTableIndex:
179       OperandHash = Op.getJumpTableIndex();
180       break;
181     case MachineOperand::MO_GlobalAddress:
182     case MachineOperand::MO_ExternalSymbol:
183       // Global address / external symbol are too hard, don't bother, but do
184       // pull in the offset.
185       OperandHash = Op.getOffset();
186       break;
187     default: break;
188     }
189     
190     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
191   }
192   return Hash;
193 }
194
195 /// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
196 /// instructions, because cross-jumping only saves code when at least two
197 /// instructions are removed (since a branch must be inserted).
198 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
199   MachineBasicBlock::const_iterator I = MBB->end();
200   if (I == MBB->begin())
201     return 0;   // Empty MBB.
202   
203   --I;
204   unsigned Hash = HashMachineInstr(I);
205     
206   if (I == MBB->begin())
207     return Hash;   // Single instr MBB.
208   
209   --I;
210   // Hash in the second-to-last instruction.
211   Hash ^= HashMachineInstr(I) << 2;
212   return Hash;
213 }
214
215 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
216 /// of instructions they actually have in common together at their end.  Return
217 /// iterators for the first shared instruction in each block.
218 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
219                                         MachineBasicBlock *MBB2,
220                                         MachineBasicBlock::iterator &I1,
221                                         MachineBasicBlock::iterator &I2) {
222   I1 = MBB1->end();
223   I2 = MBB2->end();
224   
225   unsigned TailLen = 0;
226   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
227     --I1; --I2;
228     if (!I1->isIdenticalTo(I2)) {
229       ++I1; ++I2;
230       break;
231     }
232     ++TailLen;
233   }
234   return TailLen;
235 }
236
237 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
238 /// after it, replacing it with an unconditional branch to NewDest.  This
239 /// returns true if OldInst's block is modified, false if NewDest is modified.
240 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
241                                            MachineBasicBlock *NewDest) {
242   MachineBasicBlock *OldBB = OldInst->getParent();
243   
244   // Remove all the old successors of OldBB from the CFG.
245   while (!OldBB->succ_empty())
246     OldBB->removeSuccessor(OldBB->succ_begin());
247   
248   // Remove all the dead instructions from the end of OldBB.
249   OldBB->erase(OldInst, OldBB->end());
250
251   // If OldBB isn't immediately before OldBB, insert a branch to it.
252   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
253     TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
254   OldBB->addSuccessor(NewDest);
255   ++NumTailMerge;
256 }
257
258 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
259   MadeChange = false;
260   
261   return false;
262   
263   // Find blocks with no successors.
264   std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
265   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
266     if (I->succ_empty())
267       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
268   }
269   
270   // Sort by hash value so that blocks with identical end sequences sort
271   // together.
272   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
273
274   // Walk through equivalence sets looking for actual exact matches.
275   while (MergePotentials.size() > 1) {
276     unsigned CurHash  = (MergePotentials.end()-1)->first;
277     unsigned PrevHash = (MergePotentials.end()-2)->first;
278     MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
279     
280     // If there is nothing that matches the hash of the current basic block,
281     // give up.
282     if (CurHash != PrevHash) {
283       MergePotentials.pop_back();
284       continue;
285     }
286     
287     // Determine the actual length of the shared tail between these two basic
288     // blocks.  Because the hash can have collisions, it's possible that this is
289     // less than 2.
290     MachineBasicBlock::iterator BBI1, BBI2;
291     unsigned CommonTailLen = 
292       ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second, 
293                               BBI1, BBI2);
294     
295     // If the tails don't have at least two instructions in common, see if there
296     // is anything else in the equivalence class that does match.
297     if (CommonTailLen < 2) {
298       unsigned FoundMatch = ~0U;
299       for (int i = MergePotentials.size()-2;
300            i != -1 && MergePotentials[i].first == CurHash; --i) {
301         CommonTailLen = ComputeCommonTailLength(CurMBB, 
302                                                 MergePotentials[i].second,
303                                                 BBI1, BBI2);
304         if (CommonTailLen >= 2) {
305           FoundMatch = i;
306           break;
307         }
308       }
309       
310       // If we didn't find anything that has at least two instructions matching
311       // this one, bail out.
312       if (FoundMatch == ~0U) {
313         MergePotentials.pop_back();
314         continue;
315       }
316       
317       // Otherwise, move the matching block to the right position.
318       std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
319     }
320     
321     // If either block is the entire common tail, make the longer one branch to
322     // the shorter one.
323     MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
324     if (CurMBB->begin() == BBI1) {
325       // Hack the end off MBB2, making it jump to CurMBB instead.
326       ReplaceTailWithBranchTo(BBI2, CurMBB);
327       // This modifies MBB2, so remove it from the worklist.
328       MergePotentials.erase(MergePotentials.end()-2);
329       MadeChange = true;
330       continue;
331     } else if (MBB2->begin() == BBI2) {
332       // Hack the end off CurMBB, making it jump to MBBI@ instead.
333       ReplaceTailWithBranchTo(BBI1, MBB2);
334       // This modifies CurMBB, so remove it from the worklist.
335       MergePotentials.pop_back();
336       MadeChange = true;
337       continue;
338     }
339     
340     MergePotentials.pop_back();
341   }
342   
343   return MadeChange;
344 }
345
346
347 //===----------------------------------------------------------------------===//
348 //  Branch Optimization
349 //===----------------------------------------------------------------------===//
350
351 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
352   MadeChange = false;
353   
354   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
355     MachineBasicBlock *MBB = I++;
356     OptimizeBlock(MBB);
357     
358     // If it is dead, remove it.
359     if (MBB->pred_empty()) {
360       RemoveDeadBlock(MBB);
361       MadeChange = true;
362       ++NumDeadBlocks;
363     }
364   }
365   return MadeChange;
366 }
367
368
369 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
370 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
371 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
372 /// be null.
373 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
374                                  MachineBasicBlock *DestA,
375                                  MachineBasicBlock *DestB,
376                                  bool isCond, 
377                                  MachineFunction::iterator FallThru) {
378   bool MadeChange = false;
379   bool AddedFallThrough = false;
380   
381   // If this block ends with a conditional branch that falls through to its
382   // successor, set DestB as the successor.
383   if (isCond) {
384     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
385       DestB = FallThru;
386       AddedFallThrough = true;
387     }
388   } else {
389     // If this is an unconditional branch with no explicit dest, it must just be
390     // a fallthrough into DestB.
391     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
392       DestA = FallThru;
393       AddedFallThrough = true;
394     }
395   }
396   
397   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
398   while (SI != MBB.succ_end()) {
399     if (*SI == DestA) {
400       DestA = 0;
401       ++SI;
402     } else if (*SI == DestB) {
403       DestB = 0;
404       ++SI;
405     } else {
406       // Otherwise, this is a superfluous edge, remove it.
407       MBB.removeSuccessor(SI);
408       MadeChange = true;
409     }
410   }
411   if (!AddedFallThrough) {
412     assert(DestA == 0 && DestB == 0 &&
413            "MachineCFG is missing edges!");
414   } else if (isCond) {
415     assert(DestA == 0 && "MachineCFG is missing edges!");
416   }
417   return MadeChange;
418 }
419
420
421 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
422 /// 'Old', change the code and CFG so that it branches to 'New' instead.
423 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
424                                    MachineBasicBlock *Old,
425                                    MachineBasicBlock *New,
426                                    const TargetInstrInfo *TII) {
427   assert(Old != New && "Cannot replace self with self!");
428
429   MachineBasicBlock::iterator I = BB->end();
430   while (I != BB->begin()) {
431     --I;
432     if (!TII->isTerminatorInstr(I->getOpcode())) break;
433
434     // Scan the operands of this machine instruction, replacing any uses of Old
435     // with New.
436     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
437       if (I->getOperand(i).isMachineBasicBlock() &&
438           I->getOperand(i).getMachineBasicBlock() == Old)
439         I->getOperand(i).setMachineBasicBlock(New);
440   }
441
442   // Update the successor information.
443   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
444   for (int i = Succs.size()-1; i >= 0; --i)
445     if (Succs[i] == Old) {
446       BB->removeSuccessor(Old);
447       BB->addSuccessor(New);
448     }
449 }
450
451 /// CanFallThrough - Return true if the specified block (with the specified
452 /// branch condition) can implicitly transfer control to the block after it by
453 /// falling off the end of it.  This should return false if it can reach the
454 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
455 ///
456 /// True is a conservative answer.
457 ///
458 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
459                                   bool BranchUnAnalyzable,
460                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
461                                   const std::vector<MachineOperand> &Cond) {
462   MachineFunction::iterator Fallthrough = CurBB;
463   ++Fallthrough;
464   // If FallthroughBlock is off the end of the function, it can't fall through.
465   if (Fallthrough == CurBB->getParent()->end())
466     return false;
467   
468   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
469   if (!CurBB->isSuccessor(Fallthrough))
470     return false;
471   
472   // If we couldn't analyze the branch, assume it could fall through.
473   if (BranchUnAnalyzable) return true;
474   
475   // If there is no branch, control always falls through.
476   if (TBB == 0) return true;
477
478   // If there is some explicit branch to the fallthrough block, it can obviously
479   // reach, even though the branch should get folded to fall through implicitly.
480   if (MachineFunction::iterator(TBB) == Fallthrough ||
481       MachineFunction::iterator(FBB) == Fallthrough)
482     return true;
483   
484   // If it's an unconditional branch to some block not the fall through, it 
485   // doesn't fall through.
486   if (Cond.empty()) return false;
487   
488   // Otherwise, if it is conditional and has no explicit false block, it falls
489   // through.
490   return FBB == 0;
491 }
492
493 /// CanFallThrough - Return true if the specified can implicitly transfer
494 /// control to the block after it by falling off the end of it.  This should
495 /// return false if it can reach the block after it, but it uses an explicit
496 /// branch to do so (e.g. a table jump).
497 ///
498 /// True is a conservative answer.
499 ///
500 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
501   MachineBasicBlock *TBB = 0, *FBB = 0;
502   std::vector<MachineOperand> Cond;
503   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
504   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
505 }
506
507 /// OptimizeBlock - Analyze and optimize control flow related to the specified
508 /// block.  This is never called on the entry block.
509 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
510   MachineFunction::iterator FallThrough = MBB;
511   ++FallThrough;
512   
513   // If this block is empty, make everyone use its fall-through, not the block
514   // explicitly.
515   if (MBB->empty()) {
516     // Dead block?  Leave for cleanup later.
517     if (MBB->pred_empty()) return;
518     
519     if (FallThrough == MBB->getParent()->end()) {
520       // TODO: Simplify preds to not branch here if possible!
521     } else {
522       // Rewrite all predecessors of the old block to go to the fallthrough
523       // instead.
524       while (!MBB->pred_empty()) {
525         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
526         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
527       }
528       
529       // If MBB was the target of a jump table, update jump tables to go to the
530       // fallthrough instead.
531       MBB->getParent()->getJumpTableInfo()->
532         ReplaceMBBInJumpTables(MBB, FallThrough);
533       MadeChange = true;
534     }
535     return;
536   }
537
538   // Check to see if we can simplify the terminator of the block before this
539   // one.
540   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
541
542   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
543   std::vector<MachineOperand> PriorCond;
544   bool PriorUnAnalyzable =
545     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
546   if (!PriorUnAnalyzable) {
547     // If the CFG for the prior block has extra edges, remove them.
548     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
549                                        !PriorCond.empty(), MBB);
550     
551     // If the previous branch is conditional and both conditions go to the same
552     // destination, remove the branch, replacing it with an unconditional one or
553     // a fall-through.
554     if (PriorTBB && PriorTBB == PriorFBB) {
555       TII->RemoveBranch(PrevBB);
556       PriorCond.clear(); 
557       if (PriorTBB != MBB)
558         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
559       MadeChange = true;
560       ++NumBranchOpts;
561       return OptimizeBlock(MBB);
562     }
563     
564     // If the previous branch *only* branches to *this* block (conditional or
565     // not) remove the branch.
566     if (PriorTBB == MBB && PriorFBB == 0) {
567       TII->RemoveBranch(PrevBB);
568       MadeChange = true;
569       ++NumBranchOpts;
570       return OptimizeBlock(MBB);
571     }
572     
573     // If the prior block branches somewhere else on the condition and here if
574     // the condition is false, remove the uncond second branch.
575     if (PriorFBB == MBB) {
576       TII->RemoveBranch(PrevBB);
577       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
578       MadeChange = true;
579       ++NumBranchOpts;
580       return OptimizeBlock(MBB);
581     }
582     
583     // If the prior block branches here on true and somewhere else on false, and
584     // if the branch condition is reversible, reverse the branch to create a
585     // fall-through.
586     if (PriorTBB == MBB) {
587       std::vector<MachineOperand> NewPriorCond(PriorCond);
588       if (!TII->ReverseBranchCondition(NewPriorCond)) {
589         TII->RemoveBranch(PrevBB);
590         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
591         MadeChange = true;
592         ++NumBranchOpts;
593         return OptimizeBlock(MBB);
594       }
595     }
596   }
597   
598   // Analyze the branch in the current block.
599   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
600   std::vector<MachineOperand> CurCond;
601   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
602   if (!CurUnAnalyzable) {
603     // If the CFG for the prior block has extra edges, remove them.
604     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
605                                        !CurCond.empty(),
606                                        ++MachineFunction::iterator(MBB));
607
608     // If this branch is the only thing in its block, see if we can forward
609     // other blocks across it.
610     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
611         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
612       // This block may contain just an unconditional branch.  Because there can
613       // be 'non-branch terminators' in the block, try removing the branch and
614       // then seeing if the block is empty.
615       TII->RemoveBranch(*MBB);
616
617       // If this block is just an unconditional branch to CurTBB, we can
618       // usually completely eliminate the block.  The only case we cannot
619       // completely eliminate the block is when the block before this one
620       // falls through into MBB and we can't understand the prior block's branch
621       // condition.
622       if (MBB->empty()) {
623         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
624         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
625             !PrevBB.isSuccessor(MBB)) {
626           // If the prior block falls through into us, turn it into an
627           // explicit branch to us to make updates simpler.
628           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
629               PriorTBB != MBB && PriorFBB != MBB) {
630             if (PriorTBB == 0) {
631               assert(PriorCond.empty() && PriorFBB == 0 &&
632                      "Bad branch analysis");
633               PriorTBB = MBB;
634             } else {
635               assert(PriorFBB == 0 && "Machine CFG out of date!");
636               PriorFBB = MBB;
637             }
638             TII->RemoveBranch(PrevBB);
639             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
640           }
641
642           // Iterate through all the predecessors, revectoring each in-turn.
643           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
644           bool DidChange = false;
645           bool HasBranchToSelf = false;
646           while (PI != MBB->pred_end()) {
647             if (*PI == MBB) {
648               // If this block has an uncond branch to itself, leave it.
649               ++PI;
650               HasBranchToSelf = true;
651             } else {
652               DidChange = true;
653               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
654             }
655           }
656
657           // Change any jumptables to go to the new MBB.
658           MBB->getParent()->getJumpTableInfo()->
659             ReplaceMBBInJumpTables(MBB, CurTBB);
660           if (DidChange) {
661             ++NumBranchOpts;
662             MadeChange = true;
663             if (!HasBranchToSelf) return;
664           }
665         }
666       }
667       
668       // Add the branch back if the block is more than just an uncond branch.
669       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
670     }
671   }
672
673   // If the prior block doesn't fall through into this block, and if this
674   // block doesn't fall through into some other block, see if we can find a
675   // place to move this block where a fall-through will happen.
676   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
677                       PriorTBB, PriorFBB, PriorCond)) {
678     // Now we know that there was no fall-through into this block, check to
679     // see if it has a fall-through into its successor.
680     if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
681       // Check all the predecessors of this block.  If one of them has no fall
682       // throughs, move this block right after it.
683       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
684            E = MBB->pred_end(); PI != E; ++PI) {
685         // Analyze the branch at the end of the pred.
686         MachineBasicBlock *PredBB = *PI;
687         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
688         MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
689         std::vector<MachineOperand> PredCond;
690         if (PredBB != MBB && !CanFallThrough(PredBB)) {
691           MBB->moveAfter(PredBB);
692           MadeChange = true;
693           return OptimizeBlock(MBB);
694         }
695       }
696         
697       // Check all successors to see if we can move this block before it.
698       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
699            E = MBB->succ_end(); SI != E; ++SI) {
700         // Analyze the branch at the end of the block before the succ.
701         MachineBasicBlock *SuccBB = *SI;
702         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
703         MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
704         std::vector<MachineOperand> SuccPrevCond;
705         if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
706           MBB->moveBefore(SuccBB);
707           MadeChange = true;
708           return OptimizeBlock(MBB);
709         }
710       }
711       
712       // Okay, there is no really great place to put this block.  If, however,
713       // the block before this one would be a fall-through if this block were
714       // removed, move this block to the end of the function.
715       if (FallThrough != MBB->getParent()->end() &&
716           PrevBB.isSuccessor(FallThrough)) {
717         MBB->moveAfter(--MBB->getParent()->end());
718         MadeChange = true;
719         return;
720       }
721     }
722   }
723 }