1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
14 // Note that this pass must be run after register allocation, it cannot handle
17 //===----------------------------------------------------------------------===//
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"
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;
34 void OptimizeBlock(MachineFunction::iterator MBB);
38 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
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);
49 MF->getBasicBlockList().erase(MBB);
52 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
53 TII = MF.getTarget().getInstrInfo();
54 if (!TII) return false;
58 bool EverMadeChange = false;
63 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
64 MachineBasicBlock *MBB = I++;
67 // If it is dead, remove it.
68 if (MBB->pred_empty()) {
73 EverMadeChange |= MadeChange;
76 return EverMadeChange;
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!");
87 MachineBasicBlock::iterator I = BB->end();
88 while (I != BB->begin()) {
90 if (!TII->isTerminatorInstr(I->getOpcode())) break;
92 // Scan the operands of this machine instruction, replacing any uses of Old
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);
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);
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
115 if (MBB->pred_empty()) return; // dead block? Leave for cleanup later.
117 MachineFunction::iterator FallThrough = next(MBB);
119 if (FallThrough == MBB->getParent()->end()) {
120 // TODO: Simplify preds to not branch here if possible!
122 // Rewrite all predecessors of the old block to go to the fallthrough
124 while (!MBB->pred_empty()) {
125 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
126 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
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,
138 // Check to see if we can simplify the terminator of the block before this
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));
149 if (PriorTBB != &*MBB)
150 TII->InsertBranch(*prior(MBB), PriorTBB, 0, PriorCond);
152 return OptimizeBlock(MBB);
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));
160 return OptimizeBlock(MBB);
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.
177 while (!Pred->empty() && TII.isTerminatorInstr(Pred->back().getOpcode()))
180 // Splice the instructions over.
181 Pred->splice(Pred->end(), MBB, MBB->begin(), MBB->end());
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));
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);
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);
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.
212 while (!Pred->empty() && TII.isTerminatorInstr(Pred->back().getOpcode()))
215 // Splice the instructions over.
216 Pred->splice(Pred->end(), MBB, MBB->begin(), MBB->end());
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));
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);
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();
240 while (!MBB->pred_empty()) {
241 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
242 ReplaceUsesOfBlockWith(Pred, MBB, Dest, TII);
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);
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);
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);