blob: 305fbd85a26abca7efda9a33b5398d93a9df252f [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
Chris Lattnerbb190ac2002-10-08 21:36:33 +00003// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +00004//
5//===----------------------------------------------------------------------===//
6
7#include "llvm/Transforms/Utils/Local.h"
8#include "llvm/Constant.h"
Chris Lattnerdc3602b2003-08-24 18:36:16 +00009#include "llvm/Intrinsics.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000010#include "llvm/iPHINode.h"
Chris Lattnerdc3602b2003-08-24 18:36:16 +000011#include "llvm/iTerminators.h"
12#include "llvm/iOther.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000013#include "llvm/Support/CFG.h"
14#include <algorithm>
15#include <functional>
16
Misha Brukmana3bbcb52002-10-29 23:06:16 +000017// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner01d1ee32002-05-21 20:50:24 +000018// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
19// have extra slots added to them to hold the merge edges from BB's
Chris Lattnere2ca5402003-03-05 21:01:52 +000020// predecessors, and BB itself might have had PHI nodes in it. This function
21// returns true (failure) if the Succ BB already has a predecessor that is a
Misha Brukmancf00c4a2003-10-10 17:57:28 +000022// predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner01d1ee32002-05-21 20:50:24 +000023//
24// Assumption: Succ is the single successor for BB.
25//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000026static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000027 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000028
29 if (!isa<PHINode>(Succ->front()))
30 return false; // We can make the transformation, no problem.
Chris Lattner01d1ee32002-05-21 20:50:24 +000031
32 // If there is more than one predecessor, and there are PHI nodes in
33 // the successor, then we need to add incoming edges for the PHI nodes
34 //
35 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
36
37 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000038 // Succ. If so, we cannot do the transformation if there are any PHI nodes
39 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000040 //
Chris Lattnere2ca5402003-03-05 21:01:52 +000041 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
42 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
43 // Loop over all of the PHI nodes checking to see if there are
44 // incompatible values coming in.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000045 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000046 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere2ca5402003-03-05 21:01:52 +000047 // Loop up the entries in the PHI node for BB and for *PI if the values
48 // coming in are non-equal, we cannot merge these two blocks (instead we
49 // should insert a conditional move or something, then merge the
50 // blocks).
51 int Idx1 = PN->getBasicBlockIndex(BB);
52 int Idx2 = PN->getBasicBlockIndex(*PI);
53 assert(Idx1 != -1 && Idx2 != -1 &&
54 "Didn't have entries for my predecessors??");
55 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
56 return true; // Values are not equal...
57 }
58 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000059
60 // Loop over all of the PHI nodes in the successor BB
61 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000062 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerbb190ac2002-10-08 21:36:33 +000063 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner01d1ee32002-05-21 20:50:24 +000064 assert(OldVal && "No entry in PHI for Pred BB!");
65
Chris Lattner46a5f1f2003-03-05 21:36:33 +000066 // If this incoming value is one of the PHI nodes in BB...
67 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
68 PHINode *OldValPN = cast<PHINode>(OldVal);
69 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
70 End = BBPreds.end(); PredI != End; ++PredI) {
71 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
72 }
73 } else {
74 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
75 End = BBPreds.end(); PredI != End; ++PredI) {
76 // Add an incoming value for each of the new incoming values...
77 PN->addIncoming(OldVal, *PredI);
78 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000079 }
80 }
81 return false;
82}
83
84
85// SimplifyCFG - This function is used to do simplification of a CFG. For
86// example, it adjusts branches to branches to eliminate the extra hop, it
87// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +000088// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +000089//
90// WARNING: The entry node of a function may not be simplified.
91//
Chris Lattner18961502002-06-25 16:12:52 +000092bool SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +000093 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +000094 Function *M = BB->getParent();
95
96 assert(BB && BB->getParent() && "Block not embedded in function!");
97 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +000098 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +000099
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000100 // Check to see if the first instruction in this block is just an
101 // 'llvm.unwind'. If so, replace any invoke instructions which use this as an
102 // exception destination with call instructions.
103 //
Chris Lattneree5457c2003-09-08 19:44:26 +0000104 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
105 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
106 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
107 while (!Preds.empty()) {
108 BasicBlock *Pred = Preds.back();
109 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
110 if (II->getExceptionalDest() == BB) {
111 // Insert a new branch instruction before the invoke, because this
112 // is now a fall through...
113 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
114 Pred->getInstList().remove(II); // Take out of symbol table
115
116 // Insert the call now...
117 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
118 CallInst *CI = new CallInst(II->getCalledValue(), Args,
119 II->getName(), BI);
120 // If the invoke produced a value, the Call now does instead
121 II->replaceAllUsesWith(CI);
122 delete II;
123 Changed = true;
124 }
125
126 Preds.pop_back();
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000127 }
Chris Lattneree5457c2003-09-08 19:44:26 +0000128 }
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000129
Chris Lattner01d1ee32002-05-21 20:50:24 +0000130 // Remove basic blocks that have no predecessors... which are unreachable.
131 if (pred_begin(BB) == pred_end(BB) &&
132 !BB->hasConstantReferences()) {
133 //cerr << "Removing BB: \n" << BB;
134
135 // Loop through all of our successors and make sure they know that one
136 // of their predecessors is going away.
137 for_each(succ_begin(BB), succ_end(BB),
138 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
139
140 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000141 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000142 // If this instruction is used, replace uses with an arbitrary
143 // constant value. Because control flow can't get here, we don't care
144 // what we replace the value with. Note that since this block is
145 // unreachable, and all values contained within it must dominate their
146 // uses, that all uses will eventually be removed.
Chris Lattner18961502002-06-25 16:12:52 +0000147 if (!I.use_empty())
Chris Lattner01d1ee32002-05-21 20:50:24 +0000148 // Make all users of this instruction reference the constant instead
Chris Lattner18961502002-06-25 16:12:52 +0000149 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner01d1ee32002-05-21 20:50:24 +0000150
151 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000152 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000153 }
Chris Lattner18961502002-06-25 16:12:52 +0000154 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000155 return true;
156 }
157
Chris Lattner694e37f2003-08-17 19:41:53 +0000158 // Check to see if we can constant propagate this terminator instruction
159 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000160 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000161
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000162 // Check to see if this block has no non-phi instructions and only a single
163 // successor. If so, replace references to this basic block with references
164 // to the successor.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000165 succ_iterator SI(succ_begin(BB));
166 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000167
168 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
169 while (isa<PHINode>(*BBI)) ++BBI;
170
171 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000172 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
173
174 if (Succ != BB) { // Arg, don't hurt infinite loops!
175 // If our successor has PHI nodes, then we need to update them to
176 // include entries for BB's predecessors, not for BB itself.
177 // Be careful though, if this transformation fails (returns true) then
178 // we cannot do this transformation!
179 //
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000180 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner01d1ee32002-05-21 20:50:24 +0000181 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattner18961502002-06-25 16:12:52 +0000182 std::string OldName = BB->getName();
183
Chris Lattner3a438372003-03-07 18:13:41 +0000184 std::vector<BasicBlock*>
185 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
186
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000187 // Move all PHI nodes in BB to Succ if they are alive, otherwise
188 // delete them.
189 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
190 if (PN->use_empty())
191 BB->getInstList().erase(BB->begin()); // Nuke instruction...
192 else {
193 // The instruction is alive, so this means that Succ must have
194 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner3a438372003-03-07 18:13:41 +0000195 // now. Simply move it into Succ, because we know that BB
196 // strictly dominated Succ.
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000197 BB->getInstList().remove(BB->begin());
198 Succ->getInstList().push_front(PN);
Chris Lattner3a438372003-03-07 18:13:41 +0000199
200 // We need to add new entries for the PHI node to account for
201 // predecessors of Succ that the PHI node does not take into
202 // account. At this point, since we know that BB dominated succ,
203 // this means that we should any newly added incoming edges should
204 // use the PHI node as the value for these edges, because they are
205 // loop back edges.
206
207 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
208 if (OldSuccPreds[i] != BB)
209 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000210 }
211
Chris Lattner3a438372003-03-07 18:13:41 +0000212 // Everything that jumped to BB now goes to Succ...
213 BB->replaceAllUsesWith(Succ);
214
Chris Lattner18961502002-06-25 16:12:52 +0000215 // Delete the old basic block...
216 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000217
Chris Lattner18961502002-06-25 16:12:52 +0000218 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
219 Succ->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000220
221 //cerr << "Function after removal: \n" << M;
222 return true;
223 }
224 }
225 }
226 }
227
228 // Merge basic blocks into their predecessor if there is only one distinct
229 // pred, and if there is only one distinct successor of the predecessor, and
230 // if there are no PHI nodes.
231 //
Chris Lattner91b65c02002-07-29 21:26:30 +0000232 if (!BB->hasConstantReferences()) {
Chris Lattner01d1ee32002-05-21 20:50:24 +0000233 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
234 BasicBlock *OnlyPred = *PI++;
235 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
236 if (*PI != OnlyPred) {
237 OnlyPred = 0; // There are multiple different predecessors...
238 break;
239 }
240
241 BasicBlock *OnlySucc = 0;
Chris Lattner122558b2003-08-05 16:27:44 +0000242 if (OnlyPred && OnlyPred != BB && // Don't break self loops
243 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
Chris Lattner01d1ee32002-05-21 20:50:24 +0000244 // Check to see if there is only one distinct successor...
245 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
246 OnlySucc = BB;
247 for (; SI != SE; ++SI)
248 if (*SI != OnlySucc) {
249 OnlySucc = 0; // There are multiple distinct successors!
250 break;
251 }
252 }
253
254 if (OnlySucc) {
255 //cerr << "Merging: " << BB << "into: " << OnlyPred;
256 TerminatorInst *Term = OnlyPred->getTerminator();
257
Chris Lattner91b65c02002-07-29 21:26:30 +0000258 // Resolve any PHI nodes at the start of the block. They are all
Chris Lattner929b2c62002-09-24 16:09:17 +0000259 // guaranteed to have exactly one entry if they exist, unless there are
260 // multiple duplicate (but guaranteed to be equal) entries for the
261 // incoming edges. This occurs when there are multiple edges from
262 // OnlyPred to OnlySucc.
Chris Lattner91b65c02002-07-29 21:26:30 +0000263 //
264 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattner91b65c02002-07-29 21:26:30 +0000265 PN->replaceAllUsesWith(PN->getIncomingValue(0));
266 BB->getInstList().pop_front(); // Delete the phi node...
267 }
268
Chris Lattner01d1ee32002-05-21 20:50:24 +0000269 // Delete the unconditional branch from the predecessor...
Chris Lattner18961502002-06-25 16:12:52 +0000270 OnlyPred->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000271
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000272 // Move all definitions in the successor to the predecessor...
Chris Lattner18961502002-06-25 16:12:52 +0000273 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
274
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000275 // Make all PHI nodes that referred to BB now refer to Pred as their
Chris Lattner01d1ee32002-05-21 20:50:24 +0000276 // source...
277 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +0000278
279 std::string OldName = BB->getName();
280
281 // Erase basic block from the function...
282 M->getBasicBlockList().erase(BB);
283
Chris Lattner01d1ee32002-05-21 20:50:24 +0000284 // Inherit predecessors name if it exists...
Chris Lattner18961502002-06-25 16:12:52 +0000285 if (!OldName.empty() && !OnlyPred->hasName())
286 OnlyPred->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000287
Chris Lattner01d1ee32002-05-21 20:50:24 +0000288 return true;
289 }
290 }
291
Chris Lattner694e37f2003-08-17 19:41:53 +0000292 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000293}