blob: ca59276f2b7d88c3f90a27302a3dec9d9d70fbce [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
John Criswellb576c942003-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 Lattner01d1ee32002-05-21 20:50:24 +00009//
Chris Lattnerbb190ac2002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000015#include "llvm/Constants.h"
16#include "llvm/Instructions.h"
Chris Lattner0d560082004-02-24 05:38:11 +000017#include "llvm/Type.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000018#include "llvm/Support/CFG.h"
19#include <algorithm>
20#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000021#include <set>
Chris Lattnerf7703df2004-01-09 06:12:26 +000022using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000023
Chris Lattner0d560082004-02-24 05:38:11 +000024// PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
25// predecessors from "BB". This is a little tricky because "Succ" has PHI
26// nodes, which need to have extra slots added to them to hold the merge edges
27// from BB's predecessors, and BB itself might have had PHI nodes in it. This
28// function returns true (failure) if the Succ BB already has a predecessor that
29// is a predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner01d1ee32002-05-21 20:50:24 +000030//
31// Assumption: Succ is the single successor for BB.
32//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000033static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000034 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000035
36 if (!isa<PHINode>(Succ->front()))
37 return false; // We can make the transformation, no problem.
Chris Lattner01d1ee32002-05-21 20:50:24 +000038
39 // If there is more than one predecessor, and there are PHI nodes in
40 // the successor, then we need to add incoming edges for the PHI nodes
41 //
42 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
43
44 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000045 // Succ. If so, we cannot do the transformation if there are any PHI nodes
46 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000047 //
Chris Lattnere2ca5402003-03-05 21:01:52 +000048 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
49 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
50 // Loop over all of the PHI nodes checking to see if there are
51 // incompatible values coming in.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000052 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000053 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere2ca5402003-03-05 21:01:52 +000054 // Loop up the entries in the PHI node for BB and for *PI if the values
55 // coming in are non-equal, we cannot merge these two blocks (instead we
56 // should insert a conditional move or something, then merge the
57 // blocks).
58 int Idx1 = PN->getBasicBlockIndex(BB);
59 int Idx2 = PN->getBasicBlockIndex(*PI);
60 assert(Idx1 != -1 && Idx2 != -1 &&
61 "Didn't have entries for my predecessors??");
62 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
63 return true; // Values are not equal...
64 }
65 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000066
67 // Loop over all of the PHI nodes in the successor BB
68 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000069 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerbb190ac2002-10-08 21:36:33 +000070 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner01d1ee32002-05-21 20:50:24 +000071 assert(OldVal && "No entry in PHI for Pred BB!");
72
Chris Lattner46a5f1f2003-03-05 21:36:33 +000073 // If this incoming value is one of the PHI nodes in BB...
74 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
75 PHINode *OldValPN = cast<PHINode>(OldVal);
76 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
77 End = BBPreds.end(); PredI != End; ++PredI) {
78 PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
79 }
80 } else {
81 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
82 End = BBPreds.end(); PredI != End; ++PredI) {
83 // Add an incoming value for each of the new incoming values...
84 PN->addIncoming(OldVal, *PredI);
85 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000086 }
87 }
88 return false;
89}
90
Chris Lattner723c66d2004-02-11 03:36:04 +000091/// GetIfCondition - Given a basic block (BB) with two predecessors (and
92/// presumably PHI nodes in it), check to see if the merge at this block is due
93/// to an "if condition". If so, return the boolean condition that determines
94/// which entry into BB will be taken. Also, return by references the block
95/// that will be entered from if the condition is true, and the block that will
96/// be entered if the condition is false.
97///
98///
99static Value *GetIfCondition(BasicBlock *BB,
100 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
101 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
102 "Function can only handle blocks with 2 predecessors!");
103 BasicBlock *Pred1 = *pred_begin(BB);
104 BasicBlock *Pred2 = *++pred_begin(BB);
105
106 // We can only handle branches. Other control flow will be lowered to
107 // branches if possible anyway.
108 if (!isa<BranchInst>(Pred1->getTerminator()) ||
109 !isa<BranchInst>(Pred2->getTerminator()))
110 return 0;
111 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
112 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
113
114 // Eliminate code duplication by ensuring that Pred1Br is conditional if
115 // either are.
116 if (Pred2Br->isConditional()) {
117 // If both branches are conditional, we don't have an "if statement". In
118 // reality, we could transform this case, but since the condition will be
119 // required anyway, we stand no chance of eliminating it, so the xform is
120 // probably not profitable.
121 if (Pred1Br->isConditional())
122 return 0;
123
124 std::swap(Pred1, Pred2);
125 std::swap(Pred1Br, Pred2Br);
126 }
127
128 if (Pred1Br->isConditional()) {
129 // If we found a conditional branch predecessor, make sure that it branches
130 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
131 if (Pred1Br->getSuccessor(0) == BB &&
132 Pred1Br->getSuccessor(1) == Pred2) {
133 IfTrue = Pred1;
134 IfFalse = Pred2;
135 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
136 Pred1Br->getSuccessor(1) == BB) {
137 IfTrue = Pred2;
138 IfFalse = Pred1;
139 } else {
140 // We know that one arm of the conditional goes to BB, so the other must
141 // go somewhere unrelated, and this must not be an "if statement".
142 return 0;
143 }
144
145 // The only thing we have to watch out for here is to make sure that Pred2
146 // doesn't have incoming edges from other blocks. If it does, the condition
147 // doesn't dominate BB.
148 if (++pred_begin(Pred2) != pred_end(Pred2))
149 return 0;
150
151 return Pred1Br->getCondition();
152 }
153
154 // Ok, if we got here, both predecessors end with an unconditional branch to
155 // BB. Don't panic! If both blocks only have a single (identical)
156 // predecessor, and THAT is a conditional branch, then we're all ok!
157 if (pred_begin(Pred1) == pred_end(Pred1) ||
158 ++pred_begin(Pred1) != pred_end(Pred1) ||
159 pred_begin(Pred2) == pred_end(Pred2) ||
160 ++pred_begin(Pred2) != pred_end(Pred2) ||
161 *pred_begin(Pred1) != *pred_begin(Pred2))
162 return 0;
163
164 // Otherwise, if this is a conditional branch, then we can use it!
165 BasicBlock *CommonPred = *pred_begin(Pred1);
166 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
167 assert(BI->isConditional() && "Two successors but not conditional?");
168 if (BI->getSuccessor(0) == Pred1) {
169 IfTrue = Pred1;
170 IfFalse = Pred2;
171 } else {
172 IfTrue = Pred2;
173 IfFalse = Pred1;
174 }
175 return BI->getCondition();
176 }
177 return 0;
178}
179
180
181// If we have a merge point of an "if condition" as accepted above, return true
182// if the specified value dominates the block. We don't handle the true
183// generality of domination here, just a special case which works well enough
184// for us.
185static bool DominatesMergePoint(Value *V, BasicBlock *BB) {
186 if (Instruction *I = dyn_cast<Instruction>(V)) {
187 BasicBlock *PBB = I->getParent();
188 // If this instruction is defined in a block that contains an unconditional
189 // branch to BB, then it must be in the 'conditional' part of the "if
190 // statement".
191 if (isa<BranchInst>(PBB->getTerminator()) &&
192 cast<BranchInst>(PBB->getTerminator())->isUnconditional() &&
193 cast<BranchInst>(PBB->getTerminator())->getSuccessor(0) == BB)
194 return false;
195
196 // We also don't want to allow wierd loops that might have the "if
197 // condition" in the bottom of this block.
198 if (PBB == BB) return false;
199 }
200
201 // Non-instructions all dominate instructions.
202 return true;
203}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000204
Chris Lattner0d560082004-02-24 05:38:11 +0000205// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
206// instructions that compare a value against a constant, return the value being
207// compared, and stick the constant into the Values vector.
208static Value *GatherConstantSetEQs(Value *V, std::vector<Constant*> &Values) {
209 if (Instruction *Inst = dyn_cast<Instruction>(V))
210 if (Inst->getOpcode() == Instruction::SetEQ) {
211 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(1))) {
212 Values.push_back(C);
213 return Inst->getOperand(0);
214 } else if (Constant *C = dyn_cast<Constant>(Inst->getOperand(0))) {
215 Values.push_back(C);
216 return Inst->getOperand(1);
217 }
218 } else if (Inst->getOpcode() == Instruction::Or) {
219 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
220 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
221 if (LHS == RHS)
222 return LHS;
223 }
224 return 0;
225}
226
227// GatherConstantSetNEs - Given a potentially 'and'd together collection of
228// setne instructions that compare a value against a constant, return the value
229// being compared, and stick the constant into the Values vector.
230static Value *GatherConstantSetNEs(Value *V, std::vector<Constant*> &Values) {
231 if (Instruction *Inst = dyn_cast<Instruction>(V))
232 if (Inst->getOpcode() == Instruction::SetNE) {
233 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(1))) {
234 Values.push_back(C);
235 return Inst->getOperand(0);
236 } else if (Constant *C = dyn_cast<Constant>(Inst->getOperand(0))) {
237 Values.push_back(C);
238 return Inst->getOperand(1);
239 }
240 } else if (Inst->getOpcode() == Instruction::Cast) {
241 // Cast of X to bool is really a comparison against zero.
242 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
243 Values.push_back(Constant::getNullValue(Inst->getOperand(0)->getType()));
244 return Inst->getOperand(0);
245 } else if (Inst->getOpcode() == Instruction::And) {
246 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
247 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
248 if (LHS == RHS)
249 return LHS;
250 }
251 return 0;
252}
253
254
255
256/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
257/// bunch of comparisons of one value against constants, return the value and
258/// the constants being compared.
259static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
260 std::vector<Constant*> &Values) {
261 if (Cond->getOpcode() == Instruction::Or) {
262 CompVal = GatherConstantSetEQs(Cond, Values);
263
264 // Return true to indicate that the condition is true if the CompVal is
265 // equal to one of the constants.
266 return true;
267 } else if (Cond->getOpcode() == Instruction::And) {
268 CompVal = GatherConstantSetNEs(Cond, Values);
269
270 // Return false to indicate that the condition is false if the CompVal is
271 // equal to one of the constants.
272 return false;
273 }
274 return false;
275}
276
277/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
278/// has no side effects, nuke it. If it uses any instructions that become dead
279/// because the instruction is now gone, nuke them too.
280static void ErasePossiblyDeadInstructionTree(Instruction *I) {
281 if (isInstructionTriviallyDead(I)) {
282 std::vector<Value*> Operands(I->op_begin(), I->op_end());
283 I->getParent()->getInstList().erase(I);
284 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
285 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
286 ErasePossiblyDeadInstructionTree(OpI);
287 }
288}
289
Chris Lattnerd52c2612004-02-24 07:23:58 +0000290/// SafeToMergeTerminators - Return true if it is safe to merge these two
291/// terminator instructions together.
292///
293static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
294 if (SI1 == SI2) return false; // Can't merge with self!
295
296 // It is not safe to merge these two switch instructions if they have a common
297 // successor, and if that successor has a PHI node, and if that PHI node has
298 // conflicting incoming values from the two switch blocks.
299 BasicBlock *SI1BB = SI1->getParent();
300 BasicBlock *SI2BB = SI2->getParent();
301 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
302
303 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
304 if (SI1Succs.count(*I))
305 for (BasicBlock::iterator BBI = (*I)->begin();
306 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI)
307 if (PN->getIncomingValueForBlock(SI1BB) !=
308 PN->getIncomingValueForBlock(SI2BB))
309 return false;
310
311 return true;
312}
313
314/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
315/// now be entries in it from the 'NewPred' block. The values that will be
316/// flowing into the PHI nodes will be the same as those coming in from
317/// ExistPred, and existing predecessor of Succ.
318static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
319 BasicBlock *ExistPred) {
320 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
321 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
322 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
323
324 for (BasicBlock::iterator I = Succ->begin();
325 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
326 Value *V = PN->getIncomingValueForBlock(ExistPred);
327 PN->addIncoming(V, NewPred);
328 }
329}
330
Chris Lattner01d1ee32002-05-21 20:50:24 +0000331// SimplifyCFG - This function is used to do simplification of a CFG. For
332// example, it adjusts branches to branches to eliminate the extra hop, it
333// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +0000334// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000335//
336// WARNING: The entry node of a function may not be simplified.
337//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000338bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000339 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000340 Function *M = BB->getParent();
341
342 assert(BB && BB->getParent() && "Block not embedded in function!");
343 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +0000344 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +0000345
Chris Lattner01d1ee32002-05-21 20:50:24 +0000346 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000347 if (pred_begin(BB) == pred_end(BB) ||
348 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner01d1ee32002-05-21 20:50:24 +0000349 //cerr << "Removing BB: \n" << BB;
350
351 // Loop through all of our successors and make sure they know that one
352 // of their predecessors is going away.
353 for_each(succ_begin(BB), succ_end(BB),
354 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
355
356 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000357 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000358 // If this instruction is used, replace uses with an arbitrary
359 // constant value. Because control flow can't get here, we don't care
360 // what we replace the value with. Note that since this block is
361 // unreachable, and all values contained within it must dominate their
362 // uses, that all uses will eventually be removed.
Chris Lattner18961502002-06-25 16:12:52 +0000363 if (!I.use_empty())
Chris Lattner01d1ee32002-05-21 20:50:24 +0000364 // Make all users of this instruction reference the constant instead
Chris Lattner18961502002-06-25 16:12:52 +0000365 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner01d1ee32002-05-21 20:50:24 +0000366
367 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000368 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000369 }
Chris Lattner18961502002-06-25 16:12:52 +0000370 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000371 return true;
372 }
373
Chris Lattner694e37f2003-08-17 19:41:53 +0000374 // Check to see if we can constant propagate this terminator instruction
375 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000376 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000377
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000378 // Check to see if this block has no non-phi instructions and only a single
379 // successor. If so, replace references to this basic block with references
380 // to the successor.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000381 succ_iterator SI(succ_begin(BB));
382 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000383
384 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
385 while (isa<PHINode>(*BBI)) ++BBI;
386
387 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000388 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
389
390 if (Succ != BB) { // Arg, don't hurt infinite loops!
391 // If our successor has PHI nodes, then we need to update them to
392 // include entries for BB's predecessors, not for BB itself.
393 // Be careful though, if this transformation fails (returns true) then
394 // we cannot do this transformation!
395 //
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000396 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner01d1ee32002-05-21 20:50:24 +0000397 //cerr << "Killing Trivial BB: \n" << BB;
Chris Lattner18961502002-06-25 16:12:52 +0000398 std::string OldName = BB->getName();
399
Chris Lattner3a438372003-03-07 18:13:41 +0000400 std::vector<BasicBlock*>
401 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
402
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000403 // Move all PHI nodes in BB to Succ if they are alive, otherwise
404 // delete them.
405 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
406 if (PN->use_empty())
407 BB->getInstList().erase(BB->begin()); // Nuke instruction...
408 else {
409 // The instruction is alive, so this means that Succ must have
410 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner3a438372003-03-07 18:13:41 +0000411 // now. Simply move it into Succ, because we know that BB
412 // strictly dominated Succ.
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000413 BB->getInstList().remove(BB->begin());
414 Succ->getInstList().push_front(PN);
Chris Lattner3a438372003-03-07 18:13:41 +0000415
416 // We need to add new entries for the PHI node to account for
417 // predecessors of Succ that the PHI node does not take into
418 // account. At this point, since we know that BB dominated succ,
419 // this means that we should any newly added incoming edges should
420 // use the PHI node as the value for these edges, because they are
421 // loop back edges.
422
423 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
424 if (OldSuccPreds[i] != BB)
425 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000426 }
427
Chris Lattner3a438372003-03-07 18:13:41 +0000428 // Everything that jumped to BB now goes to Succ...
429 BB->replaceAllUsesWith(Succ);
430
Chris Lattner18961502002-06-25 16:12:52 +0000431 // Delete the old basic block...
432 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000433
Chris Lattner18961502002-06-25 16:12:52 +0000434 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
435 Succ->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000436
437 //cerr << "Function after removal: \n" << M;
438 return true;
439 }
440 }
441 }
442 }
443
Chris Lattner19831ec2004-02-16 06:35:48 +0000444 // If this is a returning block with only PHI nodes in it, fold the return
445 // instruction into any unconditional branch predecessors.
446 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
447 BasicBlock::iterator BBI = BB->getTerminator();
448 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
449 // Find predecessors that end with unconditional branches.
450 std::vector<BasicBlock*> UncondBranchPreds;
451 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
452 TerminatorInst *PTI = (*PI)->getTerminator();
453 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
454 if (BI->isUnconditional())
455 UncondBranchPreds.push_back(*PI);
456 }
457
458 // If we found some, do the transformation!
459 if (!UncondBranchPreds.empty()) {
460 while (!UncondBranchPreds.empty()) {
461 BasicBlock *Pred = UncondBranchPreds.back();
462 UncondBranchPreds.pop_back();
463 Instruction *UncondBranch = Pred->getTerminator();
464 // Clone the return and add it to the end of the predecessor.
465 Instruction *NewRet = RI->clone();
466 Pred->getInstList().push_back(NewRet);
467
468 // If the return instruction returns a value, and if the value was a
469 // PHI node in "BB", propagate the right value into the return.
470 if (NewRet->getNumOperands() == 1)
471 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
472 if (PN->getParent() == BB)
473 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
474 // Update any PHI nodes in the returning block to realize that we no
475 // longer branch to them.
476 BB->removePredecessor(Pred);
477 Pred->getInstList().erase(UncondBranch);
478 }
479
480 // If we eliminated all predecessors of the block, delete the block now.
481 if (pred_begin(BB) == pred_end(BB))
482 // We know there are no successors, so just nuke the block.
483 M->getBasicBlockList().erase(BB);
484
Chris Lattner19831ec2004-02-16 06:35:48 +0000485 return true;
486 }
487 }
Chris Lattnere14ea082004-02-24 05:54:22 +0000488 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
489 // Check to see if the first instruction in this block is just an unwind.
490 // If so, replace any invoke instructions which use this as an exception
491 // destination with call instructions.
492 //
493 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
494 while (!Preds.empty()) {
495 BasicBlock *Pred = Preds.back();
496 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
497 if (II->getUnwindDest() == BB) {
498 // Insert a new branch instruction before the invoke, because this
499 // is now a fall through...
500 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
501 Pred->getInstList().remove(II); // Take out of symbol table
502
503 // Insert the call now...
504 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
505 CallInst *CI = new CallInst(II->getCalledValue(), Args,
506 II->getName(), BI);
507 // If the invoke produced a value, the Call now does instead
508 II->replaceAllUsesWith(CI);
509 delete II;
510 Changed = true;
511 }
512
513 Preds.pop_back();
514 }
Chris Lattner8e509dd2004-02-24 16:09:21 +0000515
516 // If this block is now dead, remove it.
517 if (pred_begin(BB) == pred_end(BB)) {
518 // We know there are no successors, so just nuke the block.
519 M->getBasicBlockList().erase(BB);
520 return true;
521 }
522
Chris Lattnerd52c2612004-02-24 07:23:58 +0000523 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
524 // If the only instruction in this block is a switch instruction, see if we
525 // can fold the switch instruction into a switch in a predecessor block.
526 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
527 while (!Preds.empty()) {
528 BasicBlock *Pred = Preds.back();
529 Preds.pop_back();
530
531 // If the two blocks are switching on the same value, we can merge this
532 // switch into the predecessor's switch.
533 if (SwitchInst *PSI = dyn_cast<SwitchInst>(Pred->getTerminator()))
534 if (PSI->getCondition() == SI->getCondition() &&
535 SafeToMergeTerminators(SI, PSI)) {
536 // Figure out which 'cases' to copy from SI to PSI.
537 std::vector<std::pair<Constant*, BasicBlock*> > Cases;
538 BasicBlock *NewDefault = 0;
539 if (PSI->getDefaultDest() == BB) {
540 // If this is the default destination from PSI, only the edges in SI
541 // that don't occur in PSI, or that branch to BB will be activated.
542 std::set<Constant*> PSIHandled;
543 for (unsigned i = 1, e = PSI->getNumSuccessors(); i != e; ++i)
544 if (PSI->getSuccessor(i) != BB)
545 PSIHandled.insert(PSI->getCaseValue(i));
546 else {
547 // This entry will be replaced.
548 PSI->removeCase(i);
549 --i; --e;
550 }
551
552 NewDefault = SI->getDefaultDest();
553 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
554 Constant *C = SI->getCaseValue(i);
555 if (!PSIHandled.count(C))
556 Cases.push_back(std::make_pair(C, SI->getSuccessor(i)));
557 }
558
559 } else {
560 // If this is not the default destination from PSI, only the edges
561 // in SI that occur in PSI with a destination of BB will be
562 // activated.
563 std::set<Constant*> PSIHandled;
564 for (unsigned i = 1, e = PSI->getNumSuccessors(); i != e; ++i)
565 if (PSI->getSuccessor(i) == BB) {
566 // We know that BB doesn't have any PHI nodes in it, so just
567 // drop the edges.
568 PSIHandled.insert(PSI->getCaseValue(i));
569 PSI->removeCase(i);
570 --i; --e;
571 }
572
573 // Okay, now we know which constants were sent to BB from the
574 // predecessor. Figure out where they will all go now.
575 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
576 Constant *C = SI->getCaseValue(i);
577 if (PSIHandled.count(C)) {
578 // If this is one we are capable of getting...
579 Cases.push_back(std::make_pair(C, SI->getSuccessor(i)));
580 PSIHandled.erase(C); // This constant is taken care of
581 }
582 }
583
584 // If there are any constants vectored to BB that SI doesn't handle,
585 // they must go to the default destination of SI.
586 for (std::set<Constant*>::iterator I = PSIHandled.begin(),
587 E = PSIHandled.end(); I != E; ++I)
588 Cases.push_back(std::make_pair(*I, SI->getDefaultDest()));
589 }
590
591 // Okay, at this point, we know which cases need to be added to the
592 // PSI switch and which destinations they go to. If PSI needs its
593 // default destination changed, NewDefault is set. Start changing
594 // stuff now.
595 if (NewDefault) {
596 AddPredecessorToBlock(NewDefault, Pred, BB);
597 PSI->setSuccessor(0, NewDefault);
598 }
599
600 // Okay, add all of the cases now.
601 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
602 AddPredecessorToBlock(Cases[i].second, Pred, BB);
603 PSI->addCase(Cases[i].first, Cases[i].second);
604 }
605
606 // Okay, last check. If BB is still a successor of PSI, then we must
607 // have an infinite loop case. If so, add an infinitely looping block
608 // to handle the case to preserve the behavior of the code.
609 BasicBlock *InfLoopBlock = 0;
610 for (unsigned i = 0, e = PSI->getNumSuccessors(); i != e; ++i)
611 if (PSI->getSuccessor(i) == BB) {
612 if (InfLoopBlock == 0) {
613 // Insert it at the end of the loop, because it's either code,
614 // or it won't matter if it's hot. :)
615 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
616 new BranchInst(InfLoopBlock, InfLoopBlock);
617 }
618 PSI->setSuccessor(i, InfLoopBlock);
619 }
620
621 Changed = true;
622 }
623 }
624
625 // If we removed all predecessors of this block, recursively call
626 // SimplifyCFG to remove it.
627 if (pred_begin(BB) == pred_end(BB))
628 return SimplifyCFG(BB);
Chris Lattner19831ec2004-02-16 06:35:48 +0000629 }
630
Chris Lattner01d1ee32002-05-21 20:50:24 +0000631 // Merge basic blocks into their predecessor if there is only one distinct
632 // pred, and if there is only one distinct successor of the predecessor, and
633 // if there are no PHI nodes.
634 //
Chris Lattner2355f942004-02-11 01:17:07 +0000635 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
636 BasicBlock *OnlyPred = *PI++;
637 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
638 if (*PI != OnlyPred) {
639 OnlyPred = 0; // There are multiple different predecessors...
640 break;
641 }
642
643 BasicBlock *OnlySucc = 0;
644 if (OnlyPred && OnlyPred != BB && // Don't break self loops
645 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
646 // Check to see if there is only one distinct successor...
647 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
648 OnlySucc = BB;
649 for (; SI != SE; ++SI)
650 if (*SI != OnlySucc) {
651 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000652 break;
653 }
Chris Lattner2355f942004-02-11 01:17:07 +0000654 }
655
656 if (OnlySucc) {
657 //cerr << "Merging: " << BB << "into: " << OnlyPred;
658 TerminatorInst *Term = OnlyPred->getTerminator();
659
660 // Resolve any PHI nodes at the start of the block. They are all
661 // guaranteed to have exactly one entry if they exist, unless there are
662 // multiple duplicate (but guaranteed to be equal) entries for the
663 // incoming edges. This occurs when there are multiple edges from
664 // OnlyPred to OnlySucc.
665 //
666 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
667 PN->replaceAllUsesWith(PN->getIncomingValue(0));
668 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner01d1ee32002-05-21 20:50:24 +0000669 }
670
Chris Lattner2355f942004-02-11 01:17:07 +0000671 // Delete the unconditional branch from the predecessor...
672 OnlyPred->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000673
Chris Lattner2355f942004-02-11 01:17:07 +0000674 // Move all definitions in the successor to the predecessor...
675 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattner18961502002-06-25 16:12:52 +0000676
Chris Lattner2355f942004-02-11 01:17:07 +0000677 // Make all PHI nodes that referred to BB now refer to Pred as their
678 // source...
679 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +0000680
Chris Lattner2355f942004-02-11 01:17:07 +0000681 std::string OldName = BB->getName();
Chris Lattner18961502002-06-25 16:12:52 +0000682
Chris Lattner2355f942004-02-11 01:17:07 +0000683 // Erase basic block from the function...
684 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +0000685
Chris Lattner2355f942004-02-11 01:17:07 +0000686 // Inherit predecessors name if it exists...
687 if (!OldName.empty() && !OnlyPred->hasName())
688 OnlyPred->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000689
Chris Lattner2355f942004-02-11 01:17:07 +0000690 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000691 }
Chris Lattner723c66d2004-02-11 03:36:04 +0000692
Chris Lattner0d560082004-02-24 05:38:11 +0000693 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
694 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
695 // Change br (X == 0 | X == 1), T, F into a switch instruction.
696 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
697 Instruction *Cond = cast<Instruction>(BI->getCondition());
698 // If this is a bunch of seteq's or'd together, or if it's a bunch of
699 // 'setne's and'ed together, collect them.
700 Value *CompVal = 0;
701 std::vector<Constant*> Values;
702 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
703 if (CompVal && CompVal->getType()->isInteger()) {
704 // There might be duplicate constants in the list, which the switch
705 // instruction can't handle, remove them now.
706 std::sort(Values.begin(), Values.end());
707 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
708
709 // Figure out which block is which destination.
710 BasicBlock *DefaultBB = BI->getSuccessor(1);
711 BasicBlock *EdgeBB = BI->getSuccessor(0);
712 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
713
714 // Create the new switch instruction now.
715 SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
716
717 // Add all of the 'cases' to the switch instruction.
718 for (unsigned i = 0, e = Values.size(); i != e; ++i)
719 New->addCase(Values[i], EdgeBB);
720
721 // We added edges from PI to the EdgeBB. As such, if there were any
722 // PHI nodes in EdgeBB, they need entries to be added corresponding to
723 // the number of edges added.
724 for (BasicBlock::iterator BBI = EdgeBB->begin();
725 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
726 Value *InVal = PN->getIncomingValueForBlock(*PI);
727 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
728 PN->addIncoming(InVal, *PI);
729 }
730
731 // Erase the old branch instruction.
732 (*PI)->getInstList().erase(BI);
733
734 // Erase the potentially condition tree that was used to computed the
735 // branch condition.
736 ErasePossiblyDeadInstructionTree(Cond);
737 return true;
738 }
739 }
740
Chris Lattner723c66d2004-02-11 03:36:04 +0000741 // If there is a trivial two-entry PHI node in this basic block, and we can
742 // eliminate it, do so now.
743 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
744 if (PN->getNumIncomingValues() == 2) {
745 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
746 // statement", which has a very simple dominance structure. Basically, we
747 // are trying to find the condition that is being branched on, which
748 // subsequently causes this merge to happen. We really want control
749 // dependence information for this check, but simplifycfg can't keep it up
750 // to date, and this catches most of the cases we care about anyway.
751 //
752 BasicBlock *IfTrue, *IfFalse;
753 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
754 //std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
755 // << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
756
757 // Figure out where to insert instructions as necessary.
758 BasicBlock::iterator AfterPHIIt = BB->begin();
759 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
760
761 BasicBlock::iterator I = BB->begin();
762 while (PHINode *PN = dyn_cast<PHINode>(I)) {
763 ++I;
764
765 // If we can eliminate this PHI by directly computing it based on the
766 // condition, do so now. We can't eliminate PHI nodes where the
767 // incoming values are defined in the conditional parts of the branch,
768 // so check for this.
769 //
770 if (DominatesMergePoint(PN->getIncomingValue(0), BB) &&
771 DominatesMergePoint(PN->getIncomingValue(1), BB)) {
772 Value *TrueVal =
773 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
774 Value *FalseVal =
775 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
776
777 // FIXME: when we have a 'select' statement, we can be completely
778 // generic and clean here and let the instcombine pass clean up
779 // after us, by folding the select instructions away when possible.
780 //
781 if (TrueVal == FalseVal) {
782 // Degenerate case...
783 PN->replaceAllUsesWith(TrueVal);
784 BB->getInstList().erase(PN);
785 Changed = true;
786 } else if (isa<ConstantBool>(TrueVal) &&
787 isa<ConstantBool>(FalseVal)) {
788 if (TrueVal == ConstantBool::True) {
789 // The PHI node produces the same thing as the condition.
790 PN->replaceAllUsesWith(IfCond);
791 } else {
792 // The PHI node produces the inverse of the condition. Insert a
793 // "NOT" instruction, which is really a XOR.
794 Value *InverseCond =
795 BinaryOperator::createNot(IfCond, IfCond->getName()+".inv",
796 AfterPHIIt);
797 PN->replaceAllUsesWith(InverseCond);
798 }
799 BB->getInstList().erase(PN);
800 Changed = true;
801 } else if (isa<ConstantInt>(TrueVal) && isa<ConstantInt>(FalseVal)){
802 // If this is a PHI of two constant integers, we insert a cast of
803 // the boolean to the integer type in question, giving us 0 or 1.
804 // Then we multiply this by the difference of the two constants,
805 // giving us 0 if false, and the difference if true. We add this
806 // result to the base constant, giving us our final value. We
807 // rely on the instruction combiner to eliminate many special
808 // cases, like turning multiplies into shifts when possible.
809 std::string Name = PN->getName(); PN->setName("");
810 Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
811 Name, AfterPHIIt);
812 Constant *TheDiff = ConstantExpr::get(Instruction::Sub,
813 cast<Constant>(TrueVal),
814 cast<Constant>(FalseVal));
815 Value *V = TheCast;
816 if (TheDiff != ConstantInt::get(TrueVal->getType(), 1))
817 V = BinaryOperator::create(Instruction::Mul, TheCast,
818 TheDiff, TheCast->getName()+".scale",
819 AfterPHIIt);
820 if (!cast<Constant>(FalseVal)->isNullValue())
821 V = BinaryOperator::create(Instruction::Add, V, FalseVal,
822 V->getName()+".offs", AfterPHIIt);
823 PN->replaceAllUsesWith(V);
824 BB->getInstList().erase(PN);
825 Changed = true;
826 } else if (isa<ConstantInt>(FalseVal) &&
827 cast<Constant>(FalseVal)->isNullValue()) {
828 // If the false condition is an integral zero value, we can
829 // compute the PHI by multiplying the condition by the other
830 // value.
831 std::string Name = PN->getName(); PN->setName("");
832 Value *TheCast = new CastInst(IfCond, TrueVal->getType(),
833 Name+".c", AfterPHIIt);
834 Value *V = BinaryOperator::create(Instruction::Mul, TrueVal,
835 TheCast, Name, AfterPHIIt);
836 PN->replaceAllUsesWith(V);
837 BB->getInstList().erase(PN);
838 Changed = true;
839 } else if (isa<ConstantInt>(TrueVal) &&
840 cast<Constant>(TrueVal)->isNullValue()) {
841 // If the true condition is an integral zero value, we can compute
842 // the PHI by multiplying the inverse condition by the other
843 // value.
844 std::string Name = PN->getName(); PN->setName("");
845 Value *NotCond = BinaryOperator::createNot(IfCond, Name+".inv",
846 AfterPHIIt);
847 Value *TheCast = new CastInst(NotCond, TrueVal->getType(),
848 Name+".inv", AfterPHIIt);
849 Value *V = BinaryOperator::create(Instruction::Mul, FalseVal,
850 TheCast, Name, AfterPHIIt);
851 PN->replaceAllUsesWith(V);
852 BB->getInstList().erase(PN);
853 Changed = true;
854 }
855 }
856 }
857 }
858 }
Chris Lattner01d1ee32002-05-21 20:50:24 +0000859
Chris Lattner694e37f2003-08-17 19:41:53 +0000860 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000861}