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