b589c03f56d93b3c04ba65ed38d002d7f9462a9f
[oota-llvm.git] / lib / CodeGen / BranchFolding.cpp
1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass forwards branches to unconditional branches to make them branch
11 // directly to the target block.  This pass often results in dead MBB's, which
12 // it then removes.
13 //
14 // Note that this pass must be run after register allocation, it cannot handle
15 // SSA form.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/ADT/STLExtras.h"
25 using namespace llvm;
26
27 namespace {
28   struct BranchFolder : public MachineFunctionPass {
29     virtual bool runOnMachineFunction(MachineFunction &MF);
30     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
31     const TargetInstrInfo *TII;
32     bool MadeChange;
33   private:
34     void OptimizeBlock(MachineFunction::iterator MBB);
35   };
36 }
37
38 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
39
40 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
41 /// function, updating the CFG.
42 static void RemoveDeadBlock(MachineBasicBlock *MBB) {
43   assert(MBB->pred_empty() && "MBB must be dead!");
44   MachineFunction *MF = MBB->getParent();
45   // drop all successors.
46   while (!MBB->succ_empty())
47     MBB->removeSuccessor(MBB->succ_end()-1);
48   // Remove the block.
49   MF->getBasicBlockList().erase(MBB);
50 }
51
52 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
53   TII = MF.getTarget().getInstrInfo();
54   if (!TII) return false;
55
56   //MF.dump();
57   
58   bool EverMadeChange = false;
59   MadeChange = true;
60   while (MadeChange) {
61     MadeChange = false;
62     
63     for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
64       MachineBasicBlock *MBB = I++;
65       OptimizeBlock(MBB);
66       
67       // If it is dead, remove it.
68       if (MBB->pred_empty()) {
69         RemoveDeadBlock(MBB);
70         MadeChange = true;
71       }
72     }      
73     EverMadeChange |= MadeChange;
74   }
75
76   return EverMadeChange;
77 }
78
79 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
80 /// 'Old', change the code and CFG so that it branches to 'New' instead.
81 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
82                                    MachineBasicBlock *Old,
83                                    MachineBasicBlock *New,
84                                    const TargetInstrInfo *TII) {
85   assert(Old != New && "Cannot replace self with self!");
86
87   MachineBasicBlock::iterator I = BB->end();
88   while (I != BB->begin()) {
89     --I;
90     if (!TII->isTerminatorInstr(I->getOpcode())) break;
91
92     // Scan the operands of this machine instruction, replacing any uses of Old
93     // with New.
94     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
95       if (I->getOperand(i).isMachineBasicBlock() &&
96           I->getOperand(i).getMachineBasicBlock() == Old)
97         I->getOperand(i).setMachineBasicBlock(New);
98   }
99
100   // Update the successor information.
101   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
102   for (int i = Succs.size()-1; i >= 0; --i)
103     if (Succs[i] == Old) {
104       BB->removeSuccessor(Old);
105       BB->addSuccessor(New);
106     }
107 }
108
109 /// OptimizeBlock - Analyze and optimize control flow related to the specified
110 /// block.  This is never called on the entry block.
111 void BranchFolder::OptimizeBlock(MachineFunction::iterator MBB) {
112   // If this block is empty, make everyone use its fall-through, not the block
113   // explicitly.
114   if (MBB->empty()) {
115     if (MBB->pred_empty()) return;  // dead block?  Leave for cleanup later.
116     
117     MachineFunction::iterator FallThrough = next(MBB);
118     
119     if (FallThrough == MBB->getParent()->end()) {
120       // TODO: Simplify preds to not branch here if possible!
121     } else {
122       // Rewrite all predecessors of the old block to go to the fallthrough
123       // instead.
124       while (!MBB->pred_empty()) {
125         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
126         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
127       }
128       
129       // If MBB was the target of a jump table, update jump tables to go to the
130       // fallthrough instead.
131       MBB->getParent()->getJumpTableInfo()->ReplaceMBBInJumpTables(MBB,
132                                                                    FallThrough);
133       MadeChange = true;
134     }
135     return;
136   }
137
138   // Check to see if we can simplify the terminator of the block before this
139   // one.
140 #if 0
141   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
142   std::vector<MachineOperand> PriorCond;
143   if (!TII->AnalyzeBranch(*prior(MBB), PriorTBB, PriorFBB, PriorCond)) {
144     // If the previous branch is conditional and both conditions go to the same
145     // destination, remove the branch, replacing it with an unconditional one.
146     if (PriorTBB && PriorTBB == PriorFBB) {
147       TII->RemoveBranch(*prior(MBB));
148       PriorCond.clear(); 
149       if (PriorTBB != &*MBB)
150         TII->InsertBranch(*prior(MBB), PriorTBB, 0, PriorCond);
151       MadeChange = true;
152       return OptimizeBlock(MBB);
153     }
154     
155     // If the previous branch *only* branches to *this* block (conditional or
156     // not) remove the branch.
157     if (PriorTBB == &*MBB && PriorFBB == 0) {
158       TII->RemoveBranch(*prior(MBB));
159       MadeChange = true;
160       return OptimizeBlock(MBB);
161     }
162   }
163 #endif
164   
165   
166 #if 0
167
168   if (MBB->pred_size() == 1) {
169     // If this block has a single predecessor, and if that block has a single
170     // successor, merge this block into that block.
171     MachineBasicBlock *Pred = *MBB->pred_begin();
172     if (Pred->succ_size() == 1) {
173       // Delete all of the terminators from end of the pred block.  NOTE, this
174       // assumes that terminators do not have side effects!
175       // FIXME: This doesn't work for FP_REG_KILL.
176       
177       while (!Pred->empty() && TII.isTerminatorInstr(Pred->back().getOpcode()))
178         Pred->pop_back();
179       
180       // Splice the instructions over.
181       Pred->splice(Pred->end(), MBB, MBB->begin(), MBB->end());
182       
183       // If MBB does not end with a barrier, add a goto instruction to the end.
184       if (Pred->empty() || !TII.isBarrier(Pred->back().getOpcode()))
185         TII.insertGoto(*Pred, *next(MBB));
186       
187       // Update the CFG now.
188       Pred->removeSuccessor(Pred->succ_begin());
189       while (!MBB->succ_empty()) {
190         Pred->addSuccessor(*(MBB->succ_end()-1));
191         MBB->removeSuccessor(MBB->succ_end()-1);
192       }
193       return true;
194     }
195   }
196   
197   // If BB falls through into Old, insert an unconditional branch to New.
198   MachineFunction::iterator BBSucc = BB; ++BBSucc;
199   if (BBSucc != BB->getParent()->end() && &*BBSucc == Old)
200     TII.insertGoto(*BB, *New);
201   
202   
203   if (MBB->pred_size() == 1) {
204     // If this block has a single predecessor, and if that block has a single
205     // successor, merge this block into that block.
206     MachineBasicBlock *Pred = *MBB->pred_begin();
207     if (Pred->succ_size() == 1) {
208       // Delete all of the terminators from end of the pred block.  NOTE, this
209       // assumes that terminators do not have side effects!
210       // FIXME: This doesn't work for FP_REG_KILL.
211       
212       while (!Pred->empty() && TII.isTerminatorInstr(Pred->back().getOpcode()))
213         Pred->pop_back();
214
215       // Splice the instructions over.
216       Pred->splice(Pred->end(), MBB, MBB->begin(), MBB->end());
217
218       // If MBB does not end with a barrier, add a goto instruction to the end.
219       if (Pred->empty() || !TII.isBarrier(Pred->back().getOpcode()))
220         TII.insertGoto(*Pred, *next(MBB));
221
222       // Update the CFG now.
223       Pred->removeSuccessor(Pred->succ_begin());
224       while (!MBB->succ_empty()) {
225         Pred->addSuccessor(*(MBB->succ_end()-1));
226         MBB->removeSuccessor(MBB->succ_end()-1);
227       }
228       return true;
229     }
230   }
231
232   // If the first instruction in this block is an unconditional branch, and if
233   // there are predecessors, fold the branch into the predecessors.
234   if (!MBB->pred_empty() && isUncondBranch(MBB->begin(), TII)) {
235     MachineInstr *Br = MBB->begin();
236     assert(Br->getNumOperands() == 1 && Br->getOperand(0).isMachineBasicBlock()
237            && "Uncond branch should take one MBB argument!");
238     MachineBasicBlock *Dest = Br->getOperand(0).getMachineBasicBlock();
239
240     while (!MBB->pred_empty()) {
241       MachineBasicBlock *Pred = *(MBB->pred_end()-1);
242       ReplaceUsesOfBlockWith(Pred, MBB, Dest, TII);
243     }
244     return true;
245   }
246
247   // If the last instruction is an unconditional branch and the fall through
248   // block is the destination, just delete the branch.
249   if (isUncondBranch(--MBB->end(), TII)) {
250     MachineBasicBlock::iterator MI = --MBB->end();
251     MachineInstr *UncondBr = MI;
252     MachineFunction::iterator FallThrough = next(MBB);
253
254     MachineFunction::iterator UncondDest =
255       MI->getOperand(0).getMachineBasicBlock();
256     if (UncondDest == FallThrough) {
257       // Just delete the branch.  This does not effect the CFG.
258       MBB->erase(UncondBr);
259       return true;
260     }
261
262     // Okay, so we don't have a fall-through.  Check to see if we have an
263     // conditional branch that would be a fall through if we reversed it.  If
264     // so, invert the condition and delete the uncond branch.
265     if (MI != MBB->begin() && isCondBranch(--MI, TII)) {
266       // We assume that conditional branches always have the branch dest as the
267       // last operand.  This could be generalized in the future if needed.
268       unsigned LastOpnd = MI->getNumOperands()-1;
269       if (MachineFunction::iterator(
270             MI->getOperand(LastOpnd).getMachineBasicBlock()) == FallThrough) {
271         // Change the cond branch to go to the uncond dest, nuke the uncond,
272         // then reverse the condition.
273         MI->getOperand(LastOpnd).setMachineBasicBlock(UncondDest);
274         MBB->erase(UncondBr);
275         TII.reverseBranchCondition(MI);
276         return true;
277       }
278     }
279   }
280 #endif
281 }