blob: abe229d7edcf473a9f8f637a131e3d4d8bfb7d16 [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner9734fd02004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner466a0492002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner18d1f192004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Chris Lattner6f4b45a2004-02-24 05:38:11 +000018#include "llvm/Type.h"
Chris Lattner466a0492002-05-21 20:50:24 +000019#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/Support/Debug.h"
Chris Lattner466a0492002-05-21 20:50:24 +000021#include <algorithm>
22#include <functional>
Chris Lattnera2ab4892004-02-24 07:23:58 +000023#include <set>
Chris Lattner5edb2f32004-10-18 04:07:22 +000024#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000026
Chris Lattner76dc2042005-08-03 00:19:45 +000027/// SafeToMergeTerminators - Return true if it is safe to merge these two
28/// terminator instructions together.
29///
30static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
31 if (SI1 == SI2) return false; // Can't merge with self!
32
33 // It is not safe to merge these two switch instructions if they have a common
34 // successor, and if that successor has a PHI node, and if *that* PHI node has
35 // conflicting incoming values from the two switch blocks.
36 BasicBlock *SI1BB = SI1->getParent();
37 BasicBlock *SI2BB = SI2->getParent();
38 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
39
40 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
41 if (SI1Succs.count(*I))
42 for (BasicBlock::iterator BBI = (*I)->begin();
43 isa<PHINode>(BBI); ++BBI) {
44 PHINode *PN = cast<PHINode>(BBI);
45 if (PN->getIncomingValueForBlock(SI1BB) !=
46 PN->getIncomingValueForBlock(SI2BB))
47 return false;
48 }
49
50 return true;
51}
52
53/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
54/// now be entries in it from the 'NewPred' block. The values that will be
55/// flowing into the PHI nodes will be the same as those coming in from
56/// ExistPred, an existing predecessor of Succ.
57static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
58 BasicBlock *ExistPred) {
59 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
60 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
61 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
62
63 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
64 PHINode *PN = cast<PHINode>(I);
65 Value *V = PN->getIncomingValueForBlock(ExistPred);
66 PN->addIncoming(V, NewPred);
67 }
68}
69
Chris Lattner982b75c2005-08-03 00:29:26 +000070// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
71// almost-empty BB ending in an unconditional branch to Succ, into succ.
Chris Lattner466a0492002-05-21 20:50:24 +000072//
73// Assumption: Succ is the single successor for BB.
74//
Chris Lattner982b75c2005-08-03 00:29:26 +000075static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000076 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000077
78 if (!isa<PHINode>(Succ->front()))
Chris Lattner982b75c2005-08-03 00:29:26 +000079 return true; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000080
81 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000082 // Succ. If so, we cannot do the transformation if there are any PHI nodes
83 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000084 //
Chris Lattner76dc2042005-08-03 00:19:45 +000085 if (!SafeToMergeTerminators(BB->getTerminator(), Succ->getTerminator()))
Chris Lattner982b75c2005-08-03 00:29:26 +000086 return false; // Cannot merge.
Chris Lattner466a0492002-05-21 20:50:24 +000087
Chris Lattner982b75c2005-08-03 00:29:26 +000088 return true;
Chris Lattner466a0492002-05-21 20:50:24 +000089}
90
Chris Lattner733d6702005-08-03 00:11:16 +000091/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
92/// branch to Succ, and contains no instructions other than PHI nodes and the
93/// branch. If possible, eliminate BB.
94static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
95 BasicBlock *Succ) {
96 // If our successor has PHI nodes, then we need to update them to include
97 // entries for BB's predecessors, not for BB itself. Be careful though,
98 // if this transformation fails (returns true) then we cannot do this
99 // transformation!
100 //
Chris Lattner982b75c2005-08-03 00:29:26 +0000101 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner733d6702005-08-03 00:11:16 +0000102
103 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
104
Chris Lattner982b75c2005-08-03 00:29:26 +0000105 if (isa<PHINode>(Succ->begin())) {
106 // If there is more than one pred of succ, and there are PHI nodes in
107 // the successor, then we need to add incoming edges for the PHI nodes
108 //
109 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
110
111 // Loop over all of the PHI nodes in the successor of BB.
112 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
113 PHINode *PN = cast<PHINode>(I);
114 Value *OldVal = PN->removeIncomingValue(BB, false);
115 assert(OldVal && "No entry in PHI for Pred BB!");
116
117 // If this incoming value is one of the PHI nodes in BB, the new entries in
118 // the PHI node are the entries from the old PHI.
119 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
120 PHINode *OldValPN = cast<PHINode>(OldVal);
121 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
122 PN->addIncoming(OldValPN->getIncomingValue(i),
123 OldValPN->getIncomingBlock(i));
124 } else {
125 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
126 End = BBPreds.end(); PredI != End; ++PredI) {
127 // Add an incoming value for each of the new incoming values...
128 PN->addIncoming(OldVal, *PredI);
129 }
130 }
131 }
132 }
133
Chris Lattner733d6702005-08-03 00:11:16 +0000134 if (isa<PHINode>(&BB->front())) {
135 std::vector<BasicBlock*>
136 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
137
138 // Move all PHI nodes in BB to Succ if they are alive, otherwise
139 // delete them.
140 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
141 if (PN->use_empty() /*|| Succ->getSinglePredecessor() == 0*/) {
142 // We can only move the PHI node into Succ if BB dominates Succ.
143 // Since BB only has a single successor (Succ), the PHI nodes
144 // will dominate Succ, unless Succ has multiple predecessors. In
145 // this case, the PHIs are either dead, or have references in dead
146 // blocks. In either case, we can just remove them.
147 if (!PN->use_empty()) // Uses in dead block?
148 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
149 PN->eraseFromParent(); // Nuke instruction.
150 } else {
151 // The instruction is alive, so this means that Succ must have
152 // *ONLY* had BB as a predecessor, and the PHI node is still valid
153 // now. Simply move it into Succ, because we know that BB
154 // strictly dominated Succ.
Chris Lattner1f047fd2005-08-03 00:23:42 +0000155 Succ->getInstList().splice(Succ->begin(),
156 BB->getInstList(), BB->begin());
Chris Lattner733d6702005-08-03 00:11:16 +0000157
158 // We need to add new entries for the PHI node to account for
159 // predecessors of Succ that the PHI node does not take into
160 // account. At this point, since we know that BB dominated succ,
161 // this means that we should any newly added incoming edges should
162 // use the PHI node as the value for these edges, because they are
163 // loop back edges.
164 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
165 if (OldSuccPreds[i] != BB)
166 PN->addIncoming(PN, OldSuccPreds[i]);
167 }
168 }
169
170 // Everything that jumped to BB now goes to Succ.
171 std::string OldName = BB->getName();
172 BB->replaceAllUsesWith(Succ);
173 BB->eraseFromParent(); // Delete the old basic block.
174
175 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
176 Succ->setName(OldName);
177 return true;
178}
179
Chris Lattner18d1f192004-02-11 03:36:04 +0000180/// GetIfCondition - Given a basic block (BB) with two predecessors (and
181/// presumably PHI nodes in it), check to see if the merge at this block is due
182/// to an "if condition". If so, return the boolean condition that determines
183/// which entry into BB will be taken. Also, return by references the block
184/// that will be entered from if the condition is true, and the block that will
185/// be entered if the condition is false.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000186///
Chris Lattner18d1f192004-02-11 03:36:04 +0000187///
188static Value *GetIfCondition(BasicBlock *BB,
189 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
190 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
191 "Function can only handle blocks with 2 predecessors!");
192 BasicBlock *Pred1 = *pred_begin(BB);
193 BasicBlock *Pred2 = *++pred_begin(BB);
194
195 // We can only handle branches. Other control flow will be lowered to
196 // branches if possible anyway.
197 if (!isa<BranchInst>(Pred1->getTerminator()) ||
198 !isa<BranchInst>(Pred2->getTerminator()))
199 return 0;
200 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
201 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
202
203 // Eliminate code duplication by ensuring that Pred1Br is conditional if
204 // either are.
205 if (Pred2Br->isConditional()) {
206 // If both branches are conditional, we don't have an "if statement". In
207 // reality, we could transform this case, but since the condition will be
208 // required anyway, we stand no chance of eliminating it, so the xform is
209 // probably not profitable.
210 if (Pred1Br->isConditional())
211 return 0;
212
213 std::swap(Pred1, Pred2);
214 std::swap(Pred1Br, Pred2Br);
215 }
216
217 if (Pred1Br->isConditional()) {
218 // If we found a conditional branch predecessor, make sure that it branches
219 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
220 if (Pred1Br->getSuccessor(0) == BB &&
221 Pred1Br->getSuccessor(1) == Pred2) {
222 IfTrue = Pred1;
223 IfFalse = Pred2;
224 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
225 Pred1Br->getSuccessor(1) == BB) {
226 IfTrue = Pred2;
227 IfFalse = Pred1;
228 } else {
229 // We know that one arm of the conditional goes to BB, so the other must
230 // go somewhere unrelated, and this must not be an "if statement".
231 return 0;
232 }
233
234 // The only thing we have to watch out for here is to make sure that Pred2
235 // doesn't have incoming edges from other blocks. If it does, the condition
236 // doesn't dominate BB.
237 if (++pred_begin(Pred2) != pred_end(Pred2))
238 return 0;
239
240 return Pred1Br->getCondition();
241 }
242
243 // Ok, if we got here, both predecessors end with an unconditional branch to
244 // BB. Don't panic! If both blocks only have a single (identical)
245 // predecessor, and THAT is a conditional branch, then we're all ok!
246 if (pred_begin(Pred1) == pred_end(Pred1) ||
247 ++pred_begin(Pred1) != pred_end(Pred1) ||
248 pred_begin(Pred2) == pred_end(Pred2) ||
249 ++pred_begin(Pred2) != pred_end(Pred2) ||
250 *pred_begin(Pred1) != *pred_begin(Pred2))
251 return 0;
252
253 // Otherwise, if this is a conditional branch, then we can use it!
254 BasicBlock *CommonPred = *pred_begin(Pred1);
255 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
256 assert(BI->isConditional() && "Two successors but not conditional?");
257 if (BI->getSuccessor(0) == Pred1) {
258 IfTrue = Pred1;
259 IfFalse = Pred2;
260 } else {
261 IfTrue = Pred2;
262 IfFalse = Pred1;
263 }
264 return BI->getCondition();
265 }
266 return 0;
267}
268
269
270// If we have a merge point of an "if condition" as accepted above, return true
271// if the specified value dominates the block. We don't handle the true
272// generality of domination here, just a special case which works well enough
273// for us.
Chris Lattner45c35b12004-10-14 05:13:36 +0000274//
275// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
276// see if V (which must be an instruction) is cheap to compute and is
277// non-trapping. If both are true, the instruction is inserted into the set and
278// true is returned.
279static bool DominatesMergePoint(Value *V, BasicBlock *BB,
280 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000281 Instruction *I = dyn_cast<Instruction>(V);
282 if (!I) return true; // Non-instructions all dominate instructions.
283 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000284
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000285 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000286 // the bottom of this block.
287 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000288
Chris Lattner0aa56562004-04-09 22:50:22 +0000289 // If this instruction is defined in a block that contains an unconditional
290 // branch to BB, then it must be in the 'conditional' part of the "if
291 // statement".
292 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
293 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner45c35b12004-10-14 05:13:36 +0000294 if (!AggressiveInsts) return false;
Chris Lattner0aa56562004-04-09 22:50:22 +0000295 // Okay, it looks like the instruction IS in the "condition". Check to
296 // see if its a cheap instruction to unconditionally compute, and if it
297 // only uses stuff defined outside of the condition. If so, hoist it out.
298 switch (I->getOpcode()) {
299 default: return false; // Cannot hoist this out safely.
300 case Instruction::Load:
301 // We can hoist loads that are non-volatile and obviously cannot trap.
302 if (cast<LoadInst>(I)->isVolatile())
303 return false;
304 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spenceref784f02004-07-18 00:32:14 +0000305 !isa<Constant>(I->getOperand(0)))
Chris Lattner0aa56562004-04-09 22:50:22 +0000306 return false;
307
308 // Finally, we have to check to make sure there are no instructions
309 // before the load in its basic block, as we are going to hoist the loop
310 // out to its predecessor.
311 if (PBB->begin() != BasicBlock::iterator(I))
312 return false;
313 break;
314 case Instruction::Add:
315 case Instruction::Sub:
316 case Instruction::And:
317 case Instruction::Or:
318 case Instruction::Xor:
319 case Instruction::Shl:
320 case Instruction::Shr:
Chris Lattnerb38b4432005-04-21 05:31:13 +0000321 case Instruction::SetEQ:
322 case Instruction::SetNE:
323 case Instruction::SetLT:
324 case Instruction::SetGT:
325 case Instruction::SetLE:
326 case Instruction::SetGE:
Chris Lattner0aa56562004-04-09 22:50:22 +0000327 break; // These are all cheap and non-trapping instructions.
328 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000329
Chris Lattner0aa56562004-04-09 22:50:22 +0000330 // Okay, we can only really hoist these out if their operands are not
331 // defined in the conditional region.
332 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner45c35b12004-10-14 05:13:36 +0000333 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner0aa56562004-04-09 22:50:22 +0000334 return false;
Chris Lattner45c35b12004-10-14 05:13:36 +0000335 // Okay, it's safe to do this! Remember this instruction.
336 AggressiveInsts->insert(I);
Chris Lattner0aa56562004-04-09 22:50:22 +0000337 }
338
Chris Lattner18d1f192004-02-11 03:36:04 +0000339 return true;
340}
Chris Lattner466a0492002-05-21 20:50:24 +0000341
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000342// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
343// instructions that compare a value against a constant, return the value being
344// compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000345static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000346 if (Instruction *Inst = dyn_cast<Instruction>(V))
347 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000348 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000349 Values.push_back(C);
350 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000351 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000352 Values.push_back(C);
353 return Inst->getOperand(1);
354 }
355 } else if (Inst->getOpcode() == Instruction::Or) {
356 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
357 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
358 if (LHS == RHS)
359 return LHS;
360 }
361 return 0;
362}
363
364// GatherConstantSetNEs - Given a potentially 'and'd together collection of
365// setne instructions that compare a value against a constant, return the value
366// being compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000367static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000368 if (Instruction *Inst = dyn_cast<Instruction>(V))
369 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000370 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000371 Values.push_back(C);
372 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000373 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000374 Values.push_back(C);
375 return Inst->getOperand(1);
376 }
377 } else if (Inst->getOpcode() == Instruction::Cast) {
378 // Cast of X to bool is really a comparison against zero.
379 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000380 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000381 return Inst->getOperand(0);
382 } else if (Inst->getOpcode() == Instruction::And) {
383 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
384 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
385 if (LHS == RHS)
386 return LHS;
387 }
388 return 0;
389}
390
391
392
393/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
394/// bunch of comparisons of one value against constants, return the value and
395/// the constants being compared.
396static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000397 std::vector<ConstantInt*> &Values) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000398 if (Cond->getOpcode() == Instruction::Or) {
399 CompVal = GatherConstantSetEQs(Cond, Values);
400
401 // Return true to indicate that the condition is true if the CompVal is
402 // equal to one of the constants.
403 return true;
404 } else if (Cond->getOpcode() == Instruction::And) {
405 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000406
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000407 // Return false to indicate that the condition is false if the CompVal is
408 // equal to one of the constants.
409 return false;
410 }
411 return false;
412}
413
414/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
415/// has no side effects, nuke it. If it uses any instructions that become dead
416/// because the instruction is now gone, nuke them too.
417static void ErasePossiblyDeadInstructionTree(Instruction *I) {
418 if (isInstructionTriviallyDead(I)) {
419 std::vector<Value*> Operands(I->op_begin(), I->op_end());
420 I->getParent()->getInstList().erase(I);
421 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
422 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
423 ErasePossiblyDeadInstructionTree(OpI);
424 }
425}
426
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000427// isValueEqualityComparison - Return true if the specified terminator checks to
428// see if a value is equal to constant integer value.
429static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattnera64923a2004-03-16 19:45:22 +0000430 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
431 // Do not permit merging of large switch instructions into their
432 // predecessors unless there is only one predecessor.
433 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
434 pred_end(SI->getParent())) > 128)
435 return 0;
436
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000437 return SI->getCondition();
Chris Lattnera64923a2004-03-16 19:45:22 +0000438 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000439 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
440 if (BI->isConditional() && BI->getCondition()->hasOneUse())
441 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
442 if ((SCI->getOpcode() == Instruction::SetEQ ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000443 SCI->getOpcode() == Instruction::SetNE) &&
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000444 isa<ConstantInt>(SCI->getOperand(1)))
445 return SCI->getOperand(0);
446 return 0;
447}
448
449// Given a value comparison instruction, decode all of the 'cases' that it
450// represents and return the 'default' block.
451static BasicBlock *
Misha Brukmanb1c93172005-04-21 23:48:37 +0000452GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000453 std::vector<std::pair<ConstantInt*,
454 BasicBlock*> > &Cases) {
455 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
456 Cases.reserve(SI->getNumCases());
457 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnercc6d75f2005-02-26 18:33:28 +0000458 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000459 return SI->getDefaultDest();
460 }
461
462 BranchInst *BI = cast<BranchInst>(TI);
463 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
464 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
465 BI->getSuccessor(SCI->getOpcode() ==
466 Instruction::SetNE)));
467 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
468}
469
470
Chris Lattner1cca9592005-02-24 06:17:52 +0000471// EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
472// in the list that match the specified block.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000473static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner1cca9592005-02-24 06:17:52 +0000474 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
475 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
476 if (Cases[i].second == BB) {
477 Cases.erase(Cases.begin()+i);
478 --i; --e;
479 }
480}
481
482// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
483// well.
484static bool
485ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
486 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
487 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
488
489 // Make V1 be smaller than V2.
490 if (V1->size() > V2->size())
491 std::swap(V1, V2);
492
493 if (V1->size() == 0) return false;
494 if (V1->size() == 1) {
495 // Just scan V2.
496 ConstantInt *TheVal = (*V1)[0].first;
497 for (unsigned i = 0, e = V2->size(); i != e; ++i)
498 if (TheVal == (*V2)[i].first)
499 return true;
500 }
501
502 // Otherwise, just sort both lists and compare element by element.
503 std::sort(V1->begin(), V1->end());
504 std::sort(V2->begin(), V2->end());
505 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
506 while (i1 != e1 && i2 != e2) {
507 if ((*V1)[i1].first == (*V2)[i2].first)
508 return true;
509 if ((*V1)[i1].first < (*V2)[i2].first)
510 ++i1;
511 else
512 ++i2;
513 }
514 return false;
515}
516
517// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
518// terminator instruction and its block is known to only have a single
519// predecessor block, check to see if that predecessor is also a value
520// comparison with the same value, and if that comparison determines the outcome
521// of this comparison. If so, simplify TI. This does a very limited form of
522// jump threading.
523static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
524 BasicBlock *Pred) {
525 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
526 if (!PredVal) return false; // Not a value comparison in predecessor.
527
528 Value *ThisVal = isValueEqualityComparison(TI);
529 assert(ThisVal && "This isn't a value comparison!!");
530 if (ThisVal != PredVal) return false; // Different predicates.
531
532 // Find out information about when control will move from Pred to TI's block.
533 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
534 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
535 PredCases);
536 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000537
Chris Lattner1cca9592005-02-24 06:17:52 +0000538 // Find information about how control leaves this block.
539 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
540 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
541 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
542
543 // If TI's block is the default block from Pred's comparison, potentially
544 // simplify TI based on this knowledge.
545 if (PredDef == TI->getParent()) {
546 // If we are here, we know that the value is none of those cases listed in
547 // PredCases. If there are any cases in ThisCases that are in PredCases, we
548 // can simplify TI.
549 if (ValuesOverlap(PredCases, ThisCases)) {
550 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
551 // Okay, one of the successors of this condbr is dead. Convert it to a
552 // uncond br.
553 assert(ThisCases.size() == 1 && "Branch can only have one case!");
554 Value *Cond = BTI->getCondition();
555 // Insert the new branch.
556 Instruction *NI = new BranchInst(ThisDef, TI);
557
558 // Remove PHI node entries for the dead edge.
559 ThisCases[0].second->removePredecessor(TI->getParent());
560
561 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
562 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
563
564 TI->eraseFromParent(); // Nuke the old one.
565 // If condition is now dead, nuke it.
566 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
567 ErasePossiblyDeadInstructionTree(CondI);
568 return true;
569
570 } else {
571 SwitchInst *SI = cast<SwitchInst>(TI);
572 // Okay, TI has cases that are statically dead, prune them away.
573 std::set<Constant*> DeadCases;
574 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
575 DeadCases.insert(PredCases[i].first);
576
577 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
578 << "Through successor TI: " << *TI);
579
580 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
581 if (DeadCases.count(SI->getCaseValue(i))) {
582 SI->getSuccessor(i)->removePredecessor(TI->getParent());
583 SI->removeCase(i);
584 }
585
586 DEBUG(std::cerr << "Leaving: " << *TI << "\n");
587 return true;
588 }
589 }
590
591 } else {
592 // Otherwise, TI's block must correspond to some matched value. Find out
593 // which value (or set of values) this is.
594 ConstantInt *TIV = 0;
595 BasicBlock *TIBB = TI->getParent();
596 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
597 if (PredCases[i].second == TIBB)
598 if (TIV == 0)
599 TIV = PredCases[i].first;
600 else
601 return false; // Cannot handle multiple values coming to this block.
602 assert(TIV && "No edge from pred to succ?");
603
604 // Okay, we found the one constant that our value can be if we get into TI's
605 // BB. Find out which successor will unconditionally be branched to.
606 BasicBlock *TheRealDest = 0;
607 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
608 if (ThisCases[i].first == TIV) {
609 TheRealDest = ThisCases[i].second;
610 break;
611 }
612
613 // If not handled by any explicit cases, it is handled by the default case.
614 if (TheRealDest == 0) TheRealDest = ThisDef;
615
616 // Remove PHI node entries for dead edges.
617 BasicBlock *CheckEdge = TheRealDest;
618 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
619 if (*SI != CheckEdge)
620 (*SI)->removePredecessor(TIBB);
621 else
622 CheckEdge = 0;
623
624 // Insert the new branch.
625 Instruction *NI = new BranchInst(TheRealDest, TI);
626
627 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
628 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
629 Instruction *Cond = 0;
630 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
631 Cond = dyn_cast<Instruction>(BI->getCondition());
632 TI->eraseFromParent(); // Nuke the old one.
633
634 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
635 return true;
636 }
637 return false;
638}
639
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000640// FoldValueComparisonIntoPredecessors - The specified terminator is a value
641// equality comparison instruction (either a switch or a branch on "X == c").
642// See if any of the predecessors of the terminator block are value comparisons
643// on the same value. If so, and if safe to do so, fold them together.
644static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
645 BasicBlock *BB = TI->getParent();
646 Value *CV = isValueEqualityComparison(TI); // CondVal
647 assert(CV && "Not a comparison?");
648 bool Changed = false;
649
650 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
651 while (!Preds.empty()) {
652 BasicBlock *Pred = Preds.back();
653 Preds.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000654
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000655 // See if the predecessor is a comparison with the same value.
656 TerminatorInst *PTI = Pred->getTerminator();
657 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
658
659 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
660 // Figure out which 'cases' to copy from SI to PSI.
661 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
662 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
663
664 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
665 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
666
667 // Based on whether the default edge from PTI goes to BB or not, fill in
668 // PredCases and PredDefault with the new switch cases we would like to
669 // build.
670 std::vector<BasicBlock*> NewSuccessors;
671
672 if (PredDefault == BB) {
673 // If this is the default destination from PTI, only the edges in TI
674 // that don't occur in PTI, or that branch to BB will be activated.
675 std::set<ConstantInt*> PTIHandled;
676 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
677 if (PredCases[i].second != BB)
678 PTIHandled.insert(PredCases[i].first);
679 else {
680 // The default destination is BB, we don't need explicit targets.
681 std::swap(PredCases[i], PredCases.back());
682 PredCases.pop_back();
683 --i; --e;
684 }
685
686 // Reconstruct the new switch statement we will be building.
687 if (PredDefault != BBDefault) {
688 PredDefault->removePredecessor(Pred);
689 PredDefault = BBDefault;
690 NewSuccessors.push_back(BBDefault);
691 }
692 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
693 if (!PTIHandled.count(BBCases[i].first) &&
694 BBCases[i].second != BBDefault) {
695 PredCases.push_back(BBCases[i]);
696 NewSuccessors.push_back(BBCases[i].second);
697 }
698
699 } else {
700 // If this is not the default destination from PSI, only the edges
701 // in SI that occur in PSI with a destination of BB will be
702 // activated.
703 std::set<ConstantInt*> PTIHandled;
704 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
705 if (PredCases[i].second == BB) {
706 PTIHandled.insert(PredCases[i].first);
707 std::swap(PredCases[i], PredCases.back());
708 PredCases.pop_back();
709 --i; --e;
710 }
711
712 // Okay, now we know which constants were sent to BB from the
713 // predecessor. Figure out where they will all go now.
714 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
715 if (PTIHandled.count(BBCases[i].first)) {
716 // If this is one we are capable of getting...
717 PredCases.push_back(BBCases[i]);
718 NewSuccessors.push_back(BBCases[i].second);
719 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
720 }
721
722 // If there are any constants vectored to BB that TI doesn't handle,
723 // they must go to the default destination of TI.
724 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
725 E = PTIHandled.end(); I != E; ++I) {
726 PredCases.push_back(std::make_pair(*I, BBDefault));
727 NewSuccessors.push_back(BBDefault);
728 }
729 }
730
731 // Okay, at this point, we know which new successor Pred will get. Make
732 // sure we update the number of entries in the PHI nodes for these
733 // successors.
734 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
735 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
736
737 // Now that the successors are updated, create the new Switch instruction.
Chris Lattnera35dfce2005-01-29 00:38:26 +0000738 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000739 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
740 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner3215bb62005-01-01 16:02:12 +0000741
742 Instruction *DeadCond = 0;
743 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
744 // If PTI is a branch, remember the condition.
745 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000746 Pred->getInstList().erase(PTI);
747
Chris Lattner3215bb62005-01-01 16:02:12 +0000748 // If the condition is dead now, remove the instruction tree.
749 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
750
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000751 // Okay, last check. If BB is still a successor of PSI, then we must
752 // have an infinite loop case. If so, add an infinitely looping block
753 // to handle the case to preserve the behavior of the code.
754 BasicBlock *InfLoopBlock = 0;
755 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
756 if (NewSI->getSuccessor(i) == BB) {
757 if (InfLoopBlock == 0) {
758 // Insert it at the end of the loop, because it's either code,
759 // or it won't matter if it's hot. :)
760 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
761 new BranchInst(InfLoopBlock, InfLoopBlock);
762 }
763 NewSI->setSuccessor(i, InfLoopBlock);
764 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000765
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000766 Changed = true;
767 }
768 }
769 return Changed;
770}
771
Chris Lattner389cfac2004-11-30 00:29:14 +0000772/// HoistThenElseCodeToIf - Given a conditional branch that codes to BB1 and
773/// BB2, hoist any common code in the two blocks up into the branch block. The
774/// caller of this function guarantees that BI's block dominates BB1 and BB2.
775static bool HoistThenElseCodeToIf(BranchInst *BI) {
776 // This does very trivial matching, with limited scanning, to find identical
777 // instructions in the two blocks. In particular, we don't want to get into
778 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
779 // such, we currently just scan for obviously identical instructions in an
780 // identical order.
781 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
782 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
783
784 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
785 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2))
786 return false;
787
788 // If we get here, we can hoist at least one instruction.
789 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +0000790
791 do {
792 // If we are hoisting the terminator instruction, don't move one (making a
793 // broken BB), instead clone it, and remove BI.
794 if (isa<TerminatorInst>(I1))
795 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000796
Chris Lattner389cfac2004-11-30 00:29:14 +0000797 // For a normal instruction, we just move one to right before the branch,
798 // then replace all uses of the other with the first. Finally, we remove
799 // the now redundant second instruction.
800 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
801 if (!I2->use_empty())
802 I2->replaceAllUsesWith(I1);
803 BB2->getInstList().erase(I2);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000804
Chris Lattner389cfac2004-11-30 00:29:14 +0000805 I1 = BB1->begin();
806 I2 = BB2->begin();
Chris Lattner389cfac2004-11-30 00:29:14 +0000807 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
808
809 return true;
810
811HoistTerminator:
812 // Okay, it is safe to hoist the terminator.
813 Instruction *NT = I1->clone();
814 BIParent->getInstList().insert(BI, NT);
815 if (NT->getType() != Type::VoidTy) {
816 I1->replaceAllUsesWith(NT);
817 I2->replaceAllUsesWith(NT);
818 NT->setName(I1->getName());
819 }
820
821 // Hoisting one of the terminators from our successor is a great thing.
822 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
823 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
824 // nodes, so we insert select instruction to compute the final result.
825 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
826 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
827 PHINode *PN;
828 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +0000829 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +0000830 Value *BB1V = PN->getIncomingValueForBlock(BB1);
831 Value *BB2V = PN->getIncomingValueForBlock(BB2);
832 if (BB1V != BB2V) {
833 // These values do not agree. Insert a select instruction before NT
834 // that determines the right value.
835 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
836 if (SI == 0)
837 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
838 BB1V->getName()+"."+BB2V->getName(), NT);
839 // Make the PHI node use the select for all incoming values for BB1/BB2
840 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
841 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
842 PN->setIncomingValue(i, SI);
843 }
844 }
845 }
846
847 // Update any PHI nodes in our new successors.
848 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
849 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000850
Chris Lattner389cfac2004-11-30 00:29:14 +0000851 BI->eraseFromParent();
852 return true;
853}
854
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000855namespace {
856 /// ConstantIntOrdering - This class implements a stable ordering of constant
857 /// integers that does not depend on their address. This is important for
858 /// applications that sort ConstantInt's to ensure uniqueness.
859 struct ConstantIntOrdering {
860 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
861 return LHS->getRawValue() < RHS->getRawValue();
862 }
863 };
864}
865
Chris Lattner466a0492002-05-21 20:50:24 +0000866// SimplifyCFG - This function is used to do simplification of a CFG. For
867// example, it adjusts branches to branches to eliminate the extra hop, it
868// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +0000869// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +0000870//
871// WARNING: The entry node of a function may not be simplified.
872//
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000873bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000874 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000875 Function *M = BB->getParent();
876
877 assert(BB && BB->getParent() && "Block not embedded in function!");
878 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000879 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000880
Chris Lattner466a0492002-05-21 20:50:24 +0000881 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnera2ab4892004-02-24 07:23:58 +0000882 if (pred_begin(BB) == pred_end(BB) ||
883 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner32c518e2004-07-15 02:06:12 +0000884 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000885
886 // Loop through all of our successors and make sure they know that one
887 // of their predecessors is going away.
Chris Lattner95f16a32005-04-12 18:51:33 +0000888 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
889 SI->removePredecessor(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000890
891 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000892 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000893 // If this instruction is used, replace uses with an arbitrary
Chris Lattnereee90f72005-08-02 23:29:23 +0000894 // value. Because control flow can't get here, we don't care
Misha Brukmanb1c93172005-04-21 23:48:37 +0000895 // what we replace the value with. Note that since this block is
Chris Lattner466a0492002-05-21 20:50:24 +0000896 // unreachable, and all values contained within it must dominate their
897 // uses, that all uses will eventually be removed.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000898 if (!I.use_empty())
Chris Lattnereee90f72005-08-02 23:29:23 +0000899 // Make all users of this instruction use undef instead
900 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000901
Chris Lattner466a0492002-05-21 20:50:24 +0000902 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000903 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000904 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000905 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000906 return true;
907 }
908
Chris Lattner031340a2003-08-17 19:41:53 +0000909 // Check to see if we can constant propagate this terminator instruction
910 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +0000911 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +0000912
Chris Lattnere42732e2004-02-16 06:35:48 +0000913 // If this is a returning block with only PHI nodes in it, fold the return
914 // instruction into any unconditional branch predecessors.
Chris Lattner9f0db322004-04-02 18:13:43 +0000915 //
916 // If any predecessor is a conditional branch that just selects among
917 // different return values, fold the replace the branch/return with a select
918 // and return.
Chris Lattnere42732e2004-02-16 06:35:48 +0000919 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
920 BasicBlock::iterator BBI = BB->getTerminator();
921 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner9f0db322004-04-02 18:13:43 +0000922 // Find predecessors that end with branches.
Chris Lattnere42732e2004-02-16 06:35:48 +0000923 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner9f0db322004-04-02 18:13:43 +0000924 std::vector<BranchInst*> CondBranchPreds;
Chris Lattnere42732e2004-02-16 06:35:48 +0000925 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
926 TerminatorInst *PTI = (*PI)->getTerminator();
927 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
928 if (BI->isUnconditional())
929 UncondBranchPreds.push_back(*PI);
Chris Lattner9f0db322004-04-02 18:13:43 +0000930 else
931 CondBranchPreds.push_back(BI);
Chris Lattnere42732e2004-02-16 06:35:48 +0000932 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000933
Chris Lattnere42732e2004-02-16 06:35:48 +0000934 // If we found some, do the transformation!
935 if (!UncondBranchPreds.empty()) {
936 while (!UncondBranchPreds.empty()) {
937 BasicBlock *Pred = UncondBranchPreds.back();
938 UncondBranchPreds.pop_back();
939 Instruction *UncondBranch = Pred->getTerminator();
940 // Clone the return and add it to the end of the predecessor.
941 Instruction *NewRet = RI->clone();
942 Pred->getInstList().push_back(NewRet);
943
944 // If the return instruction returns a value, and if the value was a
945 // PHI node in "BB", propagate the right value into the return.
946 if (NewRet->getNumOperands() == 1)
947 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
948 if (PN->getParent() == BB)
949 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
950 // Update any PHI nodes in the returning block to realize that we no
951 // longer branch to them.
952 BB->removePredecessor(Pred);
953 Pred->getInstList().erase(UncondBranch);
954 }
955
956 // If we eliminated all predecessors of the block, delete the block now.
957 if (pred_begin(BB) == pred_end(BB))
958 // We know there are no successors, so just nuke the block.
959 M->getBasicBlockList().erase(BB);
960
Chris Lattnere42732e2004-02-16 06:35:48 +0000961 return true;
962 }
Chris Lattner9f0db322004-04-02 18:13:43 +0000963
964 // Check out all of the conditional branches going to this return
965 // instruction. If any of them just select between returns, change the
966 // branch itself into a select/return pair.
967 while (!CondBranchPreds.empty()) {
968 BranchInst *BI = CondBranchPreds.back();
969 CondBranchPreds.pop_back();
970 BasicBlock *TrueSucc = BI->getSuccessor(0);
971 BasicBlock *FalseSucc = BI->getSuccessor(1);
972 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
973
974 // Check to see if the non-BB successor is also a return block.
975 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
976 // Check to see if there are only PHI instructions in this block.
977 BasicBlock::iterator OSI = OtherSucc->getTerminator();
978 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
979 // Okay, we found a branch that is going to two return nodes. If
980 // there is no return value for this function, just change the
981 // branch into a return.
982 if (RI->getNumOperands() == 0) {
983 TrueSucc->removePredecessor(BI->getParent());
984 FalseSucc->removePredecessor(BI->getParent());
985 new ReturnInst(0, BI);
986 BI->getParent()->getInstList().erase(BI);
987 return true;
988 }
989
990 // Otherwise, figure out what the true and false return values are
991 // so we can insert a new select instruction.
992 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
993 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
994
995 // Unwrap any PHI nodes in the return blocks.
996 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
997 if (TVPN->getParent() == TrueSucc)
998 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
999 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1000 if (FVPN->getParent() == FalseSucc)
1001 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1002
Chris Lattnereed034b2004-04-02 18:15:10 +00001003 TrueSucc->removePredecessor(BI->getParent());
1004 FalseSucc->removePredecessor(BI->getParent());
1005
Chris Lattner9f0db322004-04-02 18:13:43 +00001006 // Insert a new select instruction.
Chris Lattner879ce782004-09-29 05:43:32 +00001007 Value *NewRetVal;
1008 Value *BrCond = BI->getCondition();
1009 if (TrueValue != FalseValue)
1010 NewRetVal = new SelectInst(BrCond, TrueValue,
1011 FalseValue, "retval", BI);
1012 else
1013 NewRetVal = TrueValue;
1014
Chris Lattner9f0db322004-04-02 18:13:43 +00001015 new ReturnInst(NewRetVal, BI);
1016 BI->getParent()->getInstList().erase(BI);
Chris Lattner879ce782004-09-29 05:43:32 +00001017 if (BrCond->use_empty())
1018 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1019 BrCondI->getParent()->getInstList().erase(BrCondI);
Chris Lattner9f0db322004-04-02 18:13:43 +00001020 return true;
1021 }
1022 }
1023 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001024 }
Chris Lattner3cd98f02004-02-24 05:54:22 +00001025 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1026 // Check to see if the first instruction in this block is just an unwind.
1027 // If so, replace any invoke instructions which use this as an exception
Chris Lattner5823ac12004-07-20 01:17:38 +00001028 // destination with call instructions, and any unconditional branch
1029 // predecessor with an unwind.
Chris Lattner3cd98f02004-02-24 05:54:22 +00001030 //
1031 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1032 while (!Preds.empty()) {
1033 BasicBlock *Pred = Preds.back();
Chris Lattner5823ac12004-07-20 01:17:38 +00001034 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1035 if (BI->isUnconditional()) {
1036 Pred->getInstList().pop_back(); // nuke uncond branch
1037 new UnwindInst(Pred); // Use unwind.
1038 Changed = true;
1039 }
1040 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattner3cd98f02004-02-24 05:54:22 +00001041 if (II->getUnwindDest() == BB) {
1042 // Insert a new branch instruction before the invoke, because this
1043 // is now a fall through...
1044 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1045 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001046
Chris Lattner3cd98f02004-02-24 05:54:22 +00001047 // Insert the call now...
1048 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1049 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1050 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001051 CI->setCallingConv(II->getCallingConv());
Chris Lattner3cd98f02004-02-24 05:54:22 +00001052 // If the invoke produced a value, the Call now does instead
1053 II->replaceAllUsesWith(CI);
1054 delete II;
1055 Changed = true;
1056 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001057
Chris Lattner3cd98f02004-02-24 05:54:22 +00001058 Preds.pop_back();
1059 }
Chris Lattner90ea78e2004-02-24 16:09:21 +00001060
1061 // If this block is now dead, remove it.
1062 if (pred_begin(BB) == pred_end(BB)) {
1063 // We know there are no successors, so just nuke the block.
1064 M->getBasicBlockList().erase(BB);
1065 return true;
1066 }
1067
Chris Lattner1cca9592005-02-24 06:17:52 +00001068 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1069 if (isValueEqualityComparison(SI)) {
1070 // If we only have one predecessor, and if it is a branch on this value,
1071 // see if that predecessor totally determines the outcome of this switch.
1072 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1073 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1074 return SimplifyCFG(BB) || 1;
1075
1076 // If the block only contains the switch, see if we can fold the block
1077 // away into any preds.
1078 if (SI == &BB->front())
1079 if (FoldValueComparisonIntoPredecessors(SI))
1080 return SimplifyCFG(BB) || 1;
1081 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001082 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner733d6702005-08-03 00:11:16 +00001083 if (BI->isUnconditional()) {
1084 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1085 while (isa<PHINode>(*BBI)) ++BBI;
1086
1087 BasicBlock *Succ = BI->getSuccessor(0);
1088 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1089 Succ != BB) // Don't hurt infinite loops!
1090 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1091 return 1;
1092
1093 } else { // Conditional branch
Chris Lattner2e93c422004-05-01 23:35:43 +00001094 if (Value *CompVal = isValueEqualityComparison(BI)) {
Chris Lattner1cca9592005-02-24 06:17:52 +00001095 // If we only have one predecessor, and if it is a branch on this value,
1096 // see if that predecessor totally determines the outcome of this
1097 // switch.
1098 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1099 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1100 return SimplifyCFG(BB) || 1;
1101
Chris Lattner2e93c422004-05-01 23:35:43 +00001102 // This block must be empty, except for the setcond inst, if it exists.
1103 BasicBlock::iterator I = BB->begin();
1104 if (&*I == BI ||
1105 (&*I == cast<Instruction>(BI->getCondition()) &&
1106 &*++I == BI))
1107 if (FoldValueComparisonIntoPredecessors(BI))
1108 return SimplifyCFG(BB) | true;
1109 }
1110
1111 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1112 // branches to us and one of our successors, fold the setcc into the
1113 // predecessor and use logical operations to pick the right destination.
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001114 BasicBlock *TrueDest = BI->getSuccessor(0);
1115 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbe6f0682004-05-02 05:19:36 +00001116 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattner2e93c422004-05-01 23:35:43 +00001117 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001118 Cond->getNext() == BI && Cond->hasOneUse() &&
1119 TrueDest != BB && FalseDest != BB)
Chris Lattner2e93c422004-05-01 23:35:43 +00001120 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1121 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner1e94ed62004-05-02 01:00:44 +00001122 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001123 BasicBlock *PredBlock = *PI;
Chris Lattner2e93c422004-05-01 23:35:43 +00001124 if (PBI->getSuccessor(0) == FalseDest ||
1125 PBI->getSuccessor(1) == TrueDest) {
1126 // Invert the predecessors condition test (xor it with true),
1127 // which allows us to write this code once.
1128 Value *NewCond =
1129 BinaryOperator::createNot(PBI->getCondition(),
1130 PBI->getCondition()->getName()+".not", PBI);
1131 PBI->setCondition(NewCond);
1132 BasicBlock *OldTrue = PBI->getSuccessor(0);
1133 BasicBlock *OldFalse = PBI->getSuccessor(1);
1134 PBI->setSuccessor(0, OldFalse);
1135 PBI->setSuccessor(1, OldTrue);
1136 }
1137
1138 if (PBI->getSuccessor(0) == TrueDest ||
1139 PBI->getSuccessor(1) == FalseDest) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001140 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattner2e93c422004-05-01 23:35:43 +00001141 // two conditions together.
1142 Instruction *New = Cond->clone();
1143 New->setName(Cond->getName());
1144 Cond->setName(Cond->getName()+".old");
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001145 PredBlock->getInstList().insert(PBI, New);
Chris Lattner2e93c422004-05-01 23:35:43 +00001146 Instruction::BinaryOps Opcode =
1147 PBI->getSuccessor(0) == TrueDest ?
1148 Instruction::Or : Instruction::And;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149 Value *NewCond =
Chris Lattner2e93c422004-05-01 23:35:43 +00001150 BinaryOperator::create(Opcode, PBI->getCondition(),
1151 New, "bothcond", PBI);
1152 PBI->setCondition(NewCond);
1153 if (PBI->getSuccessor(0) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001154 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001155 PBI->setSuccessor(0, TrueDest);
1156 }
1157 if (PBI->getSuccessor(1) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001158 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001159 PBI->setSuccessor(1, FalseDest);
1160 }
1161 return SimplifyCFG(BB) | 1;
1162 }
1163 }
Chris Lattner2e93c422004-05-01 23:35:43 +00001164
Chris Lattner88da6f72004-05-01 22:36:37 +00001165 // If this block ends with a branch instruction, and if there is one
1166 // predecessor, see if the previous block ended with a branch on the same
1167 // condition, which makes this conditional branch redundant.
Chris Lattner733d6702005-08-03 00:11:16 +00001168 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Chris Lattner88da6f72004-05-01 22:36:37 +00001169 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1170 if (PBI->isConditional() &&
1171 PBI->getCondition() == BI->getCondition() &&
Chris Lattner4cbd1602004-05-01 22:41:51 +00001172 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner88da6f72004-05-01 22:36:37 +00001173 // Okay, the outcome of this conditional branch is statically
1174 // knowable. Delete the outgoing CFG edge that is impossible to
1175 // execute.
1176 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1177 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
1178 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
1179 BB->getInstList().erase(BI);
1180 return SimplifyCFG(BB) | true;
1181 }
Chris Lattnera2ab4892004-02-24 07:23:58 +00001182 }
Chris Lattner5edb2f32004-10-18 04:07:22 +00001183 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1184 // If there are any instructions immediately before the unreachable that can
1185 // be removed, do so.
1186 Instruction *Unreachable = BB->getTerminator();
1187 while (Unreachable != BB->begin()) {
1188 BasicBlock::iterator BBI = Unreachable;
1189 --BBI;
1190 if (isa<CallInst>(BBI)) break;
1191 // Delete this instruction
1192 BB->getInstList().erase(BBI);
1193 Changed = true;
1194 }
1195
1196 // If the unreachable instruction is the first in the block, take a gander
1197 // at all of the predecessors of this instruction, and simplify them.
1198 if (&BB->front() == Unreachable) {
1199 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1200 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1201 TerminatorInst *TI = Preds[i]->getTerminator();
1202
1203 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1204 if (BI->isUnconditional()) {
1205 if (BI->getSuccessor(0) == BB) {
1206 new UnreachableInst(TI);
1207 TI->eraseFromParent();
1208 Changed = true;
1209 }
1210 } else {
1211 if (BI->getSuccessor(0) == BB) {
1212 new BranchInst(BI->getSuccessor(1), BI);
1213 BI->eraseFromParent();
1214 } else if (BI->getSuccessor(1) == BB) {
1215 new BranchInst(BI->getSuccessor(0), BI);
1216 BI->eraseFromParent();
1217 Changed = true;
1218 }
1219 }
1220 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1221 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1222 if (SI->getSuccessor(i) == BB) {
Chris Lattner19f9f322005-05-20 22:19:54 +00001223 BB->removePredecessor(SI->getParent());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001224 SI->removeCase(i);
1225 --i; --e;
1226 Changed = true;
1227 }
1228 // If the default value is unreachable, figure out the most popular
1229 // destination and make it the default.
1230 if (SI->getSuccessor(0) == BB) {
1231 std::map<BasicBlock*, unsigned> Popularity;
1232 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1233 Popularity[SI->getSuccessor(i)]++;
1234
1235 // Find the most popular block.
1236 unsigned MaxPop = 0;
1237 BasicBlock *MaxBlock = 0;
1238 for (std::map<BasicBlock*, unsigned>::iterator
1239 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1240 if (I->second > MaxPop) {
1241 MaxPop = I->second;
1242 MaxBlock = I->first;
1243 }
1244 }
1245 if (MaxBlock) {
1246 // Make this the new default, allowing us to delete any explicit
1247 // edges to it.
1248 SI->setSuccessor(0, MaxBlock);
1249 Changed = true;
1250
Chris Lattner19f9f322005-05-20 22:19:54 +00001251 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1252 // it.
1253 if (isa<PHINode>(MaxBlock->begin()))
1254 for (unsigned i = 0; i != MaxPop-1; ++i)
1255 MaxBlock->removePredecessor(SI->getParent());
1256
Chris Lattner5edb2f32004-10-18 04:07:22 +00001257 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1258 if (SI->getSuccessor(i) == MaxBlock) {
1259 SI->removeCase(i);
1260 --i; --e;
1261 }
1262 }
1263 }
1264 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1265 if (II->getUnwindDest() == BB) {
1266 // Convert the invoke to a call instruction. This would be a good
1267 // place to note that the call does not throw though.
1268 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1269 II->removeFromParent(); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001270
Chris Lattner5edb2f32004-10-18 04:07:22 +00001271 // Insert the call now...
1272 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1273 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1274 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001275 CI->setCallingConv(II->getCallingConv());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001276 // If the invoke produced a value, the Call does now instead.
1277 II->replaceAllUsesWith(CI);
1278 delete II;
1279 Changed = true;
1280 }
1281 }
1282 }
1283
1284 // If this block is now dead, remove it.
1285 if (pred_begin(BB) == pred_end(BB)) {
1286 // We know there are no successors, so just nuke the block.
1287 M->getBasicBlockList().erase(BB);
1288 return true;
1289 }
1290 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001291 }
1292
Chris Lattner466a0492002-05-21 20:50:24 +00001293 // Merge basic blocks into their predecessor if there is only one distinct
1294 // pred, and if there is only one distinct successor of the predecessor, and
1295 // if there are no PHI nodes.
1296 //
Chris Lattner838b8452004-02-11 01:17:07 +00001297 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1298 BasicBlock *OnlyPred = *PI++;
1299 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1300 if (*PI != OnlyPred) {
1301 OnlyPred = 0; // There are multiple different predecessors...
1302 break;
1303 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001304
Chris Lattner838b8452004-02-11 01:17:07 +00001305 BasicBlock *OnlySucc = 0;
1306 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1307 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1308 // Check to see if there is only one distinct successor...
1309 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1310 OnlySucc = BB;
1311 for (; SI != SE; ++SI)
1312 if (*SI != OnlySucc) {
1313 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +00001314 break;
1315 }
Chris Lattner838b8452004-02-11 01:17:07 +00001316 }
1317
1318 if (OnlySucc) {
Chris Lattner32c518e2004-07-15 02:06:12 +00001319 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner838b8452004-02-11 01:17:07 +00001320 TerminatorInst *Term = OnlyPred->getTerminator();
1321
1322 // Resolve any PHI nodes at the start of the block. They are all
1323 // guaranteed to have exactly one entry if they exist, unless there are
1324 // multiple duplicate (but guaranteed to be equal) entries for the
1325 // incoming edges. This occurs when there are multiple edges from
1326 // OnlyPred to OnlySucc.
1327 //
1328 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1329 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1330 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +00001331 }
1332
Chris Lattner838b8452004-02-11 01:17:07 +00001333 // Delete the unconditional branch from the predecessor...
1334 OnlyPred->getInstList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001335
Chris Lattner838b8452004-02-11 01:17:07 +00001336 // Move all definitions in the successor to the predecessor...
1337 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001338
Chris Lattner838b8452004-02-11 01:17:07 +00001339 // Make all PHI nodes that referred to BB now refer to Pred as their
1340 // source...
1341 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001342
Chris Lattner838b8452004-02-11 01:17:07 +00001343 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +00001344
Misha Brukmanb1c93172005-04-21 23:48:37 +00001345 // Erase basic block from the function...
Chris Lattner838b8452004-02-11 01:17:07 +00001346 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001347
Chris Lattner838b8452004-02-11 01:17:07 +00001348 // Inherit predecessors name if it exists...
1349 if (!OldName.empty() && !OnlyPred->hasName())
1350 OnlyPred->setName(OldName);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001351
Chris Lattner838b8452004-02-11 01:17:07 +00001352 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00001353 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001354
Chris Lattner389cfac2004-11-30 00:29:14 +00001355 // Otherwise, if this block only has a single predecessor, and if that block
1356 // is a conditional branch, see if we can hoist any code from this block up
1357 // into our predecessor.
1358 if (OnlyPred)
Chris Lattner4fc998d2004-12-10 17:42:31 +00001359 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1360 if (BI->isConditional()) {
1361 // Get the other block.
1362 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1363 PI = pred_begin(OtherBB);
1364 ++PI;
1365 if (PI == pred_end(OtherBB)) {
1366 // We have a conditional branch to two blocks that are only reachable
1367 // from the condbr. We know that the condbr dominates the two blocks,
1368 // so see if there is any identical code in the "then" and "else"
1369 // blocks. If so, we can hoist it up to the branching block.
1370 Changed |= HoistThenElseCodeToIf(BI);
1371 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001372 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001373
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001374 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1375 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1376 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1377 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1378 Instruction *Cond = cast<Instruction>(BI->getCondition());
1379 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1380 // 'setne's and'ed together, collect them.
1381 Value *CompVal = 0;
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001382 std::vector<ConstantInt*> Values;
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001383 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1384 if (CompVal && CompVal->getType()->isInteger()) {
1385 // There might be duplicate constants in the list, which the switch
1386 // instruction can't handle, remove them now.
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001387 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001388 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001389
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001390 // Figure out which block is which destination.
1391 BasicBlock *DefaultBB = BI->getSuccessor(1);
1392 BasicBlock *EdgeBB = BI->getSuccessor(0);
1393 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001394
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001395 // Create the new switch instruction now.
Chris Lattnera35dfce2005-01-29 00:38:26 +00001396 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001397
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001398 // Add all of the 'cases' to the switch instruction.
1399 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1400 New->addCase(Values[i], EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001401
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001402 // We added edges from PI to the EdgeBB. As such, if there were any
1403 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1404 // the number of edges added.
1405 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer66149462004-09-15 17:06:42 +00001406 isa<PHINode>(BBI); ++BBI) {
1407 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001408 Value *InVal = PN->getIncomingValueForBlock(*PI);
1409 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1410 PN->addIncoming(InVal, *PI);
1411 }
1412
1413 // Erase the old branch instruction.
1414 (*PI)->getInstList().erase(BI);
1415
1416 // Erase the potentially condition tree that was used to computed the
1417 // branch condition.
1418 ErasePossiblyDeadInstructionTree(Cond);
1419 return true;
1420 }
1421 }
1422
Chris Lattner18d1f192004-02-11 03:36:04 +00001423 // If there is a trivial two-entry PHI node in this basic block, and we can
1424 // eliminate it, do so now.
1425 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1426 if (PN->getNumIncomingValues() == 2) {
1427 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1428 // statement", which has a very simple dominance structure. Basically, we
1429 // are trying to find the condition that is being branched on, which
1430 // subsequently causes this merge to happen. We really want control
1431 // dependence information for this check, but simplifycfg can't keep it up
1432 // to date, and this catches most of the cases we care about anyway.
1433 //
1434 BasicBlock *IfTrue, *IfFalse;
1435 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner9734fd02004-06-20 01:13:18 +00001436 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1437 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner18d1f192004-02-11 03:36:04 +00001438
Chris Lattner45c35b12004-10-14 05:13:36 +00001439 // Loop over the PHI's seeing if we can promote them all to select
1440 // instructions. While we are at it, keep track of the instructions
1441 // that need to be moved to the dominating block.
1442 std::set<Instruction*> AggressiveInsts;
1443 bool CanPromote = true;
1444
Chris Lattner18d1f192004-02-11 03:36:04 +00001445 BasicBlock::iterator AfterPHIIt = BB->begin();
Chris Lattner45c35b12004-10-14 05:13:36 +00001446 while (isa<PHINode>(AfterPHIIt)) {
1447 PHINode *PN = cast<PHINode>(AfterPHIIt++);
Chris Lattner5e735292005-06-17 01:45:53 +00001448 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1449 if (PN->getIncomingValue(0) != PN)
1450 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1451 else
1452 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1453 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1454 &AggressiveInsts) ||
1455 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1456 &AggressiveInsts)) {
Chris Lattner45c35b12004-10-14 05:13:36 +00001457 CanPromote = false;
1458 break;
1459 }
1460 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001461
Chris Lattner45c35b12004-10-14 05:13:36 +00001462 // Did we eliminate all PHI's?
1463 CanPromote |= AfterPHIIt == BB->begin();
Chris Lattner18d1f192004-02-11 03:36:04 +00001464
Chris Lattner45c35b12004-10-14 05:13:36 +00001465 // If we all PHI nodes are promotable, check to make sure that all
1466 // instructions in the predecessor blocks can be promoted as well. If
1467 // not, we won't be able to get rid of the control flow, so it's not
1468 // worth promoting to select instructions.
Reid Spencerfad217c2004-10-22 16:10:39 +00001469 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
Chris Lattner45c35b12004-10-14 05:13:36 +00001470 if (CanPromote) {
1471 PN = cast<PHINode>(BB->begin());
1472 BasicBlock *Pred = PN->getIncomingBlock(0);
1473 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1474 IfBlock1 = Pred;
1475 DomBlock = *pred_begin(Pred);
1476 for (BasicBlock::iterator I = Pred->begin();
1477 !isa<TerminatorInst>(I); ++I)
1478 if (!AggressiveInsts.count(I)) {
1479 // This is not an aggressive instruction that we can promote.
1480 // Because of this, we won't be able to get rid of the control
1481 // flow, so the xform is not worth it.
1482 CanPromote = false;
1483 break;
1484 }
1485 }
1486
1487 Pred = PN->getIncomingBlock(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001488 if (CanPromote &&
Chris Lattner45c35b12004-10-14 05:13:36 +00001489 cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1490 IfBlock2 = Pred;
1491 DomBlock = *pred_begin(Pred);
1492 for (BasicBlock::iterator I = Pred->begin();
1493 !isa<TerminatorInst>(I); ++I)
1494 if (!AggressiveInsts.count(I)) {
1495 // This is not an aggressive instruction that we can promote.
1496 // Because of this, we won't be able to get rid of the control
1497 // flow, so the xform is not worth it.
1498 CanPromote = false;
1499 break;
1500 }
1501 }
1502 }
1503
1504 // If we can still promote the PHI nodes after this gauntlet of tests,
1505 // do all of the PHI's now.
1506 if (CanPromote) {
1507 // Move all 'aggressive' instructions, which are defined in the
1508 // conditional parts of the if's up to the dominating block.
1509 if (IfBlock1) {
1510 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1511 IfBlock1->getInstList(),
1512 IfBlock1->begin(),
1513 IfBlock1->getTerminator());
1514 }
1515 if (IfBlock2) {
1516 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1517 IfBlock2->getInstList(),
1518 IfBlock2->begin(),
1519 IfBlock2->getTerminator());
1520 }
1521
1522 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1523 // Change the PHI node into a select instruction.
Chris Lattner18d1f192004-02-11 03:36:04 +00001524 Value *TrueVal =
1525 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1526 Value *FalseVal =
1527 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1528
Chris Lattner81bdcb92004-03-30 19:44:05 +00001529 std::string Name = PN->getName(); PN->setName("");
1530 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
Chris Lattner45c35b12004-10-14 05:13:36 +00001531 Name, AfterPHIIt));
Chris Lattner81bdcb92004-03-30 19:44:05 +00001532 BB->getInstList().erase(PN);
Chris Lattner18d1f192004-02-11 03:36:04 +00001533 }
Chris Lattner45c35b12004-10-14 05:13:36 +00001534 Changed = true;
Chris Lattner18d1f192004-02-11 03:36:04 +00001535 }
1536 }
1537 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001538
Chris Lattner031340a2003-08-17 19:41:53 +00001539 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00001540}