efc382bcfa569412384e03d1298f59403f117eeb
[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 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     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 LABEL
78   // records in the basic block.  If so, unregister them from MachineDebugInfo.
79   if (MDI && !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         MDI->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   MDI = getAnalysisToUpdate<MachineDebugInfo>();
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   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
435     MachineBasicBlock *MBB = I++;
436     OptimizeBlock(MBB);
437     
438     // If it is dead, remove it.
439     if (MBB->pred_empty()) {
440       RemoveDeadBlock(MBB);
441       MadeChange = true;
442       ++NumDeadBlocks;
443     }
444   }
445   return MadeChange;
446 }
447
448
449 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
450 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
451 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
452 /// be null.
453 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
454                                  MachineBasicBlock *DestA,
455                                  MachineBasicBlock *DestB,
456                                  bool isCond, 
457                                  MachineFunction::iterator FallThru) {
458   bool MadeChange = false;
459   bool AddedFallThrough = false;
460   
461   // If this block ends with a conditional branch that falls through to its
462   // successor, set DestB as the successor.
463   if (isCond) {
464     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
465       DestB = FallThru;
466       AddedFallThrough = true;
467     }
468   } else {
469     // If this is an unconditional branch with no explicit dest, it must just be
470     // a fallthrough into DestB.
471     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
472       DestA = FallThru;
473       AddedFallThrough = true;
474     }
475   }
476   
477   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
478   while (SI != MBB.succ_end()) {
479     if (*SI == DestA) {
480       DestA = 0;
481       ++SI;
482     } else if (*SI == DestB) {
483       DestB = 0;
484       ++SI;
485     } else {
486       // Otherwise, this is a superfluous edge, remove it.
487       MBB.removeSuccessor(SI);
488       MadeChange = true;
489     }
490   }
491   if (!AddedFallThrough) {
492     assert(DestA == 0 && DestB == 0 &&
493            "MachineCFG is missing edges!");
494   } else if (isCond) {
495     assert(DestA == 0 && "MachineCFG is missing edges!");
496   }
497   return MadeChange;
498 }
499
500
501 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
502 /// 'Old', change the code and CFG so that it branches to 'New' instead.
503 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
504                                    MachineBasicBlock *Old,
505                                    MachineBasicBlock *New,
506                                    const TargetInstrInfo *TII) {
507   assert(Old != New && "Cannot replace self with self!");
508
509   MachineBasicBlock::iterator I = BB->end();
510   while (I != BB->begin()) {
511     --I;
512     if (!TII->isTerminatorInstr(I->getOpcode())) break;
513
514     // Scan the operands of this machine instruction, replacing any uses of Old
515     // with New.
516     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
517       if (I->getOperand(i).isMachineBasicBlock() &&
518           I->getOperand(i).getMachineBasicBlock() == Old)
519         I->getOperand(i).setMachineBasicBlock(New);
520   }
521
522   // Update the successor information.
523   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
524   for (int i = Succs.size()-1; i >= 0; --i)
525     if (Succs[i] == Old) {
526       BB->removeSuccessor(Old);
527       BB->addSuccessor(New);
528     }
529 }
530
531 /// CanFallThrough - Return true if the specified block (with the specified
532 /// branch condition) can implicitly transfer control to the block after it by
533 /// falling off the end of it.  This should return false if it can reach the
534 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
535 ///
536 /// True is a conservative answer.
537 ///
538 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
539                                   bool BranchUnAnalyzable,
540                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
541                                   const std::vector<MachineOperand> &Cond) {
542   MachineFunction::iterator Fallthrough = CurBB;
543   ++Fallthrough;
544   // If FallthroughBlock is off the end of the function, it can't fall through.
545   if (Fallthrough == CurBB->getParent()->end())
546     return false;
547   
548   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
549   if (!CurBB->isSuccessor(Fallthrough))
550     return false;
551   
552   // If we couldn't analyze the branch, assume it could fall through.
553   if (BranchUnAnalyzable) return true;
554   
555   // If there is no branch, control always falls through.
556   if (TBB == 0) return true;
557
558   // If there is some explicit branch to the fallthrough block, it can obviously
559   // reach, even though the branch should get folded to fall through implicitly.
560   if (MachineFunction::iterator(TBB) == Fallthrough ||
561       MachineFunction::iterator(FBB) == Fallthrough)
562     return true;
563   
564   // If it's an unconditional branch to some block not the fall through, it 
565   // doesn't fall through.
566   if (Cond.empty()) return false;
567   
568   // Otherwise, if it is conditional and has no explicit false block, it falls
569   // through.
570   return FBB == 0;
571 }
572
573 /// CanFallThrough - Return true if the specified can implicitly transfer
574 /// control to the block after it by falling off the end of it.  This should
575 /// return false if it can reach the block after it, but it uses an explicit
576 /// branch to do so (e.g. a table jump).
577 ///
578 /// True is a conservative answer.
579 ///
580 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
581   MachineBasicBlock *TBB = 0, *FBB = 0;
582   std::vector<MachineOperand> Cond;
583   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
584   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
585 }
586
587 /// IsBetterFallthrough - Return true if it would be clearly better to
588 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
589 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
590 /// result in infinite loops.
591 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
592                                 MachineBasicBlock *MBB2,
593                                 const TargetInstrInfo &TII) {
594   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
595   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
596   // optimize branches that branch to either a return block or an assert block
597   // into a fallthrough to the return.
598   if (MBB1->empty() || MBB2->empty()) return false;
599
600   MachineInstr *MBB1I = --MBB1->end();
601   MachineInstr *MBB2I = --MBB2->end();
602   return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
603 }
604
605 /// OptimizeBlock - Analyze and optimize control flow related to the specified
606 /// block.  This is never called on the entry block.
607 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
608   MachineFunction::iterator FallThrough = MBB;
609   ++FallThrough;
610   
611   // If this block is empty, make everyone use its fall-through, not the block
612   // explicitly.
613   if (MBB->empty()) {
614     // Dead block?  Leave for cleanup later.
615     if (MBB->pred_empty()) return;
616     
617     if (FallThrough == MBB->getParent()->end()) {
618       // TODO: Simplify preds to not branch here if possible!
619     } else {
620       // Rewrite all predecessors of the old block to go to the fallthrough
621       // instead.
622       while (!MBB->pred_empty()) {
623         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
624         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
625       }
626       
627       // If MBB was the target of a jump table, update jump tables to go to the
628       // fallthrough instead.
629       MBB->getParent()->getJumpTableInfo()->
630         ReplaceMBBInJumpTables(MBB, FallThrough);
631       MadeChange = true;
632     }
633     return;
634   }
635
636   // Check to see if we can simplify the terminator of the block before this
637   // one.
638   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
639
640   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
641   std::vector<MachineOperand> PriorCond;
642   bool PriorUnAnalyzable =
643     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
644   if (!PriorUnAnalyzable) {
645     // If the CFG for the prior block has extra edges, remove them.
646     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
647                                        !PriorCond.empty(), MBB);
648     
649     // If the previous branch is conditional and both conditions go to the same
650     // destination, remove the branch, replacing it with an unconditional one or
651     // a fall-through.
652     if (PriorTBB && PriorTBB == PriorFBB) {
653       TII->RemoveBranch(PrevBB);
654       PriorCond.clear(); 
655       if (PriorTBB != MBB)
656         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
657       MadeChange = true;
658       ++NumBranchOpts;
659       return OptimizeBlock(MBB);
660     }
661     
662     // If the previous branch *only* branches to *this* block (conditional or
663     // not) remove the branch.
664     if (PriorTBB == MBB && PriorFBB == 0) {
665       TII->RemoveBranch(PrevBB);
666       MadeChange = true;
667       ++NumBranchOpts;
668       return OptimizeBlock(MBB);
669     }
670     
671     // If the prior block branches somewhere else on the condition and here if
672     // the condition is false, remove the uncond second branch.
673     if (PriorFBB == MBB) {
674       TII->RemoveBranch(PrevBB);
675       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
676       MadeChange = true;
677       ++NumBranchOpts;
678       return OptimizeBlock(MBB);
679     }
680     
681     // If the prior block branches here on true and somewhere else on false, and
682     // if the branch condition is reversible, reverse the branch to create a
683     // fall-through.
684     if (PriorTBB == MBB) {
685       std::vector<MachineOperand> NewPriorCond(PriorCond);
686       if (!TII->ReverseBranchCondition(NewPriorCond)) {
687         TII->RemoveBranch(PrevBB);
688         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
689         MadeChange = true;
690         ++NumBranchOpts;
691         return OptimizeBlock(MBB);
692       }
693     }
694     
695     // If this block doesn't fall through (e.g. it ends with an uncond branch or
696     // has no successors) and if the pred falls through into this block, and if
697     // it would otherwise fall through into the block after this, move this
698     // block to the end of the function.
699     //
700     // We consider it more likely that execution will stay in the function (e.g.
701     // due to loops) than it is to exit it.  This asserts in loops etc, moving
702     // the assert condition out of the loop body.
703     if (!PriorCond.empty() && PriorFBB == 0 &&
704         MachineFunction::iterator(PriorTBB) == FallThrough &&
705         !CanFallThrough(MBB)) {
706       bool DoTransform = true;
707       
708       // We have to be careful that the succs of PredBB aren't both no-successor
709       // blocks.  If neither have successors and if PredBB is the second from
710       // last block in the function, we'd just keep swapping the two blocks for
711       // last.  Only do the swap if one is clearly better to fall through than
712       // the other.
713       if (FallThrough == --MBB->getParent()->end() &&
714           !IsBetterFallthrough(PriorTBB, MBB, *TII))
715         DoTransform = false;
716
717       // We don't want to do this transformation if we have control flow like:
718       //   br cond BB2
719       // BB1:
720       //   ..
721       //   jmp BBX
722       // BB2:
723       //   ..
724       //   ret
725       //
726       // In this case, we could actually be moving the return block *into* a
727       // loop!
728       if (DoTransform && !MBB->succ_empty() &&
729           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
730         DoTransform = false;
731       
732       
733       if (DoTransform) {
734         // Reverse the branch so we will fall through on the previous true cond.
735         std::vector<MachineOperand> NewPriorCond(PriorCond);
736         if (!TII->ReverseBranchCondition(NewPriorCond)) {
737           DOUT << "\nMoving MBB: " << *MBB;
738           DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
739           
740           TII->RemoveBranch(PrevBB);
741           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
742
743           // Move this block to the end of the function.
744           MBB->moveAfter(--MBB->getParent()->end());
745           MadeChange = true;
746           ++NumBranchOpts;
747           return;
748         }
749       }
750     }
751   }
752   
753   // Analyze the branch in the current block.
754   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
755   std::vector<MachineOperand> CurCond;
756   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
757   if (!CurUnAnalyzable) {
758     // If the CFG for the prior block has extra edges, remove them.
759     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
760                                        !CurCond.empty(),
761                                        ++MachineFunction::iterator(MBB));
762
763     // If this is a two-way branch, and the FBB branches to this block, reverse 
764     // the condition so the single-basic-block loop is faster.  Instead of:
765     //    Loop: xxx; jcc Out; jmp Loop
766     // we want:
767     //    Loop: xxx; jncc Loop; jmp Out
768     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
769       std::vector<MachineOperand> NewCond(CurCond);
770       if (!TII->ReverseBranchCondition(NewCond)) {
771         TII->RemoveBranch(*MBB);
772         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
773         MadeChange = true;
774         ++NumBranchOpts;
775         return OptimizeBlock(MBB);
776       }
777     }
778     
779     
780     // If this branch is the only thing in its block, see if we can forward
781     // other blocks across it.
782     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
783         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
784       // This block may contain just an unconditional branch.  Because there can
785       // be 'non-branch terminators' in the block, try removing the branch and
786       // then seeing if the block is empty.
787       TII->RemoveBranch(*MBB);
788
789       // If this block is just an unconditional branch to CurTBB, we can
790       // usually completely eliminate the block.  The only case we cannot
791       // completely eliminate the block is when the block before this one
792       // falls through into MBB and we can't understand the prior block's branch
793       // condition.
794       if (MBB->empty()) {
795         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
796         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
797             !PrevBB.isSuccessor(MBB)) {
798           // If the prior block falls through into us, turn it into an
799           // explicit branch to us to make updates simpler.
800           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
801               PriorTBB != MBB && PriorFBB != MBB) {
802             if (PriorTBB == 0) {
803               assert(PriorCond.empty() && PriorFBB == 0 &&
804                      "Bad branch analysis");
805               PriorTBB = MBB;
806             } else {
807               assert(PriorFBB == 0 && "Machine CFG out of date!");
808               PriorFBB = MBB;
809             }
810             TII->RemoveBranch(PrevBB);
811             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
812           }
813
814           // Iterate through all the predecessors, revectoring each in-turn.
815           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
816           bool DidChange = false;
817           bool HasBranchToSelf = false;
818           while (PI != MBB->pred_end()) {
819             if (*PI == MBB) {
820               // If this block has an uncond branch to itself, leave it.
821               ++PI;
822               HasBranchToSelf = true;
823             } else {
824               DidChange = true;
825               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
826             }
827           }
828
829           // Change any jumptables to go to the new MBB.
830           MBB->getParent()->getJumpTableInfo()->
831             ReplaceMBBInJumpTables(MBB, CurTBB);
832           if (DidChange) {
833             ++NumBranchOpts;
834             MadeChange = true;
835             if (!HasBranchToSelf) return;
836           }
837         }
838       }
839       
840       // Add the branch back if the block is more than just an uncond branch.
841       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
842     }
843   }
844
845   // If the prior block doesn't fall through into this block, and if this
846   // block doesn't fall through into some other block, see if we can find a
847   // place to move this block where a fall-through will happen.
848   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
849                       PriorTBB, PriorFBB, PriorCond)) {
850     // Now we know that there was no fall-through into this block, check to
851     // see if it has a fall-through into its successor.
852     if (!CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, CurCond)) {
853       // Check all the predecessors of this block.  If one of them has no fall
854       // throughs, move this block right after it.
855       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
856            E = MBB->pred_end(); PI != E; ++PI) {
857         // Analyze the branch at the end of the pred.
858         MachineBasicBlock *PredBB = *PI;
859         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
860         std::vector<MachineOperand> PredCond;
861         if (PredBB != MBB && !CanFallThrough(PredBB)) {
862           MBB->moveAfter(PredBB);
863           MadeChange = true;
864           return OptimizeBlock(MBB);
865         }
866       }
867         
868       // Check all successors to see if we can move this block before it.
869       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
870            E = MBB->succ_end(); SI != E; ++SI) {
871         // Analyze the branch at the end of the block before the succ.
872         MachineBasicBlock *SuccBB = *SI;
873         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
874         std::vector<MachineOperand> SuccPrevCond;
875         if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
876           MBB->moveBefore(SuccBB);
877           MadeChange = true;
878           return OptimizeBlock(MBB);
879         }
880       }
881       
882       // Okay, there is no really great place to put this block.  If, however,
883       // the block before this one would be a fall-through if this block were
884       // removed, move this block to the end of the function.
885       if (FallThrough != MBB->getParent()->end() &&
886           PrevBB.isSuccessor(FallThrough)) {
887         MBB->moveAfter(--MBB->getParent()->end());
888         MadeChange = true;
889         return;
890       }
891     }
892   }
893 }