blob: 579812efa8f556e2e2606973651d616cc0ba4c8e [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
Chris Lattner218a8222004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner01d1ee32002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Chris Lattner0d560082004-02-24 05:38:11 +000018#include "llvm/Type.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000019#include "llvm/Support/CFG.h"
Chris Lattner218a8222004-06-20 01:13:18 +000020#include "Support/Debug.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000021#include <algorithm>
22#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000023#include <set>
Reid Spencer954da372004-07-04 12:19:56 +000024#include <iostream>
25
Chris Lattnerf7703df2004-01-09 06:12:26 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner0d560082004-02-24 05:38:11 +000028// PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
29// predecessors from "BB". This is a little tricky because "Succ" has PHI
30// nodes, which need to have extra slots added to them to hold the merge edges
31// from BB's predecessors, and BB itself might have had PHI nodes in it. This
32// function returns true (failure) if the Succ BB already has a predecessor that
33// is a predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner01d1ee32002-05-21 20:50:24 +000034//
35// Assumption: Succ is the single successor for BB.
36//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000037static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000038 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000039
40 if (!isa<PHINode>(Succ->front()))
41 return false; // We can make the transformation, no problem.
Chris Lattner01d1ee32002-05-21 20:50:24 +000042
43 // If there is more than one predecessor, and there are PHI nodes in
44 // the successor, then we need to add incoming edges for the PHI nodes
45 //
46 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
47
48 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000049 // Succ. If so, we cannot do the transformation if there are any PHI nodes
50 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000051 //
Chris Lattnere2ca5402003-03-05 21:01:52 +000052 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
53 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
54 // Loop over all of the PHI nodes checking to see if there are
55 // incompatible values coming in.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000056 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000057 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere2ca5402003-03-05 21:01:52 +000058 // Loop up the entries in the PHI node for BB and for *PI if the values
59 // coming in are non-equal, we cannot merge these two blocks (instead we
60 // should insert a conditional move or something, then merge the
61 // blocks).
62 int Idx1 = PN->getBasicBlockIndex(BB);
63 int Idx2 = PN->getBasicBlockIndex(*PI);
64 assert(Idx1 != -1 && Idx2 != -1 &&
65 "Didn't have entries for my predecessors??");
66 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
67 return true; // Values are not equal...
68 }
69 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000070
Chris Lattner218a8222004-06-20 01:13:18 +000071 // Loop over all of the PHI nodes in the successor BB.
Chris Lattner01d1ee32002-05-21 20:50:24 +000072 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000073 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerbb190ac2002-10-08 21:36:33 +000074 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner01d1ee32002-05-21 20:50:24 +000075 assert(OldVal && "No entry in PHI for Pred BB!");
76
Chris Lattner218a8222004-06-20 01:13:18 +000077 // If this incoming value is one of the PHI nodes in BB, the new entries in
78 // the PHI node are the entries from the old PHI.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000079 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
80 PHINode *OldValPN = cast<PHINode>(OldVal);
Chris Lattner218a8222004-06-20 01:13:18 +000081 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
82 PN->addIncoming(OldValPN->getIncomingValue(i),
83 OldValPN->getIncomingBlock(i));
Chris Lattner46a5f1f2003-03-05 21:36:33 +000084 } else {
85 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
86 End = BBPreds.end(); PredI != End; ++PredI) {
87 // Add an incoming value for each of the new incoming values...
88 PN->addIncoming(OldVal, *PredI);
89 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000090 }
91 }
92 return false;
93}
94
Chris Lattner723c66d2004-02-11 03:36:04 +000095/// GetIfCondition - Given a basic block (BB) with two predecessors (and
96/// presumably PHI nodes in it), check to see if the merge at this block is due
97/// to an "if condition". If so, return the boolean condition that determines
98/// which entry into BB will be taken. Also, return by references the block
99/// that will be entered from if the condition is true, and the block that will
100/// be entered if the condition is false.
101///
102///
103static Value *GetIfCondition(BasicBlock *BB,
104 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
105 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
106 "Function can only handle blocks with 2 predecessors!");
107 BasicBlock *Pred1 = *pred_begin(BB);
108 BasicBlock *Pred2 = *++pred_begin(BB);
109
110 // We can only handle branches. Other control flow will be lowered to
111 // branches if possible anyway.
112 if (!isa<BranchInst>(Pred1->getTerminator()) ||
113 !isa<BranchInst>(Pred2->getTerminator()))
114 return 0;
115 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
116 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
117
118 // Eliminate code duplication by ensuring that Pred1Br is conditional if
119 // either are.
120 if (Pred2Br->isConditional()) {
121 // If both branches are conditional, we don't have an "if statement". In
122 // reality, we could transform this case, but since the condition will be
123 // required anyway, we stand no chance of eliminating it, so the xform is
124 // probably not profitable.
125 if (Pred1Br->isConditional())
126 return 0;
127
128 std::swap(Pred1, Pred2);
129 std::swap(Pred1Br, Pred2Br);
130 }
131
132 if (Pred1Br->isConditional()) {
133 // If we found a conditional branch predecessor, make sure that it branches
134 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
135 if (Pred1Br->getSuccessor(0) == BB &&
136 Pred1Br->getSuccessor(1) == Pred2) {
137 IfTrue = Pred1;
138 IfFalse = Pred2;
139 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
140 Pred1Br->getSuccessor(1) == BB) {
141 IfTrue = Pred2;
142 IfFalse = Pred1;
143 } else {
144 // We know that one arm of the conditional goes to BB, so the other must
145 // go somewhere unrelated, and this must not be an "if statement".
146 return 0;
147 }
148
149 // The only thing we have to watch out for here is to make sure that Pred2
150 // doesn't have incoming edges from other blocks. If it does, the condition
151 // doesn't dominate BB.
152 if (++pred_begin(Pred2) != pred_end(Pred2))
153 return 0;
154
155 return Pred1Br->getCondition();
156 }
157
158 // Ok, if we got here, both predecessors end with an unconditional branch to
159 // BB. Don't panic! If both blocks only have a single (identical)
160 // predecessor, and THAT is a conditional branch, then we're all ok!
161 if (pred_begin(Pred1) == pred_end(Pred1) ||
162 ++pred_begin(Pred1) != pred_end(Pred1) ||
163 pred_begin(Pred2) == pred_end(Pred2) ||
164 ++pred_begin(Pred2) != pred_end(Pred2) ||
165 *pred_begin(Pred1) != *pred_begin(Pred2))
166 return 0;
167
168 // Otherwise, if this is a conditional branch, then we can use it!
169 BasicBlock *CommonPred = *pred_begin(Pred1);
170 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
171 assert(BI->isConditional() && "Two successors but not conditional?");
172 if (BI->getSuccessor(0) == Pred1) {
173 IfTrue = Pred1;
174 IfFalse = Pred2;
175 } else {
176 IfTrue = Pred2;
177 IfFalse = Pred1;
178 }
179 return BI->getCondition();
180 }
181 return 0;
182}
183
184
185// If we have a merge point of an "if condition" as accepted above, return true
186// if the specified value dominates the block. We don't handle the true
187// generality of domination here, just a special case which works well enough
188// for us.
Chris Lattner570751c2004-04-09 22:50:22 +0000189static bool DominatesMergePoint(Value *V, BasicBlock *BB, bool AllowAggressive){
190 Instruction *I = dyn_cast<Instruction>(V);
191 if (!I) return true; // Non-instructions all dominate instructions.
192 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000193
Chris Lattner570751c2004-04-09 22:50:22 +0000194 // We don't want to allow wierd loops that might have the "if condition" in
195 // the bottom of this block.
196 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000197
Chris Lattner570751c2004-04-09 22:50:22 +0000198 // If this instruction is defined in a block that contains an unconditional
199 // branch to BB, then it must be in the 'conditional' part of the "if
200 // statement".
201 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
202 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
203 if (!AllowAggressive) return false;
204 // Okay, it looks like the instruction IS in the "condition". Check to
205 // see if its a cheap instruction to unconditionally compute, and if it
206 // only uses stuff defined outside of the condition. If so, hoist it out.
207 switch (I->getOpcode()) {
208 default: return false; // Cannot hoist this out safely.
209 case Instruction::Load:
210 // We can hoist loads that are non-volatile and obviously cannot trap.
211 if (cast<LoadInst>(I)->isVolatile())
212 return false;
213 if (!isa<AllocaInst>(I->getOperand(0)) &&
214 !isa<Constant>(I->getOperand(0)) &&
215 !isa<GlobalValue>(I->getOperand(0)))
216 return false;
217
218 // Finally, we have to check to make sure there are no instructions
219 // before the load in its basic block, as we are going to hoist the loop
220 // out to its predecessor.
221 if (PBB->begin() != BasicBlock::iterator(I))
222 return false;
223 break;
224 case Instruction::Add:
225 case Instruction::Sub:
226 case Instruction::And:
227 case Instruction::Or:
228 case Instruction::Xor:
229 case Instruction::Shl:
230 case Instruction::Shr:
231 break; // These are all cheap and non-trapping instructions.
232 }
233
234 // Okay, we can only really hoist these out if their operands are not
235 // defined in the conditional region.
236 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
237 if (!DominatesMergePoint(I->getOperand(i), BB, false))
238 return false;
239 // Okay, it's safe to do this!
240 }
241
Chris Lattner723c66d2004-02-11 03:36:04 +0000242 return true;
243}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000244
Chris Lattner0d560082004-02-24 05:38:11 +0000245// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
246// instructions that compare a value against a constant, return the value being
247// compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000248static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000249 if (Instruction *Inst = dyn_cast<Instruction>(V))
250 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000251 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000252 Values.push_back(C);
253 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000254 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000255 Values.push_back(C);
256 return Inst->getOperand(1);
257 }
258 } else if (Inst->getOpcode() == Instruction::Or) {
259 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
260 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
261 if (LHS == RHS)
262 return LHS;
263 }
264 return 0;
265}
266
267// GatherConstantSetNEs - Given a potentially 'and'd together collection of
268// setne instructions that compare a value against a constant, return the value
269// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000270static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000271 if (Instruction *Inst = dyn_cast<Instruction>(V))
272 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000273 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000274 Values.push_back(C);
275 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000276 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000277 Values.push_back(C);
278 return Inst->getOperand(1);
279 }
280 } else if (Inst->getOpcode() == Instruction::Cast) {
281 // Cast of X to bool is really a comparison against zero.
282 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattner1654cff2004-06-19 07:02:14 +0000283 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner0d560082004-02-24 05:38:11 +0000284 return Inst->getOperand(0);
285 } else if (Inst->getOpcode() == Instruction::And) {
286 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
287 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
288 if (LHS == RHS)
289 return LHS;
290 }
291 return 0;
292}
293
294
295
296/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
297/// bunch of comparisons of one value against constants, return the value and
298/// the constants being compared.
299static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000300 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000301 if (Cond->getOpcode() == Instruction::Or) {
302 CompVal = GatherConstantSetEQs(Cond, Values);
303
304 // Return true to indicate that the condition is true if the CompVal is
305 // equal to one of the constants.
306 return true;
307 } else if (Cond->getOpcode() == Instruction::And) {
308 CompVal = GatherConstantSetNEs(Cond, Values);
309
310 // Return false to indicate that the condition is false if the CompVal is
311 // equal to one of the constants.
312 return false;
313 }
314 return false;
315}
316
317/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
318/// has no side effects, nuke it. If it uses any instructions that become dead
319/// because the instruction is now gone, nuke them too.
320static void ErasePossiblyDeadInstructionTree(Instruction *I) {
321 if (isInstructionTriviallyDead(I)) {
322 std::vector<Value*> Operands(I->op_begin(), I->op_end());
323 I->getParent()->getInstList().erase(I);
324 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
325 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
326 ErasePossiblyDeadInstructionTree(OpI);
327 }
328}
329
Chris Lattnerd52c2612004-02-24 07:23:58 +0000330/// SafeToMergeTerminators - Return true if it is safe to merge these two
331/// terminator instructions together.
332///
333static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
334 if (SI1 == SI2) return false; // Can't merge with self!
335
336 // It is not safe to merge these two switch instructions if they have a common
Chris Lattner2636c1b2004-06-21 07:19:01 +0000337 // successor, and if that successor has a PHI node, and if *that* PHI node has
Chris Lattnerd52c2612004-02-24 07:23:58 +0000338 // conflicting incoming values from the two switch blocks.
339 BasicBlock *SI1BB = SI1->getParent();
340 BasicBlock *SI2BB = SI2->getParent();
341 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
342
343 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
344 if (SI1Succs.count(*I))
345 for (BasicBlock::iterator BBI = (*I)->begin();
346 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI)
347 if (PN->getIncomingValueForBlock(SI1BB) !=
348 PN->getIncomingValueForBlock(SI2BB))
349 return false;
350
351 return true;
352}
353
354/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
355/// now be entries in it from the 'NewPred' block. The values that will be
356/// flowing into the PHI nodes will be the same as those coming in from
Chris Lattner2636c1b2004-06-21 07:19:01 +0000357/// ExistPred, an existing predecessor of Succ.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000358static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
359 BasicBlock *ExistPred) {
360 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
361 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
362 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
363
364 for (BasicBlock::iterator I = Succ->begin();
365 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
366 Value *V = PN->getIncomingValueForBlock(ExistPred);
367 PN->addIncoming(V, NewPred);
368 }
369}
370
Chris Lattner542f1492004-02-28 21:28:10 +0000371// isValueEqualityComparison - Return true if the specified terminator checks to
372// see if a value is equal to constant integer value.
373static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000374 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
375 // Do not permit merging of large switch instructions into their
376 // predecessors unless there is only one predecessor.
377 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
378 pred_end(SI->getParent())) > 128)
379 return 0;
380
Chris Lattner542f1492004-02-28 21:28:10 +0000381 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000382 }
Chris Lattner542f1492004-02-28 21:28:10 +0000383 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
384 if (BI->isConditional() && BI->getCondition()->hasOneUse())
385 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
386 if ((SCI->getOpcode() == Instruction::SetEQ ||
387 SCI->getOpcode() == Instruction::SetNE) &&
388 isa<ConstantInt>(SCI->getOperand(1)))
389 return SCI->getOperand(0);
390 return 0;
391}
392
393// Given a value comparison instruction, decode all of the 'cases' that it
394// represents and return the 'default' block.
395static BasicBlock *
396GetValueEqualityComparisonCases(TerminatorInst *TI,
397 std::vector<std::pair<ConstantInt*,
398 BasicBlock*> > &Cases) {
399 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
400 Cases.reserve(SI->getNumCases());
401 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
402 Cases.push_back(std::make_pair(cast<ConstantInt>(SI->getCaseValue(i)),
403 SI->getSuccessor(i)));
404 return SI->getDefaultDest();
405 }
406
407 BranchInst *BI = cast<BranchInst>(TI);
408 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
409 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
410 BI->getSuccessor(SCI->getOpcode() ==
411 Instruction::SetNE)));
412 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
413}
414
415
416// FoldValueComparisonIntoPredecessors - The specified terminator is a value
417// equality comparison instruction (either a switch or a branch on "X == c").
418// See if any of the predecessors of the terminator block are value comparisons
419// on the same value. If so, and if safe to do so, fold them together.
420static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
421 BasicBlock *BB = TI->getParent();
422 Value *CV = isValueEqualityComparison(TI); // CondVal
423 assert(CV && "Not a comparison?");
424 bool Changed = false;
425
426 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
427 while (!Preds.empty()) {
428 BasicBlock *Pred = Preds.back();
429 Preds.pop_back();
430
431 // See if the predecessor is a comparison with the same value.
432 TerminatorInst *PTI = Pred->getTerminator();
433 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
434
435 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
436 // Figure out which 'cases' to copy from SI to PSI.
437 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
438 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
439
440 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
441 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
442
443 // Based on whether the default edge from PTI goes to BB or not, fill in
444 // PredCases and PredDefault with the new switch cases we would like to
445 // build.
446 std::vector<BasicBlock*> NewSuccessors;
447
448 if (PredDefault == BB) {
449 // If this is the default destination from PTI, only the edges in TI
450 // that don't occur in PTI, or that branch to BB will be activated.
451 std::set<ConstantInt*> PTIHandled;
452 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
453 if (PredCases[i].second != BB)
454 PTIHandled.insert(PredCases[i].first);
455 else {
456 // The default destination is BB, we don't need explicit targets.
457 std::swap(PredCases[i], PredCases.back());
458 PredCases.pop_back();
459 --i; --e;
460 }
461
462 // Reconstruct the new switch statement we will be building.
463 if (PredDefault != BBDefault) {
464 PredDefault->removePredecessor(Pred);
465 PredDefault = BBDefault;
466 NewSuccessors.push_back(BBDefault);
467 }
468 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
469 if (!PTIHandled.count(BBCases[i].first) &&
470 BBCases[i].second != BBDefault) {
471 PredCases.push_back(BBCases[i]);
472 NewSuccessors.push_back(BBCases[i].second);
473 }
474
475 } else {
476 // If this is not the default destination from PSI, only the edges
477 // in SI that occur in PSI with a destination of BB will be
478 // activated.
479 std::set<ConstantInt*> PTIHandled;
480 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
481 if (PredCases[i].second == BB) {
482 PTIHandled.insert(PredCases[i].first);
483 std::swap(PredCases[i], PredCases.back());
484 PredCases.pop_back();
485 --i; --e;
486 }
487
488 // Okay, now we know which constants were sent to BB from the
489 // predecessor. Figure out where they will all go now.
490 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
491 if (PTIHandled.count(BBCases[i].first)) {
492 // If this is one we are capable of getting...
493 PredCases.push_back(BBCases[i]);
494 NewSuccessors.push_back(BBCases[i].second);
495 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
496 }
497
498 // If there are any constants vectored to BB that TI doesn't handle,
499 // they must go to the default destination of TI.
500 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
501 E = PTIHandled.end(); I != E; ++I) {
502 PredCases.push_back(std::make_pair(*I, BBDefault));
503 NewSuccessors.push_back(BBDefault);
504 }
505 }
506
507 // Okay, at this point, we know which new successor Pred will get. Make
508 // sure we update the number of entries in the PHI nodes for these
509 // successors.
510 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
511 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
512
513 // Now that the successors are updated, create the new Switch instruction.
514 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PTI);
515 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
516 NewSI->addCase(PredCases[i].first, PredCases[i].second);
517 Pred->getInstList().erase(PTI);
518
519 // Okay, last check. If BB is still a successor of PSI, then we must
520 // have an infinite loop case. If so, add an infinitely looping block
521 // to handle the case to preserve the behavior of the code.
522 BasicBlock *InfLoopBlock = 0;
523 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
524 if (NewSI->getSuccessor(i) == BB) {
525 if (InfLoopBlock == 0) {
526 // Insert it at the end of the loop, because it's either code,
527 // or it won't matter if it's hot. :)
528 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
529 new BranchInst(InfLoopBlock, InfLoopBlock);
530 }
531 NewSI->setSuccessor(i, InfLoopBlock);
532 }
533
534 Changed = true;
535 }
536 }
537 return Changed;
538}
539
Chris Lattner1654cff2004-06-19 07:02:14 +0000540namespace {
541 /// ConstantIntOrdering - This class implements a stable ordering of constant
542 /// integers that does not depend on their address. This is important for
543 /// applications that sort ConstantInt's to ensure uniqueness.
544 struct ConstantIntOrdering {
545 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
546 return LHS->getRawValue() < RHS->getRawValue();
547 }
548 };
549}
550
Chris Lattner542f1492004-02-28 21:28:10 +0000551
Chris Lattner01d1ee32002-05-21 20:50:24 +0000552// SimplifyCFG - This function is used to do simplification of a CFG. For
553// example, it adjusts branches to branches to eliminate the extra hop, it
554// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +0000555// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000556//
557// WARNING: The entry node of a function may not be simplified.
558//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000559bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000560 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000561 Function *M = BB->getParent();
562
563 assert(BB && BB->getParent() && "Block not embedded in function!");
564 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +0000565 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +0000566
Chris Lattner01d1ee32002-05-21 20:50:24 +0000567 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000568 if (pred_begin(BB) == pred_end(BB) ||
569 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner218a8222004-06-20 01:13:18 +0000570 DEBUG(std::cerr << "Removing BB: \n" << BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000571
572 // Loop through all of our successors and make sure they know that one
573 // of their predecessors is going away.
574 for_each(succ_begin(BB), succ_end(BB),
575 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
576
577 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000578 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000579 // If this instruction is used, replace uses with an arbitrary
580 // constant value. Because control flow can't get here, we don't care
581 // what we replace the value with. Note that since this block is
582 // unreachable, and all values contained within it must dominate their
583 // uses, that all uses will eventually be removed.
Chris Lattner18961502002-06-25 16:12:52 +0000584 if (!I.use_empty())
Chris Lattner01d1ee32002-05-21 20:50:24 +0000585 // Make all users of this instruction reference the constant instead
Chris Lattner18961502002-06-25 16:12:52 +0000586 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner01d1ee32002-05-21 20:50:24 +0000587
588 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000589 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000590 }
Chris Lattner18961502002-06-25 16:12:52 +0000591 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000592 return true;
593 }
594
Chris Lattner694e37f2003-08-17 19:41:53 +0000595 // Check to see if we can constant propagate this terminator instruction
596 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000597 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000598
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000599 // Check to see if this block has no non-phi instructions and only a single
600 // successor. If so, replace references to this basic block with references
601 // to the successor.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000602 succ_iterator SI(succ_begin(BB));
603 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000604
605 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
606 while (isa<PHINode>(*BBI)) ++BBI;
607
608 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000609 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
610
611 if (Succ != BB) { // Arg, don't hurt infinite loops!
612 // If our successor has PHI nodes, then we need to update them to
613 // include entries for BB's predecessors, not for BB itself.
614 // Be careful though, if this transformation fails (returns true) then
615 // we cannot do this transformation!
616 //
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000617 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner218a8222004-06-20 01:13:18 +0000618 DEBUG(std::cerr << "Killing Trivial BB: \n" << BB);
Chris Lattner18961502002-06-25 16:12:52 +0000619 std::string OldName = BB->getName();
620
Chris Lattner3a438372003-03-07 18:13:41 +0000621 std::vector<BasicBlock*>
622 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
623
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000624 // Move all PHI nodes in BB to Succ if they are alive, otherwise
625 // delete them.
626 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
627 if (PN->use_empty())
628 BB->getInstList().erase(BB->begin()); // Nuke instruction...
629 else {
630 // The instruction is alive, so this means that Succ must have
631 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner3a438372003-03-07 18:13:41 +0000632 // now. Simply move it into Succ, because we know that BB
633 // strictly dominated Succ.
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000634 BB->getInstList().remove(BB->begin());
635 Succ->getInstList().push_front(PN);
Chris Lattner3a438372003-03-07 18:13:41 +0000636
637 // We need to add new entries for the PHI node to account for
638 // predecessors of Succ that the PHI node does not take into
639 // account. At this point, since we know that BB dominated succ,
640 // this means that we should any newly added incoming edges should
641 // use the PHI node as the value for these edges, because they are
642 // loop back edges.
Chris Lattner3a438372003-03-07 18:13:41 +0000643 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
644 if (OldSuccPreds[i] != BB)
645 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000646 }
647
Chris Lattner3a438372003-03-07 18:13:41 +0000648 // Everything that jumped to BB now goes to Succ...
649 BB->replaceAllUsesWith(Succ);
650
Chris Lattner18961502002-06-25 16:12:52 +0000651 // Delete the old basic block...
652 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000653
Chris Lattner18961502002-06-25 16:12:52 +0000654 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
655 Succ->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000656 return true;
657 }
658 }
659 }
660 }
661
Chris Lattner19831ec2004-02-16 06:35:48 +0000662 // If this is a returning block with only PHI nodes in it, fold the return
663 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +0000664 //
665 // If any predecessor is a conditional branch that just selects among
666 // different return values, fold the replace the branch/return with a select
667 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +0000668 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
669 BasicBlock::iterator BBI = BB->getTerminator();
670 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner147af6b2004-04-02 18:13:43 +0000671 // Find predecessors that end with branches.
Chris Lattner19831ec2004-02-16 06:35:48 +0000672 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner147af6b2004-04-02 18:13:43 +0000673 std::vector<BranchInst*> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +0000674 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
675 TerminatorInst *PTI = (*PI)->getTerminator();
676 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
677 if (BI->isUnconditional())
678 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +0000679 else
680 CondBranchPreds.push_back(BI);
Chris Lattner19831ec2004-02-16 06:35:48 +0000681 }
682
683 // If we found some, do the transformation!
684 if (!UncondBranchPreds.empty()) {
685 while (!UncondBranchPreds.empty()) {
686 BasicBlock *Pred = UncondBranchPreds.back();
687 UncondBranchPreds.pop_back();
688 Instruction *UncondBranch = Pred->getTerminator();
689 // Clone the return and add it to the end of the predecessor.
690 Instruction *NewRet = RI->clone();
691 Pred->getInstList().push_back(NewRet);
692
693 // If the return instruction returns a value, and if the value was a
694 // PHI node in "BB", propagate the right value into the return.
695 if (NewRet->getNumOperands() == 1)
696 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
697 if (PN->getParent() == BB)
698 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
699 // Update any PHI nodes in the returning block to realize that we no
700 // longer branch to them.
701 BB->removePredecessor(Pred);
702 Pred->getInstList().erase(UncondBranch);
703 }
704
705 // If we eliminated all predecessors of the block, delete the block now.
706 if (pred_begin(BB) == pred_end(BB))
707 // We know there are no successors, so just nuke the block.
708 M->getBasicBlockList().erase(BB);
709
Chris Lattner19831ec2004-02-16 06:35:48 +0000710 return true;
711 }
Chris Lattner147af6b2004-04-02 18:13:43 +0000712
713 // Check out all of the conditional branches going to this return
714 // instruction. If any of them just select between returns, change the
715 // branch itself into a select/return pair.
716 while (!CondBranchPreds.empty()) {
717 BranchInst *BI = CondBranchPreds.back();
718 CondBranchPreds.pop_back();
719 BasicBlock *TrueSucc = BI->getSuccessor(0);
720 BasicBlock *FalseSucc = BI->getSuccessor(1);
721 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
722
723 // Check to see if the non-BB successor is also a return block.
724 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
725 // Check to see if there are only PHI instructions in this block.
726 BasicBlock::iterator OSI = OtherSucc->getTerminator();
727 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
728 // Okay, we found a branch that is going to two return nodes. If
729 // there is no return value for this function, just change the
730 // branch into a return.
731 if (RI->getNumOperands() == 0) {
732 TrueSucc->removePredecessor(BI->getParent());
733 FalseSucc->removePredecessor(BI->getParent());
734 new ReturnInst(0, BI);
735 BI->getParent()->getInstList().erase(BI);
736 return true;
737 }
738
739 // Otherwise, figure out what the true and false return values are
740 // so we can insert a new select instruction.
741 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
742 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
743
744 // Unwrap any PHI nodes in the return blocks.
745 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
746 if (TVPN->getParent() == TrueSucc)
747 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
748 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
749 if (FVPN->getParent() == FalseSucc)
750 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
751
Chris Lattner7aa773b2004-04-02 18:15:10 +0000752 TrueSucc->removePredecessor(BI->getParent());
753 FalseSucc->removePredecessor(BI->getParent());
754
Chris Lattner147af6b2004-04-02 18:13:43 +0000755 // Insert a new select instruction.
756 Value *NewRetVal = new SelectInst(BI->getCondition(), TrueValue,
757 FalseValue, "retval", BI);
758 new ReturnInst(NewRetVal, BI);
759 BI->getParent()->getInstList().erase(BI);
760 return true;
761 }
762 }
763 }
Chris Lattner19831ec2004-02-16 06:35:48 +0000764 }
Chris Lattnere14ea082004-02-24 05:54:22 +0000765 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
766 // Check to see if the first instruction in this block is just an unwind.
767 // If so, replace any invoke instructions which use this as an exception
768 // destination with call instructions.
769 //
770 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
771 while (!Preds.empty()) {
772 BasicBlock *Pred = Preds.back();
773 if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
774 if (II->getUnwindDest() == BB) {
775 // Insert a new branch instruction before the invoke, because this
776 // is now a fall through...
777 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
778 Pred->getInstList().remove(II); // Take out of symbol table
779
780 // Insert the call now...
781 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
782 CallInst *CI = new CallInst(II->getCalledValue(), Args,
783 II->getName(), BI);
784 // If the invoke produced a value, the Call now does instead
785 II->replaceAllUsesWith(CI);
786 delete II;
787 Changed = true;
788 }
789
790 Preds.pop_back();
791 }
Chris Lattner8e509dd2004-02-24 16:09:21 +0000792
793 // If this block is now dead, remove it.
794 if (pred_begin(BB) == pred_end(BB)) {
795 // We know there are no successors, so just nuke the block.
796 M->getBasicBlockList().erase(BB);
797 return true;
798 }
799
Chris Lattnerd52c2612004-02-24 07:23:58 +0000800 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
Chris Lattner7acd1cc2004-03-17 02:02:47 +0000801 if (isValueEqualityComparison(SI))
802 if (FoldValueComparisonIntoPredecessors(SI))
803 return SimplifyCFG(BB) || 1;
Chris Lattner542f1492004-02-28 21:28:10 +0000804 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner92da2c22004-05-01 22:36:37 +0000805 if (BI->isConditional()) {
Chris Lattnere67fa052004-05-01 23:35:43 +0000806 if (Value *CompVal = isValueEqualityComparison(BI)) {
807 // This block must be empty, except for the setcond inst, if it exists.
808 BasicBlock::iterator I = BB->begin();
809 if (&*I == BI ||
810 (&*I == cast<Instruction>(BI->getCondition()) &&
811 &*++I == BI))
812 if (FoldValueComparisonIntoPredecessors(BI))
813 return SimplifyCFG(BB) | true;
814 }
815
816 // If this basic block is ONLY a setcc and a branch, and if a predecessor
817 // branches to us and one of our successors, fold the setcc into the
818 // predecessor and use logical operations to pick the right destination.
Chris Lattner12fe2b12004-05-02 05:02:03 +0000819 BasicBlock *TrueDest = BI->getSuccessor(0);
820 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbdcc0b82004-05-02 05:19:36 +0000821 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattnere67fa052004-05-01 23:35:43 +0000822 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner12fe2b12004-05-02 05:02:03 +0000823 Cond->getNext() == BI && Cond->hasOneUse() &&
824 TrueDest != BB && FalseDest != BB)
Chris Lattnere67fa052004-05-01 23:35:43 +0000825 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
826 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnera1f79fb2004-05-02 01:00:44 +0000827 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000828 BasicBlock *PredBlock = *PI;
Chris Lattnere67fa052004-05-01 23:35:43 +0000829 if (PBI->getSuccessor(0) == FalseDest ||
830 PBI->getSuccessor(1) == TrueDest) {
831 // Invert the predecessors condition test (xor it with true),
832 // which allows us to write this code once.
833 Value *NewCond =
834 BinaryOperator::createNot(PBI->getCondition(),
835 PBI->getCondition()->getName()+".not", PBI);
836 PBI->setCondition(NewCond);
837 BasicBlock *OldTrue = PBI->getSuccessor(0);
838 BasicBlock *OldFalse = PBI->getSuccessor(1);
839 PBI->setSuccessor(0, OldFalse);
840 PBI->setSuccessor(1, OldTrue);
841 }
842
843 if (PBI->getSuccessor(0) == TrueDest ||
844 PBI->getSuccessor(1) == FalseDest) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000845 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattnere67fa052004-05-01 23:35:43 +0000846 // two conditions together.
847 Instruction *New = Cond->clone();
848 New->setName(Cond->getName());
849 Cond->setName(Cond->getName()+".old");
Chris Lattner2636c1b2004-06-21 07:19:01 +0000850 PredBlock->getInstList().insert(PBI, New);
Chris Lattnere67fa052004-05-01 23:35:43 +0000851 Instruction::BinaryOps Opcode =
852 PBI->getSuccessor(0) == TrueDest ?
853 Instruction::Or : Instruction::And;
854 Value *NewCond =
855 BinaryOperator::create(Opcode, PBI->getCondition(),
856 New, "bothcond", PBI);
857 PBI->setCondition(NewCond);
858 if (PBI->getSuccessor(0) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000859 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +0000860 PBI->setSuccessor(0, TrueDest);
861 }
862 if (PBI->getSuccessor(1) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000863 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +0000864 PBI->setSuccessor(1, FalseDest);
865 }
866 return SimplifyCFG(BB) | 1;
867 }
868 }
Chris Lattnere67fa052004-05-01 23:35:43 +0000869
Chris Lattner92da2c22004-05-01 22:36:37 +0000870 // If this block ends with a branch instruction, and if there is one
871 // predecessor, see if the previous block ended with a branch on the same
872 // condition, which makes this conditional branch redundant.
873 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
874 BasicBlock *OnlyPred = *PI++;
875 for (; PI != PE; ++PI)// Search all predecessors, see if they are all same
876 if (*PI != OnlyPred) {
877 OnlyPred = 0; // There are multiple different predecessors...
878 break;
879 }
880
881 if (OnlyPred)
882 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
883 if (PBI->isConditional() &&
884 PBI->getCondition() == BI->getCondition() &&
Chris Lattner951fdb92004-05-01 22:41:51 +0000885 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner92da2c22004-05-01 22:36:37 +0000886 // Okay, the outcome of this conditional branch is statically
887 // knowable. Delete the outgoing CFG edge that is impossible to
888 // execute.
889 bool CondIsTrue = PBI->getSuccessor(0) == BB;
890 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
891 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
892 BB->getInstList().erase(BI);
893 return SimplifyCFG(BB) | true;
894 }
Chris Lattnerd52c2612004-02-24 07:23:58 +0000895 }
Chris Lattner19831ec2004-02-16 06:35:48 +0000896 }
897
Chris Lattner01d1ee32002-05-21 20:50:24 +0000898 // Merge basic blocks into their predecessor if there is only one distinct
899 // pred, and if there is only one distinct successor of the predecessor, and
900 // if there are no PHI nodes.
901 //
Chris Lattner2355f942004-02-11 01:17:07 +0000902 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
903 BasicBlock *OnlyPred = *PI++;
904 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
905 if (*PI != OnlyPred) {
906 OnlyPred = 0; // There are multiple different predecessors...
907 break;
908 }
Chris Lattner92da2c22004-05-01 22:36:37 +0000909
Chris Lattner2355f942004-02-11 01:17:07 +0000910 BasicBlock *OnlySucc = 0;
911 if (OnlyPred && OnlyPred != BB && // Don't break self loops
912 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
913 // Check to see if there is only one distinct successor...
914 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
915 OnlySucc = BB;
916 for (; SI != SE; ++SI)
917 if (*SI != OnlySucc) {
918 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000919 break;
920 }
Chris Lattner2355f942004-02-11 01:17:07 +0000921 }
922
923 if (OnlySucc) {
Chris Lattner218a8222004-06-20 01:13:18 +0000924 DEBUG(std::cerr << "Merging: " << BB << "into: " << OnlyPred);
Chris Lattner2355f942004-02-11 01:17:07 +0000925 TerminatorInst *Term = OnlyPred->getTerminator();
926
927 // Resolve any PHI nodes at the start of the block. They are all
928 // guaranteed to have exactly one entry if they exist, unless there are
929 // multiple duplicate (but guaranteed to be equal) entries for the
930 // incoming edges. This occurs when there are multiple edges from
931 // OnlyPred to OnlySucc.
932 //
933 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
934 PN->replaceAllUsesWith(PN->getIncomingValue(0));
935 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner01d1ee32002-05-21 20:50:24 +0000936 }
937
Chris Lattner2355f942004-02-11 01:17:07 +0000938 // Delete the unconditional branch from the predecessor...
939 OnlyPred->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000940
Chris Lattner2355f942004-02-11 01:17:07 +0000941 // Move all definitions in the successor to the predecessor...
942 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattner18961502002-06-25 16:12:52 +0000943
Chris Lattner2355f942004-02-11 01:17:07 +0000944 // Make all PHI nodes that referred to BB now refer to Pred as their
945 // source...
946 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +0000947
Chris Lattner2355f942004-02-11 01:17:07 +0000948 std::string OldName = BB->getName();
Chris Lattner18961502002-06-25 16:12:52 +0000949
Chris Lattner2355f942004-02-11 01:17:07 +0000950 // Erase basic block from the function...
951 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +0000952
Chris Lattner2355f942004-02-11 01:17:07 +0000953 // Inherit predecessors name if it exists...
954 if (!OldName.empty() && !OnlyPred->hasName())
955 OnlyPred->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000956
Chris Lattner2355f942004-02-11 01:17:07 +0000957 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000958 }
Chris Lattner723c66d2004-02-11 03:36:04 +0000959
Chris Lattner0d560082004-02-24 05:38:11 +0000960 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
961 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
962 // Change br (X == 0 | X == 1), T, F into a switch instruction.
963 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
964 Instruction *Cond = cast<Instruction>(BI->getCondition());
965 // If this is a bunch of seteq's or'd together, or if it's a bunch of
966 // 'setne's and'ed together, collect them.
967 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +0000968 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +0000969 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
970 if (CompVal && CompVal->getType()->isInteger()) {
971 // There might be duplicate constants in the list, which the switch
972 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +0000973 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +0000974 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
975
976 // Figure out which block is which destination.
977 BasicBlock *DefaultBB = BI->getSuccessor(1);
978 BasicBlock *EdgeBB = BI->getSuccessor(0);
979 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
980
981 // Create the new switch instruction now.
982 SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
983
984 // Add all of the 'cases' to the switch instruction.
985 for (unsigned i = 0, e = Values.size(); i != e; ++i)
986 New->addCase(Values[i], EdgeBB);
987
988 // We added edges from PI to the EdgeBB. As such, if there were any
989 // PHI nodes in EdgeBB, they need entries to be added corresponding to
990 // the number of edges added.
991 for (BasicBlock::iterator BBI = EdgeBB->begin();
992 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
993 Value *InVal = PN->getIncomingValueForBlock(*PI);
994 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
995 PN->addIncoming(InVal, *PI);
996 }
997
998 // Erase the old branch instruction.
999 (*PI)->getInstList().erase(BI);
1000
1001 // Erase the potentially condition tree that was used to computed the
1002 // branch condition.
1003 ErasePossiblyDeadInstructionTree(Cond);
1004 return true;
1005 }
1006 }
1007
Chris Lattner723c66d2004-02-11 03:36:04 +00001008 // If there is a trivial two-entry PHI node in this basic block, and we can
1009 // eliminate it, do so now.
1010 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1011 if (PN->getNumIncomingValues() == 2) {
1012 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1013 // statement", which has a very simple dominance structure. Basically, we
1014 // are trying to find the condition that is being branched on, which
1015 // subsequently causes this merge to happen. We really want control
1016 // dependence information for this check, but simplifycfg can't keep it up
1017 // to date, and this catches most of the cases we care about anyway.
1018 //
1019 BasicBlock *IfTrue, *IfFalse;
1020 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner218a8222004-06-20 01:13:18 +00001021 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1022 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner723c66d2004-02-11 03:36:04 +00001023
1024 // Figure out where to insert instructions as necessary.
1025 BasicBlock::iterator AfterPHIIt = BB->begin();
1026 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
1027
1028 BasicBlock::iterator I = BB->begin();
1029 while (PHINode *PN = dyn_cast<PHINode>(I)) {
1030 ++I;
1031
1032 // If we can eliminate this PHI by directly computing it based on the
1033 // condition, do so now. We can't eliminate PHI nodes where the
1034 // incoming values are defined in the conditional parts of the branch,
1035 // so check for this.
1036 //
Chris Lattner570751c2004-04-09 22:50:22 +00001037 if (DominatesMergePoint(PN->getIncomingValue(0), BB, true) &&
1038 DominatesMergePoint(PN->getIncomingValue(1), BB, true)) {
Chris Lattner723c66d2004-02-11 03:36:04 +00001039 Value *TrueVal =
1040 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1041 Value *FalseVal =
1042 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1043
Chris Lattner570751c2004-04-09 22:50:22 +00001044 // If one of the incoming values is defined in the conditional
1045 // region, move it into it's predecessor block, which we know is
1046 // safe.
1047 if (!DominatesMergePoint(TrueVal, BB, false)) {
1048 Instruction *TrueI = cast<Instruction>(TrueVal);
1049 BasicBlock *OldBB = TrueI->getParent();
1050 OldBB->getInstList().remove(TrueI);
1051 BasicBlock *NewBB = *pred_begin(OldBB);
1052 NewBB->getInstList().insert(NewBB->getTerminator(), TrueI);
1053 }
1054 if (!DominatesMergePoint(FalseVal, BB, false)) {
1055 Instruction *FalseI = cast<Instruction>(FalseVal);
1056 BasicBlock *OldBB = FalseI->getParent();
1057 OldBB->getInstList().remove(FalseI);
1058 BasicBlock *NewBB = *pred_begin(OldBB);
1059 NewBB->getInstList().insert(NewBB->getTerminator(), FalseI);
1060 }
1061
Chris Lattner552112f2004-03-30 19:44:05 +00001062 // Change the PHI node into a select instruction.
1063 BasicBlock::iterator InsertPos = PN;
1064 while (isa<PHINode>(InsertPos)) ++InsertPos;
1065
1066 std::string Name = PN->getName(); PN->setName("");
1067 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1068 Name, InsertPos));
1069 BB->getInstList().erase(PN);
1070 Changed = true;
Chris Lattner723c66d2004-02-11 03:36:04 +00001071 }
1072 }
1073 }
1074 }
Chris Lattner01d1ee32002-05-21 20:50:24 +00001075
Chris Lattner694e37f2003-08-17 19:41:53 +00001076 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001077}