refactor the interface to ConvertUsesOfLoadToScalar,
[oota-llvm.git] / lib / Transforms / Scalar / CondPropagate.cpp
1 //===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
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"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Type.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Streams.h"
28 using namespace llvm;
29
30 STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
31 STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
32
33 namespace {
34   struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
35     static char ID; // Pass identification, replacement for typeid
36     CondProp() : FunctionPass(&ID) {}
37
38     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   };
52 }
53   
54 char CondProp::ID = 0;
55 static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
56
57 FunctionPass *llvm::createCondPropagationPass() {
58   return new CondProp();
59 }
60
61 bool 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);
69     EverMadeChange = EverMadeChange || MadeChange;
70   } while (MadeChange);
71   return EverMadeChange;
72 }
73
74 void 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);
81
82   } 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
88   // 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()))
95     if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
96         BB != BI->getSuccessor(0)) {
97       BasicBlock *Succ = BI->getSuccessor(0);
98       
99       // If Succ has any PHI nodes, they are all single-entry PHI's.  Eliminate
100       // them.
101       FoldSingleEntryPHINodes(Succ);
102       
103       // 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.
124 void 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
130   if (PN->getNumIncomingValues() == 1) {
131     // Eliminate single-entry PHI nodes.
132     FoldSingleEntryPHINodes(PN->getParent());
133     return;
134   }
135   
136   
137   if (!PN->hasOneUse()) return;
138
139   BasicBlock *BB = BI->getParent();
140   if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
141     return;
142
143   // Ok, we have this really simple case, walk the PHI operands, looking for
144   // constants.  Walk from the end to remove operands from the end when
145   // possible, and to avoid invalidating "i".
146   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
147     if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
148       // If we have a constant, forward the edge from its current to its
149       // ultimate destination.
150       RevectorBlockTo(PN->getIncomingBlock(i-1),
151                       BI->getSuccessor(CB->isZero()));
152       ++NumBrThread;
153
154       // If there were two predecessors before this simplification, or if the
155       // PHI node contained all the same value except for the one we just
156       // substituted, the PHI node may be deleted.  Don't iterate through it the
157       // last time.
158       if (BI->getCondition() != PN) return;
159     }
160 }
161
162 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
163 // defined in this block.  If the phi node contains constant operands, then the
164 // blocks corresponding to those operands can be modified to jump directly to
165 // the destination instead of going through this block.
166 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
167   // TODO: We currently only handle the most trival case, where the PHI node has
168   // one use (the branch), and is the only instruction besides the branch in the
169   // block.
170   PHINode *PN = cast<PHINode>(SI->getCondition());
171   if (!PN->hasOneUse()) return;
172
173   BasicBlock *BB = SI->getParent();
174   if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
175     return;
176
177   bool RemovedPreds = false;
178
179   // Ok, we have this really simple case, walk the PHI operands, looking for
180   // constants.  Walk from the end to remove operands from the end when
181   // possible, and to avoid invalidating "i".
182   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
183     if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
184       // If we have a constant, forward the edge from its current to its
185       // ultimate destination.
186       unsigned DestCase = SI->findCaseValue(CI);
187       RevectorBlockTo(PN->getIncomingBlock(i-1),
188                       SI->getSuccessor(DestCase));
189       ++NumSwThread;
190       RemovedPreds = true;
191
192       // If there were two predecessors before this simplification, or if the
193       // PHI node contained all the same value except for the one we just
194       // substituted, the PHI node may be deleted.  Don't iterate through it the
195       // last time.
196       if (SI->getCondition() != PN) return;
197     }
198 }
199
200
201 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
202 // the ToBB block, which is one of the successors of its current successor.
203 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
204   BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
205   assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
206
207   // Get the old block we are threading through.
208   BasicBlock *OldSucc = FromBr->getSuccessor(0);
209
210   // OldSucc had multiple successors. If ToBB has multiple predecessors, then 
211   // the edge between them would be critical, which we already took care of.
212   // If ToBB has single operand PHI node then take care of it here.
213   FoldSingleEntryPHINodes(ToBB);
214
215   // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
216   OldSucc->removePredecessor(FromBB);
217
218   // Change FromBr to branch to the new destination.
219   FromBr->setSuccessor(0, ToBB);
220
221   MadeChange = true;
222 }