1 //===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
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 propagates information about conditional expressions through the
11 // program, allowing it to eliminate conditional branches in some cases.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "condprop"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Type.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/Statistic.h"
30 NumBrThread("condprop", "Number of CFG edges threaded through branches");
32 NumSwThread("condprop", "Number of CFG edges threaded through switches");
34 struct CondProp : public FunctionPass {
35 virtual bool runOnFunction(Function &F);
37 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38 AU.addRequiredID(BreakCriticalEdgesID);
39 //AU.addRequired<DominanceFrontier>();
44 void SimplifyBlock(BasicBlock *BB);
45 void SimplifyPredecessors(BranchInst *BI);
46 void SimplifyPredecessors(SwitchInst *SI);
47 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
49 RegisterOpt<CondProp> X("condprop", "Conditional Propagation");
52 FunctionPass *llvm::createCondPropagationPass() {
53 return new CondProp();
56 bool CondProp::runOnFunction(Function &F) {
57 bool EverMadeChange = false;
59 // While we are simplifying blocks, keep iterating.
62 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
64 EverMadeChange = MadeChange;
66 return EverMadeChange;
69 void CondProp::SimplifyBlock(BasicBlock *BB) {
70 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
71 // If this is a conditional branch based on a phi node that is defined in
72 // this block, see if we can simplify predecessors of this block.
73 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
74 cast<PHINode>(BI->getCondition())->getParent() == BB)
75 SimplifyPredecessors(BI);
77 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
78 if (isa<PHINode>(SI->getCondition()) &&
79 cast<PHINode>(SI->getCondition())->getParent() == BB)
80 SimplifyPredecessors(SI);
83 // If possible, simplify the terminator of this block.
84 if (ConstantFoldTerminator(BB))
87 // If this block ends with an unconditional branch and the only successor has
88 // only this block as a predecessor, merge the two blocks together.
89 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
90 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor()) {
91 BasicBlock *Succ = BI->getSuccessor(0);
93 BI->eraseFromParent();
95 // Move over all of the instructions.
96 BB->getInstList().splice(BB->end(), Succ->getInstList());
98 // Any phi nodes that had entries for Succ now have entries from BB.
99 Succ->replaceAllUsesWith(BB);
101 // Succ is now dead, but we cannot delete it without potentially
102 // invalidating iterators elsewhere. Just insert an unreachable
103 // instruction in it.
104 new UnreachableInst(Succ);
109 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
110 // based on a PHI node defined in this block. If the phi node contains constant
111 // operands, then the blocks corresponding to those operands can be modified to
112 // jump directly to the destination instead of going through this block.
113 void CondProp::SimplifyPredecessors(BranchInst *BI) {
114 // TODO: We currently only handle the most trival case, where the PHI node has
115 // one use (the branch), and is the only instruction besides the branch in the
117 PHINode *PN = cast<PHINode>(BI->getCondition());
118 if (!PN->hasOneUse()) return;
120 BasicBlock *BB = BI->getParent();
121 if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
124 // Ok, we have this really simple case, walk the PHI operands, looking for
125 // constants. Walk from the end to remove operands from the end when
126 // possible, and to avoid invalidating "i".
127 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
128 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i-1))) {
129 // If we have a constant, forward the edge from its current to its
130 // ultimate destination.
131 bool PHIGone = PN->getNumIncomingValues() == 2;
132 RevectorBlockTo(PN->getIncomingBlock(i-1),
133 BI->getSuccessor(CB->getValue() == 0));
136 // If there were two predecessors before this simplification, the PHI node
137 // will be deleted. Don't iterate through it the last time.
142 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
143 // defined in this block. If the phi node contains constant operands, then the
144 // blocks corresponding to those operands can be modified to jump directly to
145 // the destination instead of going through this block.
146 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
147 // TODO: We currently only handle the most trival case, where the PHI node has
148 // one use (the branch), and is the only instruction besides the branch in the
150 PHINode *PN = cast<PHINode>(SI->getCondition());
151 if (!PN->hasOneUse()) return;
153 BasicBlock *BB = SI->getParent();
154 if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
157 bool RemovedPreds = false;
159 // Ok, we have this really simple case, walk the PHI operands, looking for
160 // constants. Walk from the end to remove operands from the end when
161 // possible, and to avoid invalidating "i".
162 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
163 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
164 // If we have a constant, forward the edge from its current to its
165 // ultimate destination.
166 bool PHIGone = PN->getNumIncomingValues() == 2;
167 unsigned DestCase = SI->findCaseValue(CI);
168 RevectorBlockTo(PN->getIncomingBlock(i-1),
169 SI->getSuccessor(DestCase));
173 // If there were two predecessors before this simplification, the PHI node
174 // will be deleted. Don't iterate through it the last time.
180 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
181 // the ToBB block, which is one of the successors of its current successor.
182 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
183 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
184 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
186 // Get the old block we are threading through.
187 BasicBlock *OldSucc = FromBr->getSuccessor(0);
189 // ToBB should not have any PHI nodes in it to update, because OldSucc had
190 // multiple successors. If OldSucc had multiple successor and ToBB had
191 // multiple predecessors, the edge between them would be critical, which we
192 // already took care of.
193 assert(!isa<PHINode>(ToBB->begin()) && "Critical Edge Found!");
195 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
196 OldSucc->removePredecessor(FromBB);
198 // Change FromBr to branch to the new destination.
199 FromBr->setSuccessor(0, ToBB);