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