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