blob: 2e899432909e32e502bea65c93090b2adf295d7e [file] [log] [blame]
Chris Lattner36d12732005-04-15 19:28:32 +00001//===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner36d12732005-04-15 19:28:32 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner36d12732005-04-15 19:28:32 +00008//===----------------------------------------------------------------------===//
9//
10// This pass propagates information about conditional expressions through the
11// program, allowing it to eliminate conditional branches in some cases.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "condprop"
16#include "llvm/Transforms/Scalar.h"
Chris Lattner36d12732005-04-15 19:28:32 +000017#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Pass.h"
21#include "llvm/Type.h"
Chris Lattner29874e02008-12-03 19:44:02 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattner36d12732005-04-15 19:28:32 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000026#include "llvm/Support/Compiler.h"
Bill Wendlingb7427032006-11-26 09:46:52 +000027#include "llvm/Support/Streams.h"
Chris Lattner36d12732005-04-15 19:28:32 +000028using namespace llvm;
29
Chris Lattner0e5f4992006-12-19 21:40:18 +000030STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
31STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
Chris Lattner36d12732005-04-15 19:28:32 +000032
Chris Lattner0e5f4992006-12-19 21:40:18 +000033namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000034 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000035 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000036 CondProp() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000037
Chris Lattner36d12732005-04-15 19:28:32 +000038 virtual bool runOnFunction(Function &F);
39
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequiredID(BreakCriticalEdgesID);
42 //AU.addRequired<DominanceFrontier>();
43 }
44
45 private:
46 bool MadeChange;
47 void SimplifyBlock(BasicBlock *BB);
48 void SimplifyPredecessors(BranchInst *BI);
49 void SimplifyPredecessors(SwitchInst *SI);
50 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
51 };
Chris Lattner36d12732005-04-15 19:28:32 +000052}
Dan Gohman844731a2008-05-13 00:00:25 +000053
54char CondProp::ID = 0;
55static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
Chris Lattner36d12732005-04-15 19:28:32 +000056
57FunctionPass *llvm::createCondPropagationPass() {
58 return new CondProp();
59}
60
61bool CondProp::runOnFunction(Function &F) {
62 bool EverMadeChange = false;
63
64 // While we are simplifying blocks, keep iterating.
65 do {
66 MadeChange = false;
67 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
68 SimplifyBlock(BB);
Devang Patel70b36d92007-07-26 20:21:42 +000069 EverMadeChange = EverMadeChange || MadeChange;
Chris Lattner36d12732005-04-15 19:28:32 +000070 } while (MadeChange);
71 return EverMadeChange;
72}
73
74void CondProp::SimplifyBlock(BasicBlock *BB) {
75 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
76 // If this is a conditional branch based on a phi node that is defined in
77 // this block, see if we can simplify predecessors of this block.
78 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
79 cast<PHINode>(BI->getCondition())->getParent() == BB)
80 SimplifyPredecessors(BI);
Misha Brukmanfd939082005-04-21 23:48:37 +000081
Chris Lattner36d12732005-04-15 19:28:32 +000082 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
83 if (isa<PHINode>(SI->getCondition()) &&
84 cast<PHINode>(SI->getCondition())->getParent() == BB)
85 SimplifyPredecessors(SI);
86 }
87
Chris Lattner36d12732005-04-15 19:28:32 +000088 // If possible, simplify the terminator of this block.
89 if (ConstantFoldTerminator(BB))
90 MadeChange = true;
91
92 // If this block ends with an unconditional branch and the only successor has
93 // only this block as a predecessor, merge the two blocks together.
94 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
Chris Lattnerdf32aac2006-08-14 21:38:05 +000095 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
96 BB != BI->getSuccessor(0)) {
Chris Lattner36d12732005-04-15 19:28:32 +000097 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerdf32aac2006-08-14 21:38:05 +000098
Chris Lattner29874e02008-12-03 19:44:02 +000099 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
100 // them.
101 FoldSingleEntryPHINodes(Succ);
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000102
Chris Lattner36d12732005-04-15 19:28:32 +0000103 // Remove BI.
104 BI->eraseFromParent();
105
106 // Move over all of the instructions.
107 BB->getInstList().splice(BB->end(), Succ->getInstList());
108
109 // Any phi nodes that had entries for Succ now have entries from BB.
110 Succ->replaceAllUsesWith(BB);
111
112 // Succ is now dead, but we cannot delete it without potentially
113 // invalidating iterators elsewhere. Just insert an unreachable
114 // instruction in it.
115 new UnreachableInst(Succ);
116 MadeChange = true;
117 }
118}
119
120// SimplifyPredecessors(branches) - We know that BI is a conditional branch
121// based on a PHI node defined in this block. If the phi node contains constant
122// operands, then the blocks corresponding to those operands can be modified to
123// jump directly to the destination instead of going through this block.
124void CondProp::SimplifyPredecessors(BranchInst *BI) {
125 // TODO: We currently only handle the most trival case, where the PHI node has
126 // one use (the branch), and is the only instruction besides the branch in the
127 // block.
128 PHINode *PN = cast<PHINode>(BI->getCondition());
129 if (!PN->hasOneUse()) return;
130
131 BasicBlock *BB = BI->getParent();
132 if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
133 return;
134
135 // Ok, we have this really simple case, walk the PHI operands, looking for
136 // constants. Walk from the end to remove operands from the end when
137 // possible, and to avoid invalidating "i".
138 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000139 if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
Chris Lattner36d12732005-04-15 19:28:32 +0000140 // If we have a constant, forward the edge from its current to its
141 // ultimate destination.
Chris Lattner36d12732005-04-15 19:28:32 +0000142 RevectorBlockTo(PN->getIncomingBlock(i-1),
Reid Spencercae57542007-03-02 00:28:52 +0000143 BI->getSuccessor(CB->isZero()));
Chris Lattner36d12732005-04-15 19:28:32 +0000144 ++NumBrThread;
145
Chris Lattner9dd7a512007-08-02 04:47:05 +0000146 // If there were two predecessors before this simplification, or if the
147 // PHI node contained all the same value except for the one we just
148 // substituted, the PHI node may be deleted. Don't iterate through it the
149 // last time.
150 if (BI->getCondition() != PN) return;
Chris Lattner36d12732005-04-15 19:28:32 +0000151 }
152}
153
154// SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
155// defined in this block. If the phi node contains constant operands, then the
156// blocks corresponding to those operands can be modified to jump directly to
157// the destination instead of going through this block.
158void CondProp::SimplifyPredecessors(SwitchInst *SI) {
159 // TODO: We currently only handle the most trival case, where the PHI node has
160 // one use (the branch), and is the only instruction besides the branch in the
161 // block.
162 PHINode *PN = cast<PHINode>(SI->getCondition());
163 if (!PN->hasOneUse()) return;
164
165 BasicBlock *BB = SI->getParent();
166 if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
167 return;
168
169 bool RemovedPreds = false;
170
171 // Ok, we have this really simple case, walk the PHI operands, looking for
172 // constants. Walk from the end to remove operands from the end when
173 // possible, and to avoid invalidating "i".
174 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
175 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
176 // If we have a constant, forward the edge from its current to its
177 // ultimate destination.
Chris Lattner36d12732005-04-15 19:28:32 +0000178 unsigned DestCase = SI->findCaseValue(CI);
179 RevectorBlockTo(PN->getIncomingBlock(i-1),
180 SI->getSuccessor(DestCase));
181 ++NumSwThread;
182 RemovedPreds = true;
183
Chris Lattner9dd7a512007-08-02 04:47:05 +0000184 // If there were two predecessors before this simplification, or if the
185 // PHI node contained all the same value except for the one we just
186 // substituted, the PHI node may be deleted. Don't iterate through it the
187 // last time.
188 if (SI->getCondition() != PN) return;
Chris Lattner36d12732005-04-15 19:28:32 +0000189 }
190}
191
192
193// RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
194// the ToBB block, which is one of the successors of its current successor.
195void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
196 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
197 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
198
199 // Get the old block we are threading through.
200 BasicBlock *OldSucc = FromBr->getSuccessor(0);
201
Devang Patele0805a22006-11-01 23:04:45 +0000202 // OldSucc had multiple successors. If ToBB has multiple predecessors, then
203 // the edge between them would be critical, which we already took care of.
204 // If ToBB has single operand PHI node then take care of it here.
Chris Lattner29874e02008-12-03 19:44:02 +0000205 FoldSingleEntryPHINodes(ToBB);
Chris Lattner36d12732005-04-15 19:28:32 +0000206
207 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
208 OldSucc->removePredecessor(FromBB);
209
210 // Change FromBr to branch to the new destination.
211 FromBr->setSuccessor(0, ToBB);
212
213 MadeChange = true;
214}