blob: 419c8a7542156fc623592c900d06d2cf1a36bba6 [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/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
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner0d560082004-02-24 05:38:11 +000027// PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
28// predecessors from "BB". This is a little tricky because "Succ" has PHI
29// nodes, which need to have extra slots added to them to hold the merge edges
30// from BB's predecessors, and BB itself might have had PHI nodes in it. This
31// function returns true (failure) if the Succ BB already has a predecessor that
32// is a predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner01d1ee32002-05-21 20:50:24 +000033//
34// Assumption: Succ is the single successor for BB.
35//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000036static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000037 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000038
39 if (!isa<PHINode>(Succ->front()))
40 return false; // We can make the transformation, no problem.
Chris Lattner01d1ee32002-05-21 20:50:24 +000041
42 // If there is more than one predecessor, and there are PHI nodes in
43 // the successor, then we need to add incoming edges for the PHI nodes
44 //
45 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
46
47 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000048 // Succ. If so, we cannot do the transformation if there are any PHI nodes
49 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000050 //
Chris Lattnere2ca5402003-03-05 21:01:52 +000051 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000052 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
Chris Lattnere2ca5402003-03-05 21:01:52 +000053 // Loop over all of the PHI nodes checking to see if there are
54 // incompatible values coming in.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000055 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnere2ca5402003-03-05 21:01:52 +000057 // Loop up the entries in the PHI node for BB and for *PI if the values
58 // coming in are non-equal, we cannot merge these two blocks (instead we
59 // should insert a conditional move or something, then merge the
60 // blocks).
61 int Idx1 = PN->getBasicBlockIndex(BB);
62 int Idx2 = PN->getBasicBlockIndex(*PI);
63 assert(Idx1 != -1 && Idx2 != -1 &&
64 "Didn't have entries for my predecessors??");
65 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
66 return true; // Values are not equal...
67 }
68 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000069
Chris Lattner218a8222004-06-20 01:13:18 +000070 // Loop over all of the PHI nodes in the successor BB.
Chris Lattner01d1ee32002-05-21 20:50:24 +000071 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000072 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerbb190ac2002-10-08 21:36:33 +000073 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner01d1ee32002-05-21 20:50:24 +000074 assert(OldVal && "No entry in PHI for Pred BB!");
75
Chris Lattner218a8222004-06-20 01:13:18 +000076 // If this incoming value is one of the PHI nodes in BB, the new entries in
77 // the PHI node are the entries from the old PHI.
Chris Lattner46a5f1f2003-03-05 21:36:33 +000078 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
79 PHINode *OldValPN = cast<PHINode>(OldVal);
Chris Lattner218a8222004-06-20 01:13:18 +000080 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
81 PN->addIncoming(OldValPN->getIncomingValue(i),
82 OldValPN->getIncomingBlock(i));
Chris Lattner46a5f1f2003-03-05 21:36:33 +000083 } else {
84 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
85 End = BBPreds.end(); PredI != End; ++PredI) {
86 // Add an incoming value for each of the new incoming values...
87 PN->addIncoming(OldVal, *PredI);
88 }
Chris Lattner01d1ee32002-05-21 20:50:24 +000089 }
90 }
91 return false;
92}
93
Chris Lattner723c66d2004-02-11 03:36:04 +000094/// GetIfCondition - Given a basic block (BB) with two predecessors (and
95/// presumably PHI nodes in it), check to see if the merge at this block is due
96/// to an "if condition". If so, return the boolean condition that determines
97/// which entry into BB will be taken. Also, return by references the block
98/// that will be entered from if the condition is true, and the block that will
99/// be entered if the condition is false.
100///
101///
102static Value *GetIfCondition(BasicBlock *BB,
103 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
104 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
105 "Function can only handle blocks with 2 predecessors!");
106 BasicBlock *Pred1 = *pred_begin(BB);
107 BasicBlock *Pred2 = *++pred_begin(BB);
108
109 // We can only handle branches. Other control flow will be lowered to
110 // branches if possible anyway.
111 if (!isa<BranchInst>(Pred1->getTerminator()) ||
112 !isa<BranchInst>(Pred2->getTerminator()))
113 return 0;
114 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
115 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
116
117 // Eliminate code duplication by ensuring that Pred1Br is conditional if
118 // either are.
119 if (Pred2Br->isConditional()) {
120 // If both branches are conditional, we don't have an "if statement". In
121 // reality, we could transform this case, but since the condition will be
122 // required anyway, we stand no chance of eliminating it, so the xform is
123 // probably not profitable.
124 if (Pred1Br->isConditional())
125 return 0;
126
127 std::swap(Pred1, Pred2);
128 std::swap(Pred1Br, Pred2Br);
129 }
130
131 if (Pred1Br->isConditional()) {
132 // If we found a conditional branch predecessor, make sure that it branches
133 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
134 if (Pred1Br->getSuccessor(0) == BB &&
135 Pred1Br->getSuccessor(1) == Pred2) {
136 IfTrue = Pred1;
137 IfFalse = Pred2;
138 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
139 Pred1Br->getSuccessor(1) == BB) {
140 IfTrue = Pred2;
141 IfFalse = Pred1;
142 } else {
143 // We know that one arm of the conditional goes to BB, so the other must
144 // go somewhere unrelated, and this must not be an "if statement".
145 return 0;
146 }
147
148 // The only thing we have to watch out for here is to make sure that Pred2
149 // doesn't have incoming edges from other blocks. If it does, the condition
150 // doesn't dominate BB.
151 if (++pred_begin(Pred2) != pred_end(Pred2))
152 return 0;
153
154 return Pred1Br->getCondition();
155 }
156
157 // Ok, if we got here, both predecessors end with an unconditional branch to
158 // BB. Don't panic! If both blocks only have a single (identical)
159 // predecessor, and THAT is a conditional branch, then we're all ok!
160 if (pred_begin(Pred1) == pred_end(Pred1) ||
161 ++pred_begin(Pred1) != pred_end(Pred1) ||
162 pred_begin(Pred2) == pred_end(Pred2) ||
163 ++pred_begin(Pred2) != pred_end(Pred2) ||
164 *pred_begin(Pred1) != *pred_begin(Pred2))
165 return 0;
166
167 // Otherwise, if this is a conditional branch, then we can use it!
168 BasicBlock *CommonPred = *pred_begin(Pred1);
169 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
170 assert(BI->isConditional() && "Two successors but not conditional?");
171 if (BI->getSuccessor(0) == Pred1) {
172 IfTrue = Pred1;
173 IfFalse = Pred2;
174 } else {
175 IfTrue = Pred2;
176 IfFalse = Pred1;
177 }
178 return BI->getCondition();
179 }
180 return 0;
181}
182
183
184// If we have a merge point of an "if condition" as accepted above, return true
185// if the specified value dominates the block. We don't handle the true
186// generality of domination here, just a special case which works well enough
187// for us.
Chris Lattner570751c2004-04-09 22:50:22 +0000188static bool DominatesMergePoint(Value *V, BasicBlock *BB, bool AllowAggressive){
189 Instruction *I = dyn_cast<Instruction>(V);
190 if (!I) return true; // Non-instructions all dominate instructions.
191 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000192
Chris Lattner570751c2004-04-09 22:50:22 +0000193 // We don't want to allow wierd loops that might have the "if condition" in
194 // the bottom of this block.
195 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000196
Chris Lattner570751c2004-04-09 22:50:22 +0000197 // If this instruction is defined in a block that contains an unconditional
198 // branch to BB, then it must be in the 'conditional' part of the "if
199 // statement".
200 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
201 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
202 if (!AllowAggressive) return false;
203 // Okay, it looks like the instruction IS in the "condition". Check to
204 // see if its a cheap instruction to unconditionally compute, and if it
205 // only uses stuff defined outside of the condition. If so, hoist it out.
206 switch (I->getOpcode()) {
207 default: return false; // Cannot hoist this out safely.
208 case Instruction::Load:
209 // We can hoist loads that are non-volatile and obviously cannot trap.
210 if (cast<LoadInst>(I)->isVolatile())
211 return false;
212 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spencer460f16c2004-07-18 00:32:14 +0000213 !isa<Constant>(I->getOperand(0)))
Chris Lattner570751c2004-04-09 22:50:22 +0000214 return false;
215
216 // Finally, we have to check to make sure there are no instructions
217 // before the load in its basic block, as we are going to hoist the loop
218 // out to its predecessor.
219 if (PBB->begin() != BasicBlock::iterator(I))
220 return false;
221 break;
222 case Instruction::Add:
223 case Instruction::Sub:
224 case Instruction::And:
225 case Instruction::Or:
226 case Instruction::Xor:
227 case Instruction::Shl:
228 case Instruction::Shr:
229 break; // These are all cheap and non-trapping instructions.
230 }
231
232 // Okay, we can only really hoist these out if their operands are not
233 // defined in the conditional region.
234 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
235 if (!DominatesMergePoint(I->getOperand(i), BB, false))
236 return false;
237 // Okay, it's safe to do this!
238 }
239
Chris Lattner723c66d2004-02-11 03:36:04 +0000240 return true;
241}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000242
Chris Lattner0d560082004-02-24 05:38:11 +0000243// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
244// instructions that compare a value against a constant, return the value being
245// compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000246static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000247 if (Instruction *Inst = dyn_cast<Instruction>(V))
248 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000249 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000250 Values.push_back(C);
251 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000252 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000253 Values.push_back(C);
254 return Inst->getOperand(1);
255 }
256 } else if (Inst->getOpcode() == Instruction::Or) {
257 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
258 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
259 if (LHS == RHS)
260 return LHS;
261 }
262 return 0;
263}
264
265// GatherConstantSetNEs - Given a potentially 'and'd together collection of
266// setne instructions that compare a value against a constant, return the value
267// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000268static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000269 if (Instruction *Inst = dyn_cast<Instruction>(V))
270 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000271 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000272 Values.push_back(C);
273 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000274 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000275 Values.push_back(C);
276 return Inst->getOperand(1);
277 }
278 } else if (Inst->getOpcode() == Instruction::Cast) {
279 // Cast of X to bool is really a comparison against zero.
280 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattner1654cff2004-06-19 07:02:14 +0000281 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner0d560082004-02-24 05:38:11 +0000282 return Inst->getOperand(0);
283 } else if (Inst->getOpcode() == Instruction::And) {
284 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
285 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
286 if (LHS == RHS)
287 return LHS;
288 }
289 return 0;
290}
291
292
293
294/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
295/// bunch of comparisons of one value against constants, return the value and
296/// the constants being compared.
297static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000298 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000299 if (Cond->getOpcode() == Instruction::Or) {
300 CompVal = GatherConstantSetEQs(Cond, Values);
301
302 // Return true to indicate that the condition is true if the CompVal is
303 // equal to one of the constants.
304 return true;
305 } else if (Cond->getOpcode() == Instruction::And) {
306 CompVal = GatherConstantSetNEs(Cond, Values);
307
308 // Return false to indicate that the condition is false if the CompVal is
309 // equal to one of the constants.
310 return false;
311 }
312 return false;
313}
314
315/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
316/// has no side effects, nuke it. If it uses any instructions that become dead
317/// because the instruction is now gone, nuke them too.
318static void ErasePossiblyDeadInstructionTree(Instruction *I) {
319 if (isInstructionTriviallyDead(I)) {
320 std::vector<Value*> Operands(I->op_begin(), I->op_end());
321 I->getParent()->getInstList().erase(I);
322 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
323 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
324 ErasePossiblyDeadInstructionTree(OpI);
325 }
326}
327
Chris Lattnerd52c2612004-02-24 07:23:58 +0000328/// SafeToMergeTerminators - Return true if it is safe to merge these two
329/// terminator instructions together.
330///
331static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
332 if (SI1 == SI2) return false; // Can't merge with self!
333
334 // It is not safe to merge these two switch instructions if they have a common
Chris Lattner2636c1b2004-06-21 07:19:01 +0000335 // successor, and if that successor has a PHI node, and if *that* PHI node has
Chris Lattnerd52c2612004-02-24 07:23:58 +0000336 // conflicting incoming values from the two switch blocks.
337 BasicBlock *SI1BB = SI1->getParent();
338 BasicBlock *SI2BB = SI2->getParent();
339 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
340
341 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
342 if (SI1Succs.count(*I))
343 for (BasicBlock::iterator BBI = (*I)->begin();
344 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI)
345 if (PN->getIncomingValueForBlock(SI1BB) !=
346 PN->getIncomingValueForBlock(SI2BB))
347 return false;
348
349 return true;
350}
351
352/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
353/// now be entries in it from the 'NewPred' block. The values that will be
354/// flowing into the PHI nodes will be the same as those coming in from
Chris Lattner2636c1b2004-06-21 07:19:01 +0000355/// ExistPred, an existing predecessor of Succ.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000356static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
357 BasicBlock *ExistPred) {
358 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
359 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
360 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
361
362 for (BasicBlock::iterator I = Succ->begin();
363 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
364 Value *V = PN->getIncomingValueForBlock(ExistPred);
365 PN->addIncoming(V, NewPred);
366 }
367}
368
Chris Lattner542f1492004-02-28 21:28:10 +0000369// isValueEqualityComparison - Return true if the specified terminator checks to
370// see if a value is equal to constant integer value.
371static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000372 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
373 // Do not permit merging of large switch instructions into their
374 // predecessors unless there is only one predecessor.
375 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
376 pred_end(SI->getParent())) > 128)
377 return 0;
378
Chris Lattner542f1492004-02-28 21:28:10 +0000379 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000380 }
Chris Lattner542f1492004-02-28 21:28:10 +0000381 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
382 if (BI->isConditional() && BI->getCondition()->hasOneUse())
383 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
384 if ((SCI->getOpcode() == Instruction::SetEQ ||
385 SCI->getOpcode() == Instruction::SetNE) &&
386 isa<ConstantInt>(SCI->getOperand(1)))
387 return SCI->getOperand(0);
388 return 0;
389}
390
391// Given a value comparison instruction, decode all of the 'cases' that it
392// represents and return the 'default' block.
393static BasicBlock *
394GetValueEqualityComparisonCases(TerminatorInst *TI,
395 std::vector<std::pair<ConstantInt*,
396 BasicBlock*> > &Cases) {
397 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
398 Cases.reserve(SI->getNumCases());
399 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
400 Cases.push_back(std::make_pair(cast<ConstantInt>(SI->getCaseValue(i)),
401 SI->getSuccessor(i)));
402 return SI->getDefaultDest();
403 }
404
405 BranchInst *BI = cast<BranchInst>(TI);
406 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
407 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
408 BI->getSuccessor(SCI->getOpcode() ==
409 Instruction::SetNE)));
410 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
411}
412
413
414// FoldValueComparisonIntoPredecessors - The specified terminator is a value
415// equality comparison instruction (either a switch or a branch on "X == c").
416// See if any of the predecessors of the terminator block are value comparisons
417// on the same value. If so, and if safe to do so, fold them together.
418static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
419 BasicBlock *BB = TI->getParent();
420 Value *CV = isValueEqualityComparison(TI); // CondVal
421 assert(CV && "Not a comparison?");
422 bool Changed = false;
423
424 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
425 while (!Preds.empty()) {
426 BasicBlock *Pred = Preds.back();
427 Preds.pop_back();
428
429 // See if the predecessor is a comparison with the same value.
430 TerminatorInst *PTI = Pred->getTerminator();
431 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
432
433 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
434 // Figure out which 'cases' to copy from SI to PSI.
435 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
436 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
437
438 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
439 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
440
441 // Based on whether the default edge from PTI goes to BB or not, fill in
442 // PredCases and PredDefault with the new switch cases we would like to
443 // build.
444 std::vector<BasicBlock*> NewSuccessors;
445
446 if (PredDefault == BB) {
447 // If this is the default destination from PTI, only the edges in TI
448 // that don't occur in PTI, or that branch to BB will be activated.
449 std::set<ConstantInt*> PTIHandled;
450 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
451 if (PredCases[i].second != BB)
452 PTIHandled.insert(PredCases[i].first);
453 else {
454 // The default destination is BB, we don't need explicit targets.
455 std::swap(PredCases[i], PredCases.back());
456 PredCases.pop_back();
457 --i; --e;
458 }
459
460 // Reconstruct the new switch statement we will be building.
461 if (PredDefault != BBDefault) {
462 PredDefault->removePredecessor(Pred);
463 PredDefault = BBDefault;
464 NewSuccessors.push_back(BBDefault);
465 }
466 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
467 if (!PTIHandled.count(BBCases[i].first) &&
468 BBCases[i].second != BBDefault) {
469 PredCases.push_back(BBCases[i]);
470 NewSuccessors.push_back(BBCases[i].second);
471 }
472
473 } else {
474 // If this is not the default destination from PSI, only the edges
475 // in SI that occur in PSI with a destination of BB will be
476 // activated.
477 std::set<ConstantInt*> PTIHandled;
478 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
479 if (PredCases[i].second == BB) {
480 PTIHandled.insert(PredCases[i].first);
481 std::swap(PredCases[i], PredCases.back());
482 PredCases.pop_back();
483 --i; --e;
484 }
485
486 // Okay, now we know which constants were sent to BB from the
487 // predecessor. Figure out where they will all go now.
488 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
489 if (PTIHandled.count(BBCases[i].first)) {
490 // If this is one we are capable of getting...
491 PredCases.push_back(BBCases[i]);
492 NewSuccessors.push_back(BBCases[i].second);
493 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
494 }
495
496 // If there are any constants vectored to BB that TI doesn't handle,
497 // they must go to the default destination of TI.
498 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
499 E = PTIHandled.end(); I != E; ++I) {
500 PredCases.push_back(std::make_pair(*I, BBDefault));
501 NewSuccessors.push_back(BBDefault);
502 }
503 }
504
505 // Okay, at this point, we know which new successor Pred will get. Make
506 // sure we update the number of entries in the PHI nodes for these
507 // successors.
508 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
509 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
510
511 // Now that the successors are updated, create the new Switch instruction.
512 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PTI);
513 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
514 NewSI->addCase(PredCases[i].first, PredCases[i].second);
515 Pred->getInstList().erase(PTI);
516
517 // Okay, last check. If BB is still a successor of PSI, then we must
518 // have an infinite loop case. If so, add an infinitely looping block
519 // to handle the case to preserve the behavior of the code.
520 BasicBlock *InfLoopBlock = 0;
521 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
522 if (NewSI->getSuccessor(i) == BB) {
523 if (InfLoopBlock == 0) {
524 // Insert it at the end of the loop, because it's either code,
525 // or it won't matter if it's hot. :)
526 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
527 new BranchInst(InfLoopBlock, InfLoopBlock);
528 }
529 NewSI->setSuccessor(i, InfLoopBlock);
530 }
531
532 Changed = true;
533 }
534 }
535 return Changed;
536}
537
Chris Lattner1654cff2004-06-19 07:02:14 +0000538namespace {
539 /// ConstantIntOrdering - This class implements a stable ordering of constant
540 /// integers that does not depend on their address. This is important for
541 /// applications that sort ConstantInt's to ensure uniqueness.
542 struct ConstantIntOrdering {
543 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
544 return LHS->getRawValue() < RHS->getRawValue();
545 }
546 };
547}
548
Chris Lattner542f1492004-02-28 21:28:10 +0000549
Chris Lattner01d1ee32002-05-21 20:50:24 +0000550// SimplifyCFG - This function is used to do simplification of a CFG. For
551// example, it adjusts branches to branches to eliminate the extra hop, it
552// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +0000553// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000554//
555// WARNING: The entry node of a function may not be simplified.
556//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000557bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000558 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000559 Function *M = BB->getParent();
560
561 assert(BB && BB->getParent() && "Block not embedded in function!");
562 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +0000563 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +0000564
Chris Lattner01d1ee32002-05-21 20:50:24 +0000565 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000566 if (pred_begin(BB) == pred_end(BB) ||
567 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000568 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000569
570 // Loop through all of our successors and make sure they know that one
571 // of their predecessors is going away.
572 for_each(succ_begin(BB), succ_end(BB),
573 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
574
575 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000576 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000577 // If this instruction is used, replace uses with an arbitrary
578 // constant value. Because control flow can't get here, we don't care
579 // what we replace the value with. Note that since this block is
580 // unreachable, and all values contained within it must dominate their
581 // uses, that all uses will eventually be removed.
Chris Lattner18961502002-06-25 16:12:52 +0000582 if (!I.use_empty())
Chris Lattner01d1ee32002-05-21 20:50:24 +0000583 // Make all users of this instruction reference the constant instead
Chris Lattner18961502002-06-25 16:12:52 +0000584 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner01d1ee32002-05-21 20:50:24 +0000585
586 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000587 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000588 }
Chris Lattner18961502002-06-25 16:12:52 +0000589 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000590 return true;
591 }
592
Chris Lattner694e37f2003-08-17 19:41:53 +0000593 // Check to see if we can constant propagate this terminator instruction
594 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000595 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000596
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000597 // Check to see if this block has no non-phi instructions and only a single
598 // successor. If so, replace references to this basic block with references
599 // to the successor.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000600 succ_iterator SI(succ_begin(BB));
601 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000602
603 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
604 while (isa<PHINode>(*BBI)) ++BBI;
605
606 if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000607 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
608
609 if (Succ != BB) { // Arg, don't hurt infinite loops!
610 // If our successor has PHI nodes, then we need to update them to
611 // include entries for BB's predecessors, not for BB itself.
612 // Be careful though, if this transformation fails (returns true) then
613 // we cannot do this transformation!
614 //
Misha Brukmana3bbcb52002-10-29 23:06:16 +0000615 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000616 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
Chris Lattner18961502002-06-25 16:12:52 +0000617 std::string OldName = BB->getName();
618
Chris Lattner3a438372003-03-07 18:13:41 +0000619 std::vector<BasicBlock*>
620 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
621
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000622 // Move all PHI nodes in BB to Succ if they are alive, otherwise
623 // delete them.
624 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
625 if (PN->use_empty())
626 BB->getInstList().erase(BB->begin()); // Nuke instruction...
627 else {
628 // The instruction is alive, so this means that Succ must have
629 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner3a438372003-03-07 18:13:41 +0000630 // now. Simply move it into Succ, because we know that BB
631 // strictly dominated Succ.
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000632 BB->getInstList().remove(BB->begin());
633 Succ->getInstList().push_front(PN);
Chris Lattner3a438372003-03-07 18:13:41 +0000634
635 // We need to add new entries for the PHI node to account for
636 // predecessors of Succ that the PHI node does not take into
637 // account. At this point, since we know that BB dominated succ,
638 // this means that we should any newly added incoming edges should
639 // use the PHI node as the value for these edges, because they are
640 // loop back edges.
Chris Lattner3a438372003-03-07 18:13:41 +0000641 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
642 if (OldSuccPreds[i] != BB)
643 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattner46a5f1f2003-03-05 21:36:33 +0000644 }
645
Chris Lattner3a438372003-03-07 18:13:41 +0000646 // Everything that jumped to BB now goes to Succ...
647 BB->replaceAllUsesWith(Succ);
648
Chris Lattner18961502002-06-25 16:12:52 +0000649 // Delete the old basic block...
650 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000651
Chris Lattner18961502002-06-25 16:12:52 +0000652 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
653 Succ->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000654 return true;
655 }
656 }
657 }
658 }
659
Chris Lattner19831ec2004-02-16 06:35:48 +0000660 // If this is a returning block with only PHI nodes in it, fold the return
661 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +0000662 //
663 // If any predecessor is a conditional branch that just selects among
664 // different return values, fold the replace the branch/return with a select
665 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +0000666 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
667 BasicBlock::iterator BBI = BB->getTerminator();
668 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner147af6b2004-04-02 18:13:43 +0000669 // Find predecessors that end with branches.
Chris Lattner19831ec2004-02-16 06:35:48 +0000670 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner147af6b2004-04-02 18:13:43 +0000671 std::vector<BranchInst*> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +0000672 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
673 TerminatorInst *PTI = (*PI)->getTerminator();
674 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
675 if (BI->isUnconditional())
676 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +0000677 else
678 CondBranchPreds.push_back(BI);
Chris Lattner19831ec2004-02-16 06:35:48 +0000679 }
680
681 // If we found some, do the transformation!
682 if (!UncondBranchPreds.empty()) {
683 while (!UncondBranchPreds.empty()) {
684 BasicBlock *Pred = UncondBranchPreds.back();
685 UncondBranchPreds.pop_back();
686 Instruction *UncondBranch = Pred->getTerminator();
687 // Clone the return and add it to the end of the predecessor.
688 Instruction *NewRet = RI->clone();
689 Pred->getInstList().push_back(NewRet);
690
691 // If the return instruction returns a value, and if the value was a
692 // PHI node in "BB", propagate the right value into the return.
693 if (NewRet->getNumOperands() == 1)
694 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
695 if (PN->getParent() == BB)
696 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
697 // Update any PHI nodes in the returning block to realize that we no
698 // longer branch to them.
699 BB->removePredecessor(Pred);
700 Pred->getInstList().erase(UncondBranch);
701 }
702
703 // If we eliminated all predecessors of the block, delete the block now.
704 if (pred_begin(BB) == pred_end(BB))
705 // We know there are no successors, so just nuke the block.
706 M->getBasicBlockList().erase(BB);
707
Chris Lattner19831ec2004-02-16 06:35:48 +0000708 return true;
709 }
Chris Lattner147af6b2004-04-02 18:13:43 +0000710
711 // Check out all of the conditional branches going to this return
712 // instruction. If any of them just select between returns, change the
713 // branch itself into a select/return pair.
714 while (!CondBranchPreds.empty()) {
715 BranchInst *BI = CondBranchPreds.back();
716 CondBranchPreds.pop_back();
717 BasicBlock *TrueSucc = BI->getSuccessor(0);
718 BasicBlock *FalseSucc = BI->getSuccessor(1);
719 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
720
721 // Check to see if the non-BB successor is also a return block.
722 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
723 // Check to see if there are only PHI instructions in this block.
724 BasicBlock::iterator OSI = OtherSucc->getTerminator();
725 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
726 // Okay, we found a branch that is going to two return nodes. If
727 // there is no return value for this function, just change the
728 // branch into a return.
729 if (RI->getNumOperands() == 0) {
730 TrueSucc->removePredecessor(BI->getParent());
731 FalseSucc->removePredecessor(BI->getParent());
732 new ReturnInst(0, BI);
733 BI->getParent()->getInstList().erase(BI);
734 return true;
735 }
736
737 // Otherwise, figure out what the true and false return values are
738 // so we can insert a new select instruction.
739 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
740 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
741
742 // Unwrap any PHI nodes in the return blocks.
743 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
744 if (TVPN->getParent() == TrueSucc)
745 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
746 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
747 if (FVPN->getParent() == FalseSucc)
748 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
749
Chris Lattner7aa773b2004-04-02 18:15:10 +0000750 TrueSucc->removePredecessor(BI->getParent());
751 FalseSucc->removePredecessor(BI->getParent());
752
Chris Lattner147af6b2004-04-02 18:13:43 +0000753 // Insert a new select instruction.
754 Value *NewRetVal = new SelectInst(BI->getCondition(), TrueValue,
755 FalseValue, "retval", BI);
756 new ReturnInst(NewRetVal, BI);
757 BI->getParent()->getInstList().erase(BI);
758 return true;
759 }
760 }
761 }
Chris Lattner19831ec2004-02-16 06:35:48 +0000762 }
Chris Lattnere14ea082004-02-24 05:54:22 +0000763 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
764 // Check to see if the first instruction in this block is just an unwind.
765 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +0000766 // destination with call instructions, and any unconditional branch
767 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +0000768 //
769 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
770 while (!Preds.empty()) {
771 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +0000772 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
773 if (BI->isUnconditional()) {
774 Pred->getInstList().pop_back(); // nuke uncond branch
775 new UnwindInst(Pred); // Use unwind.
776 Changed = true;
777 }
778 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +0000779 if (II->getUnwindDest() == BB) {
780 // Insert a new branch instruction before the invoke, because this
781 // is now a fall through...
782 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
783 Pred->getInstList().remove(II); // Take out of symbol table
784
785 // Insert the call now...
786 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
787 CallInst *CI = new CallInst(II->getCalledValue(), Args,
788 II->getName(), BI);
789 // If the invoke produced a value, the Call now does instead
790 II->replaceAllUsesWith(CI);
791 delete II;
792 Changed = true;
793 }
794
795 Preds.pop_back();
796 }
Chris Lattner8e509dd2004-02-24 16:09:21 +0000797
798 // If this block is now dead, remove it.
799 if (pred_begin(BB) == pred_end(BB)) {
800 // We know there are no successors, so just nuke the block.
801 M->getBasicBlockList().erase(BB);
802 return true;
803 }
804
Chris Lattnerd52c2612004-02-24 07:23:58 +0000805 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
Chris Lattner7acd1cc2004-03-17 02:02:47 +0000806 if (isValueEqualityComparison(SI))
807 if (FoldValueComparisonIntoPredecessors(SI))
808 return SimplifyCFG(BB) || 1;
Chris Lattner542f1492004-02-28 21:28:10 +0000809 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner92da2c22004-05-01 22:36:37 +0000810 if (BI->isConditional()) {
Chris Lattnere67fa052004-05-01 23:35:43 +0000811 if (Value *CompVal = isValueEqualityComparison(BI)) {
812 // This block must be empty, except for the setcond inst, if it exists.
813 BasicBlock::iterator I = BB->begin();
814 if (&*I == BI ||
815 (&*I == cast<Instruction>(BI->getCondition()) &&
816 &*++I == BI))
817 if (FoldValueComparisonIntoPredecessors(BI))
818 return SimplifyCFG(BB) | true;
819 }
820
821 // If this basic block is ONLY a setcc and a branch, and if a predecessor
822 // branches to us and one of our successors, fold the setcc into the
823 // predecessor and use logical operations to pick the right destination.
Chris Lattner12fe2b12004-05-02 05:02:03 +0000824 BasicBlock *TrueDest = BI->getSuccessor(0);
825 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbdcc0b82004-05-02 05:19:36 +0000826 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattnere67fa052004-05-01 23:35:43 +0000827 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner12fe2b12004-05-02 05:02:03 +0000828 Cond->getNext() == BI && Cond->hasOneUse() &&
829 TrueDest != BB && FalseDest != BB)
Chris Lattnere67fa052004-05-01 23:35:43 +0000830 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
831 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnera1f79fb2004-05-02 01:00:44 +0000832 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000833 BasicBlock *PredBlock = *PI;
Chris Lattnere67fa052004-05-01 23:35:43 +0000834 if (PBI->getSuccessor(0) == FalseDest ||
835 PBI->getSuccessor(1) == TrueDest) {
836 // Invert the predecessors condition test (xor it with true),
837 // which allows us to write this code once.
838 Value *NewCond =
839 BinaryOperator::createNot(PBI->getCondition(),
840 PBI->getCondition()->getName()+".not", PBI);
841 PBI->setCondition(NewCond);
842 BasicBlock *OldTrue = PBI->getSuccessor(0);
843 BasicBlock *OldFalse = PBI->getSuccessor(1);
844 PBI->setSuccessor(0, OldFalse);
845 PBI->setSuccessor(1, OldTrue);
846 }
847
848 if (PBI->getSuccessor(0) == TrueDest ||
849 PBI->getSuccessor(1) == FalseDest) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000850 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattnere67fa052004-05-01 23:35:43 +0000851 // two conditions together.
852 Instruction *New = Cond->clone();
853 New->setName(Cond->getName());
854 Cond->setName(Cond->getName()+".old");
Chris Lattner2636c1b2004-06-21 07:19:01 +0000855 PredBlock->getInstList().insert(PBI, New);
Chris Lattnere67fa052004-05-01 23:35:43 +0000856 Instruction::BinaryOps Opcode =
857 PBI->getSuccessor(0) == TrueDest ?
858 Instruction::Or : Instruction::And;
859 Value *NewCond =
860 BinaryOperator::create(Opcode, PBI->getCondition(),
861 New, "bothcond", PBI);
862 PBI->setCondition(NewCond);
863 if (PBI->getSuccessor(0) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000864 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +0000865 PBI->setSuccessor(0, TrueDest);
866 }
867 if (PBI->getSuccessor(1) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +0000868 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +0000869 PBI->setSuccessor(1, FalseDest);
870 }
871 return SimplifyCFG(BB) | 1;
872 }
873 }
Chris Lattnere67fa052004-05-01 23:35:43 +0000874
Chris Lattner92da2c22004-05-01 22:36:37 +0000875 // If this block ends with a branch instruction, and if there is one
876 // predecessor, see if the previous block ended with a branch on the same
877 // condition, which makes this conditional branch redundant.
878 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
879 BasicBlock *OnlyPred = *PI++;
880 for (; PI != PE; ++PI)// Search all predecessors, see if they are all same
881 if (*PI != OnlyPred) {
882 OnlyPred = 0; // There are multiple different predecessors...
883 break;
884 }
885
886 if (OnlyPred)
887 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
888 if (PBI->isConditional() &&
889 PBI->getCondition() == BI->getCondition() &&
Chris Lattner951fdb92004-05-01 22:41:51 +0000890 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner92da2c22004-05-01 22:36:37 +0000891 // Okay, the outcome of this conditional branch is statically
892 // knowable. Delete the outgoing CFG edge that is impossible to
893 // execute.
894 bool CondIsTrue = PBI->getSuccessor(0) == BB;
895 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
896 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
897 BB->getInstList().erase(BI);
898 return SimplifyCFG(BB) | true;
899 }
Chris Lattnerd52c2612004-02-24 07:23:58 +0000900 }
Chris Lattner19831ec2004-02-16 06:35:48 +0000901 }
902
Chris Lattner01d1ee32002-05-21 20:50:24 +0000903 // Merge basic blocks into their predecessor if there is only one distinct
904 // pred, and if there is only one distinct successor of the predecessor, and
905 // if there are no PHI nodes.
906 //
Chris Lattner2355f942004-02-11 01:17:07 +0000907 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
908 BasicBlock *OnlyPred = *PI++;
909 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
910 if (*PI != OnlyPred) {
911 OnlyPred = 0; // There are multiple different predecessors...
912 break;
913 }
Chris Lattner92da2c22004-05-01 22:36:37 +0000914
Chris Lattner2355f942004-02-11 01:17:07 +0000915 BasicBlock *OnlySucc = 0;
916 if (OnlyPred && OnlyPred != BB && // Don't break self loops
917 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
918 // Check to see if there is only one distinct successor...
919 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
920 OnlySucc = BB;
921 for (; SI != SE; ++SI)
922 if (*SI != OnlySucc) {
923 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +0000924 break;
925 }
Chris Lattner2355f942004-02-11 01:17:07 +0000926 }
927
928 if (OnlySucc) {
Chris Lattner30b43442004-07-15 02:06:12 +0000929 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner2355f942004-02-11 01:17:07 +0000930 TerminatorInst *Term = OnlyPred->getTerminator();
931
932 // Resolve any PHI nodes at the start of the block. They are all
933 // guaranteed to have exactly one entry if they exist, unless there are
934 // multiple duplicate (but guaranteed to be equal) entries for the
935 // incoming edges. This occurs when there are multiple edges from
936 // OnlyPred to OnlySucc.
937 //
938 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
939 PN->replaceAllUsesWith(PN->getIncomingValue(0));
940 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner01d1ee32002-05-21 20:50:24 +0000941 }
942
Chris Lattner2355f942004-02-11 01:17:07 +0000943 // Delete the unconditional branch from the predecessor...
944 OnlyPred->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000945
Chris Lattner2355f942004-02-11 01:17:07 +0000946 // Move all definitions in the successor to the predecessor...
947 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattner18961502002-06-25 16:12:52 +0000948
Chris Lattner2355f942004-02-11 01:17:07 +0000949 // Make all PHI nodes that referred to BB now refer to Pred as their
950 // source...
951 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +0000952
Chris Lattner2355f942004-02-11 01:17:07 +0000953 std::string OldName = BB->getName();
Chris Lattner18961502002-06-25 16:12:52 +0000954
Chris Lattner2355f942004-02-11 01:17:07 +0000955 // Erase basic block from the function...
956 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +0000957
Chris Lattner2355f942004-02-11 01:17:07 +0000958 // Inherit predecessors name if it exists...
959 if (!OldName.empty() && !OnlyPred->hasName())
960 OnlyPred->setName(OldName);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000961
Chris Lattner2355f942004-02-11 01:17:07 +0000962 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000963 }
Chris Lattner723c66d2004-02-11 03:36:04 +0000964
Chris Lattner0d560082004-02-24 05:38:11 +0000965 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
966 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
967 // Change br (X == 0 | X == 1), T, F into a switch instruction.
968 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
969 Instruction *Cond = cast<Instruction>(BI->getCondition());
970 // If this is a bunch of seteq's or'd together, or if it's a bunch of
971 // 'setne's and'ed together, collect them.
972 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +0000973 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +0000974 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
975 if (CompVal && CompVal->getType()->isInteger()) {
976 // There might be duplicate constants in the list, which the switch
977 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +0000978 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +0000979 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
980
981 // Figure out which block is which destination.
982 BasicBlock *DefaultBB = BI->getSuccessor(1);
983 BasicBlock *EdgeBB = BI->getSuccessor(0);
984 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
985
986 // Create the new switch instruction now.
987 SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
988
989 // Add all of the 'cases' to the switch instruction.
990 for (unsigned i = 0, e = Values.size(); i != e; ++i)
991 New->addCase(Values[i], EdgeBB);
992
993 // We added edges from PI to the EdgeBB. As such, if there were any
994 // PHI nodes in EdgeBB, they need entries to be added corresponding to
995 // the number of edges added.
996 for (BasicBlock::iterator BBI = EdgeBB->begin();
997 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
998 Value *InVal = PN->getIncomingValueForBlock(*PI);
999 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1000 PN->addIncoming(InVal, *PI);
1001 }
1002
1003 // Erase the old branch instruction.
1004 (*PI)->getInstList().erase(BI);
1005
1006 // Erase the potentially condition tree that was used to computed the
1007 // branch condition.
1008 ErasePossiblyDeadInstructionTree(Cond);
1009 return true;
1010 }
1011 }
1012
Chris Lattner723c66d2004-02-11 03:36:04 +00001013 // If there is a trivial two-entry PHI node in this basic block, and we can
1014 // eliminate it, do so now.
1015 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1016 if (PN->getNumIncomingValues() == 2) {
1017 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1018 // statement", which has a very simple dominance structure. Basically, we
1019 // are trying to find the condition that is being branched on, which
1020 // subsequently causes this merge to happen. We really want control
1021 // dependence information for this check, but simplifycfg can't keep it up
1022 // to date, and this catches most of the cases we care about anyway.
1023 //
1024 BasicBlock *IfTrue, *IfFalse;
1025 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner218a8222004-06-20 01:13:18 +00001026 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1027 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner723c66d2004-02-11 03:36:04 +00001028
1029 // Figure out where to insert instructions as necessary.
1030 BasicBlock::iterator AfterPHIIt = BB->begin();
1031 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
1032
1033 BasicBlock::iterator I = BB->begin();
1034 while (PHINode *PN = dyn_cast<PHINode>(I)) {
1035 ++I;
1036
1037 // If we can eliminate this PHI by directly computing it based on the
1038 // condition, do so now. We can't eliminate PHI nodes where the
1039 // incoming values are defined in the conditional parts of the branch,
1040 // so check for this.
1041 //
Chris Lattner570751c2004-04-09 22:50:22 +00001042 if (DominatesMergePoint(PN->getIncomingValue(0), BB, true) &&
1043 DominatesMergePoint(PN->getIncomingValue(1), BB, true)) {
Chris Lattner723c66d2004-02-11 03:36:04 +00001044 Value *TrueVal =
1045 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1046 Value *FalseVal =
1047 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1048
Chris Lattner570751c2004-04-09 22:50:22 +00001049 // If one of the incoming values is defined in the conditional
1050 // region, move it into it's predecessor block, which we know is
1051 // safe.
1052 if (!DominatesMergePoint(TrueVal, BB, false)) {
1053 Instruction *TrueI = cast<Instruction>(TrueVal);
1054 BasicBlock *OldBB = TrueI->getParent();
1055 OldBB->getInstList().remove(TrueI);
1056 BasicBlock *NewBB = *pred_begin(OldBB);
1057 NewBB->getInstList().insert(NewBB->getTerminator(), TrueI);
1058 }
1059 if (!DominatesMergePoint(FalseVal, BB, false)) {
1060 Instruction *FalseI = cast<Instruction>(FalseVal);
1061 BasicBlock *OldBB = FalseI->getParent();
1062 OldBB->getInstList().remove(FalseI);
1063 BasicBlock *NewBB = *pred_begin(OldBB);
1064 NewBB->getInstList().insert(NewBB->getTerminator(), FalseI);
1065 }
1066
Chris Lattner552112f2004-03-30 19:44:05 +00001067 // Change the PHI node into a select instruction.
1068 BasicBlock::iterator InsertPos = PN;
1069 while (isa<PHINode>(InsertPos)) ++InsertPos;
1070
1071 std::string Name = PN->getName(); PN->setName("");
1072 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1073 Name, InsertPos));
1074 BB->getInstList().erase(PN);
1075 Changed = true;
Chris Lattner723c66d2004-02-11 03:36:04 +00001076 }
1077 }
1078 }
1079 }
Chris Lattner01d1ee32002-05-21 20:50:24 +00001080
Chris Lattner694e37f2003-08-17 19:41:53 +00001081 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001082}