blob: 8aec92a9f4d71928f416dc35447992eba4dfba8e [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
15#include "llvm/Constant.h"
Chris Lattner3f5823f2003-08-24 18:36:16 +000016#include "llvm/Intrinsics.h"
Chris Lattner466a0492002-05-21 20:50:24 +000017#include "llvm/iPHINode.h"
Chris Lattner3f5823f2003-08-24 18:36:16 +000018#include "llvm/iTerminators.h"
19#include "llvm/iOther.h"
Chris Lattner466a0492002-05-21 20:50:24 +000020#include "llvm/Support/CFG.h"
21#include <algorithm>
22#include <functional>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000023using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000024
Misha Brukman632df282002-10-29 23:06:16 +000025// PropagatePredecessors - This gets "Succ" ready to have the predecessors from
Chris Lattner466a0492002-05-21 20:50:24 +000026// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
27// have extra slots added to them to hold the merge edges from BB's
Chris Lattner31116ba2003-03-05 21:01:52 +000028// predecessors, and BB itself might have had PHI nodes in it. This function
29// returns true (failure) if the Succ BB already has a predecessor that is a
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000030// predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner466a0492002-05-21 20:50:24 +000031//
32// Assumption: Succ is the single successor for BB.
33//
Misha Brukman632df282002-10-29 23:06:16 +000034static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000035 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000036
37 if (!isa<PHINode>(Succ->front()))
38 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000039
40 // If there is more than one predecessor, and there are PHI nodes in
41 // the successor, then we need to add incoming edges for the PHI nodes
42 //
43 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
44
45 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000046 // Succ. If so, we cannot do the transformation if there are any PHI nodes
47 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000048 //
Chris Lattner31116ba2003-03-05 21:01:52 +000049 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
50 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
51 // Loop over all of the PHI nodes checking to see if there are
52 // incompatible values coming in.
Chris Lattnere54d2142003-03-05 21:36:33 +000053 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000054 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner31116ba2003-03-05 21:01:52 +000055 // Loop up the entries in the PHI node for BB and for *PI if the values
56 // coming in are non-equal, we cannot merge these two blocks (instead we
57 // should insert a conditional move or something, then merge the
58 // blocks).
59 int Idx1 = PN->getBasicBlockIndex(BB);
60 int Idx2 = PN->getBasicBlockIndex(*PI);
61 assert(Idx1 != -1 && Idx2 != -1 &&
62 "Didn't have entries for my predecessors??");
63 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
64 return true; // Values are not equal...
65 }
66 }
Chris Lattner466a0492002-05-21 20:50:24 +000067
68 // Loop over all of the PHI nodes in the successor BB
69 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000070 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnera704ac82002-10-08 21:36:33 +000071 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000072 assert(OldVal && "No entry in PHI for Pred BB!");
73
Chris Lattnere54d2142003-03-05 21:36:33 +000074 // If this incoming value is one of the PHI nodes in BB...
75 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
76 PHINode *OldValPN = cast<PHINode>(OldVal);
77 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
78 End = BBPreds.end(); PredI != End; ++PredI) {
79 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
80 }
81 } else {
82 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
83 End = BBPreds.end(); PredI != End; ++PredI) {
84 // Add an incoming value for each of the new incoming values...
85 PN->addIncoming(OldVal, *PredI);
86 }
Chris Lattner466a0492002-05-21 20:50:24 +000087 }
88 }
89 return false;
90}
91
92
93// SimplifyCFG - This function is used to do simplification of a CFG. For
94// example, it adjusts branches to branches to eliminate the extra hop, it
95// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +000096// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +000097//
98// WARNING: The entry node of a function may not be simplified.
99//
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000100bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000101 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000102 Function *M = BB->getParent();
103
104 assert(BB && BB->getParent() && "Block not embedded in function!");
105 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000106 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000107
Chris Lattner3f5823f2003-08-24 18:36:16 +0000108 // Check to see if the first instruction in this block is just an
109 // 'llvm.unwind'. If so, replace any invoke instructions which use this as an
110 // exception destination with call instructions.
111 //
Chris Lattner04ecefe2003-09-08 19:44:26 +0000112 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator()))
113 if (BB->begin() == BasicBlock::iterator(UI)) { // Empty block?
114 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
115 while (!Preds.empty()) {
116 BasicBlock *Pred = Preds.back();
117 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000118 if (II->getUnwindDest() == BB) {
Chris Lattner04ecefe2003-09-08 19:44:26 +0000119 // Insert a new branch instruction before the invoke, because this
120 // is now a fall through...
121 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
122 Pred->getInstList().remove(II); // Take out of symbol table
123
124 // Insert the call now...
125 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
126 CallInst *CI = new CallInst(II->getCalledValue(), Args,
127 II->getName(), BI);
128 // If the invoke produced a value, the Call now does instead
129 II->replaceAllUsesWith(CI);
130 delete II;
131 Changed = true;
132 }
133
134 Preds.pop_back();
Chris Lattner3f5823f2003-08-24 18:36:16 +0000135 }
Chris Lattner04ecefe2003-09-08 19:44:26 +0000136 }
Chris Lattner3f5823f2003-08-24 18:36:16 +0000137
Chris Lattner466a0492002-05-21 20:50:24 +0000138 // Remove basic blocks that have no predecessors... which are unreachable.
139 if (pred_begin(BB) == pred_end(BB) &&
140 !BB->hasConstantReferences()) {
141 //cerr << "Removing BB: \n" << BB;
142
143 // Loop through all of our successors and make sure they know that one
144 // of their predecessors is going away.
145 for_each(succ_begin(BB), succ_end(BB),
146 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
147
148 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000149 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000150 // If this instruction is used, replace uses with an arbitrary
151 // constant value. Because control flow can't get here, we don't care
152 // what we replace the value with. Note that since this block is
153 // unreachable, and all values contained within it must dominate their
154 // uses, that all uses will eventually be removed.
Chris Lattnerfda72b12002-06-25 16:12:52 +0000155 if (!I.use_empty())
Chris Lattner466a0492002-05-21 20:50:24 +0000156 // Make all users of this instruction reference the constant instead
Chris Lattnerfda72b12002-06-25 16:12:52 +0000157 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner466a0492002-05-21 20:50:24 +0000158
159 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000160 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000161 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000162 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000163 return true;
164 }
165
Chris Lattner031340a2003-08-17 19:41:53 +0000166 // Check to see if we can constant propagate this terminator instruction
167 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +0000168 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +0000169
Chris Lattnere54d2142003-03-05 21:36:33 +0000170 // Check to see if this block has no non-phi instructions and only a single
171 // successor. If so, replace references to this basic block with references
172 // to the successor.
Chris Lattner466a0492002-05-21 20:50:24 +0000173 succ_iterator SI(succ_begin(BB));
174 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnere54d2142003-03-05 21:36:33 +0000175
176 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
177 while (isa<PHINode>(*BBI)) ++BBI;
178
179 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner466a0492002-05-21 20:50:24 +0000180 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
181
182 if (Succ != BB) { // Arg, don't hurt infinite loops!
183 // If our successor has PHI nodes, then we need to update them to
184 // include entries for BB's predecessors, not for BB itself.
185 // Be careful though, if this transformation fails (returns true) then
186 // we cannot do this transformation!
187 //
Misha Brukman632df282002-10-29 23:06:16 +0000188 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner466a0492002-05-21 20:50:24 +0000189 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattnerfda72b12002-06-25 16:12:52 +0000190 std::string OldName = BB->getName();
191
Chris Lattner569a57f2003-03-07 18:13:41 +0000192 std::vector<BasicBlock*>
193 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
194
Chris Lattnere54d2142003-03-05 21:36:33 +0000195 // Move all PHI nodes in BB to Succ if they are alive, otherwise
196 // delete them.
197 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
198 if (PN->use_empty())
199 BB->getInstList().erase(BB->begin()); // Nuke instruction...
200 else {
201 // The instruction is alive, so this means that Succ must have
202 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner569a57f2003-03-07 18:13:41 +0000203 // now. Simply move it into Succ, because we know that BB
204 // strictly dominated Succ.
Chris Lattnere54d2142003-03-05 21:36:33 +0000205 BB->getInstList().remove(BB->begin());
206 Succ->getInstList().push_front(PN);
Chris Lattner569a57f2003-03-07 18:13:41 +0000207
208 // We need to add new entries for the PHI node to account for
209 // predecessors of Succ that the PHI node does not take into
210 // account. At this point, since we know that BB dominated succ,
211 // this means that we should any newly added incoming edges should
212 // use the PHI node as the value for these edges, because they are
213 // loop back edges.
214
215 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
216 if (OldSuccPreds[i] != BB)
217 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattnere54d2142003-03-05 21:36:33 +0000218 }
219
Chris Lattner569a57f2003-03-07 18:13:41 +0000220 // Everything that jumped to BB now goes to Succ...
221 BB->replaceAllUsesWith(Succ);
222
Chris Lattnerfda72b12002-06-25 16:12:52 +0000223 // Delete the old basic block...
224 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000225
Chris Lattnerfda72b12002-06-25 16:12:52 +0000226 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
227 Succ->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000228
229 //cerr << "Function after removal: \n" << M;
230 return true;
231 }
232 }
233 }
234 }
235
236 // Merge basic blocks into their predecessor if there is only one distinct
237 // pred, and if there is only one distinct successor of the predecessor, and
238 // if there are no PHI nodes.
239 //
Chris Lattner1cec4d92002-07-29 21:26:30 +0000240 if (!BB->hasConstantReferences()) {
Chris Lattner466a0492002-05-21 20:50:24 +0000241 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
242 BasicBlock *OnlyPred = *PI++;
243 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
244 if (*PI != OnlyPred) {
245 OnlyPred = 0; // There are multiple different predecessors...
246 break;
247 }
248
249 BasicBlock *OnlySucc = 0;
Chris Lattneredc8c542003-08-05 16:27:44 +0000250 if (OnlyPred && OnlyPred != BB && // Don't break self loops
251 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
Chris Lattner466a0492002-05-21 20:50:24 +0000252 // Check to see if there is only one distinct successor...
253 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
254 OnlySucc = BB;
255 for (; SI != SE; ++SI)
256 if (*SI != OnlySucc) {
257 OnlySucc = 0; // There are multiple distinct successors!
258 break;
259 }
260 }
261
262 if (OnlySucc) {
263 //cerr << "Merging: " << BB << "into: " << OnlyPred;
264 TerminatorInst *Term = OnlyPred->getTerminator();
265
Chris Lattner1cec4d92002-07-29 21:26:30 +0000266 // Resolve any PHI nodes at the start of the block. They are all
Chris Lattnerd6dcd8e2002-09-24 16:09:17 +0000267 // guaranteed to have exactly one entry if they exist, unless there are
268 // multiple duplicate (but guaranteed to be equal) entries for the
269 // incoming edges. This occurs when there are multiple edges from
270 // OnlyPred to OnlySucc.
Chris Lattner1cec4d92002-07-29 21:26:30 +0000271 //
272 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattner1cec4d92002-07-29 21:26:30 +0000273 PN->replaceAllUsesWith(PN->getIncomingValue(0));
274 BB->getInstList().pop_front(); // Delete the phi node...
275 }
276
Chris Lattner466a0492002-05-21 20:50:24 +0000277 // Delete the unconditional branch from the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000278 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000279
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000280 // Move all definitions in the successor to the predecessor...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000281 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
282
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000283 // Make all PHI nodes that referred to BB now refer to Pred as their
Chris Lattner466a0492002-05-21 20:50:24 +0000284 // source...
285 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +0000286
287 std::string OldName = BB->getName();
288
289 // Erase basic block from the function...
290 M->getBasicBlockList().erase(BB);
291
Chris Lattner466a0492002-05-21 20:50:24 +0000292 // Inherit predecessors name if it exists...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000293 if (!OldName.empty() && !OnlyPred->hasName())
294 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +0000295
Chris Lattner466a0492002-05-21 20:50:24 +0000296 return true;
297 }
298 }
299
Chris Lattner031340a2003-08-17 19:41:53 +0000300 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +0000301}