blob: c94c41b2169b1b52f40699656304ff9a55a33004 [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"
Reid Spencera94d3942007-01-19 21:13:56 +000019#include "llvm/DerivedTypes.h"
Chris Lattner466a0492002-05-21 20:50:24 +000020#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000021#include "llvm/Support/Debug.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000022#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner748f9032005-09-19 23:49:37 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner466a0492002-05-21 20:50:24 +000024#include <algorithm>
25#include <functional>
Chris Lattnera2ab4892004-02-24 07:23:58 +000026#include <set>
Chris Lattner5edb2f32004-10-18 04:07:22 +000027#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000028using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000029
Chris Lattner76dc2042005-08-03 00:19:45 +000030/// SafeToMergeTerminators - Return true if it is safe to merge these two
31/// terminator instructions together.
32///
33static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
34 if (SI1 == SI2) return false; // Can't merge with self!
35
36 // It is not safe to merge these two switch instructions if they have a common
37 // successor, and if that successor has a PHI node, and if *that* PHI node has
38 // conflicting incoming values from the two switch blocks.
39 BasicBlock *SI1BB = SI1->getParent();
40 BasicBlock *SI2BB = SI2->getParent();
41 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
42
43 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
44 if (SI1Succs.count(*I))
45 for (BasicBlock::iterator BBI = (*I)->begin();
46 isa<PHINode>(BBI); ++BBI) {
47 PHINode *PN = cast<PHINode>(BBI);
48 if (PN->getIncomingValueForBlock(SI1BB) !=
49 PN->getIncomingValueForBlock(SI2BB))
50 return false;
51 }
52
53 return true;
54}
55
56/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
57/// now be entries in it from the 'NewPred' block. The values that will be
58/// flowing into the PHI nodes will be the same as those coming in from
59/// ExistPred, an existing predecessor of Succ.
60static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
61 BasicBlock *ExistPred) {
62 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
63 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
64 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
65
66 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
67 PHINode *PN = cast<PHINode>(I);
68 Value *V = PN->getIncomingValueForBlock(ExistPred);
69 PN->addIncoming(V, NewPred);
70 }
71}
72
Chris Lattner982b75c2005-08-03 00:29:26 +000073// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
74// almost-empty BB ending in an unconditional branch to Succ, into succ.
Chris Lattner466a0492002-05-21 20:50:24 +000075//
76// Assumption: Succ is the single successor for BB.
77//
Chris Lattner982b75c2005-08-03 00:29:26 +000078static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000079 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000080
Chris Lattner466a0492002-05-21 20:50:24 +000081 // 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 Lattner90803692005-08-03 00:38:27 +000085 if (isa<PHINode>(Succ->front())) {
86 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner2820b8c2005-12-03 18:25:58 +000087 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
Chris Lattner90803692005-08-03 00:38:27 +000088 PI != PE; ++PI)
89 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
90 // Loop over all of the PHI nodes checking to see if there are
91 // incompatible values coming in.
92 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
93 PHINode *PN = cast<PHINode>(I);
94 // Loop up the entries in the PHI node for BB and for *PI if the
95 // values coming in are non-equal, we cannot merge these two blocks
96 // (instead we should insert a conditional move or something, then
97 // merge the blocks).
98 if (PN->getIncomingValueForBlock(BB) !=
99 PN->getIncomingValueForBlock(*PI))
100 return false; // Values are not equal...
101 }
102 }
103 }
Chris Lattner2dbf1962005-08-03 00:59:12 +0000104
105 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
106 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
107 // fold these blocks, as we don't know whether BB dominates Succ or not to
108 // update the PHI nodes correctly.
109 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000110
Chris Lattner2dbf1962005-08-03 00:59:12 +0000111 // If the predecessors of Succ are only BB and Succ itself, we can handle this.
112 bool IsSafe = true;
113 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
114 if (*PI != Succ && *PI != BB) {
115 IsSafe = false;
116 break;
117 }
118 if (IsSafe) return true;
119
Chris Lattner2820b8c2005-12-03 18:25:58 +0000120 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
121 // BB and Succ have no common predecessors.
Chris Lattner35515552006-05-14 18:45:44 +0000122 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
Chris Lattner2dbf1962005-08-03 00:59:12 +0000123 PHINode *PN = cast<PHINode>(I);
124 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
125 ++UI)
Chris Lattner2820b8c2005-12-03 18:25:58 +0000126 if (cast<Instruction>(*UI)->getParent() != Succ)
127 return false;
Chris Lattner2dbf1962005-08-03 00:59:12 +0000128 }
129
Chris Lattner2820b8c2005-12-03 18:25:58 +0000130 // Scan the predecessor sets of BB and Succ, making sure there are no common
131 // predecessors. Common predecessors would cause us to build a phi node with
132 // differing incoming values, which is not legal.
133 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
134 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
135 if (BBPreds.count(*PI))
136 return false;
137
138 return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000139}
140
Chris Lattner733d6702005-08-03 00:11:16 +0000141/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
142/// branch to Succ, and contains no instructions other than PHI nodes and the
143/// branch. If possible, eliminate BB.
144static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
145 BasicBlock *Succ) {
146 // If our successor has PHI nodes, then we need to update them to include
147 // entries for BB's predecessors, not for BB itself. Be careful though,
148 // if this transformation fails (returns true) then we cannot do this
149 // transformation!
150 //
Chris Lattner982b75c2005-08-03 00:29:26 +0000151 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner733d6702005-08-03 00:11:16 +0000152
Bill Wendling4ae40102006-11-26 10:17:54 +0000153 DOUT << "Killing Trivial BB: \n" << *BB;
Chris Lattner733d6702005-08-03 00:11:16 +0000154
Chris Lattner982b75c2005-08-03 00:29:26 +0000155 if (isa<PHINode>(Succ->begin())) {
156 // If there is more than one pred of succ, and there are PHI nodes in
157 // the successor, then we need to add incoming edges for the PHI nodes
158 //
159 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
160
161 // Loop over all of the PHI nodes in the successor of BB.
162 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
163 PHINode *PN = cast<PHINode>(I);
164 Value *OldVal = PN->removeIncomingValue(BB, false);
165 assert(OldVal && "No entry in PHI for Pred BB!");
166
Chris Lattner90803692005-08-03 00:38:27 +0000167 // If this incoming value is one of the PHI nodes in BB, the new entries
168 // in the PHI node are the entries from the old PHI.
Chris Lattner982b75c2005-08-03 00:29:26 +0000169 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
170 PHINode *OldValPN = cast<PHINode>(OldVal);
171 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
172 PN->addIncoming(OldValPN->getIncomingValue(i),
173 OldValPN->getIncomingBlock(i));
174 } else {
175 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
176 End = BBPreds.end(); PredI != End; ++PredI) {
177 // Add an incoming value for each of the new incoming values...
178 PN->addIncoming(OldVal, *PredI);
179 }
180 }
181 }
182 }
183
Chris Lattner733d6702005-08-03 00:11:16 +0000184 if (isa<PHINode>(&BB->front())) {
185 std::vector<BasicBlock*>
186 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
187
188 // Move all PHI nodes in BB to Succ if they are alive, otherwise
189 // delete them.
190 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
Chris Lattner90803692005-08-03 00:38:27 +0000191 if (PN->use_empty()) {
192 // Just remove the dead phi. This happens if Succ's PHIs were the only
193 // users of the PHI nodes.
194 PN->eraseFromParent();
Chris Lattner733d6702005-08-03 00:11:16 +0000195 } else {
196 // The instruction is alive, so this means that Succ must have
197 // *ONLY* had BB as a predecessor, and the PHI node is still valid
198 // now. Simply move it into Succ, because we know that BB
199 // strictly dominated Succ.
Chris Lattner1f047fd2005-08-03 00:23:42 +0000200 Succ->getInstList().splice(Succ->begin(),
201 BB->getInstList(), BB->begin());
Chris Lattner733d6702005-08-03 00:11:16 +0000202
203 // We need to add new entries for the PHI node to account for
204 // predecessors of Succ that the PHI node does not take into
205 // account. At this point, since we know that BB dominated succ,
206 // this means that we should any newly added incoming edges should
207 // use the PHI node as the value for these edges, because they are
208 // loop back edges.
209 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
210 if (OldSuccPreds[i] != BB)
211 PN->addIncoming(PN, OldSuccPreds[i]);
212 }
213 }
214
215 // Everything that jumped to BB now goes to Succ.
216 std::string OldName = BB->getName();
217 BB->replaceAllUsesWith(Succ);
218 BB->eraseFromParent(); // Delete the old basic block.
219
220 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
221 Succ->setName(OldName);
222 return true;
223}
224
Chris Lattner18d1f192004-02-11 03:36:04 +0000225/// GetIfCondition - Given a basic block (BB) with two predecessors (and
226/// presumably PHI nodes in it), check to see if the merge at this block is due
227/// to an "if condition". If so, return the boolean condition that determines
228/// which entry into BB will be taken. Also, return by references the block
229/// that will be entered from if the condition is true, and the block that will
230/// be entered if the condition is false.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000231///
Chris Lattner18d1f192004-02-11 03:36:04 +0000232///
233static Value *GetIfCondition(BasicBlock *BB,
234 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
235 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
236 "Function can only handle blocks with 2 predecessors!");
237 BasicBlock *Pred1 = *pred_begin(BB);
238 BasicBlock *Pred2 = *++pred_begin(BB);
239
240 // We can only handle branches. Other control flow will be lowered to
241 // branches if possible anyway.
242 if (!isa<BranchInst>(Pred1->getTerminator()) ||
243 !isa<BranchInst>(Pred2->getTerminator()))
244 return 0;
245 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
246 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
247
248 // Eliminate code duplication by ensuring that Pred1Br is conditional if
249 // either are.
250 if (Pred2Br->isConditional()) {
251 // If both branches are conditional, we don't have an "if statement". In
252 // reality, we could transform this case, but since the condition will be
253 // required anyway, we stand no chance of eliminating it, so the xform is
254 // probably not profitable.
255 if (Pred1Br->isConditional())
256 return 0;
257
258 std::swap(Pred1, Pred2);
259 std::swap(Pred1Br, Pred2Br);
260 }
261
262 if (Pred1Br->isConditional()) {
263 // If we found a conditional branch predecessor, make sure that it branches
264 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
265 if (Pred1Br->getSuccessor(0) == BB &&
266 Pred1Br->getSuccessor(1) == Pred2) {
267 IfTrue = Pred1;
268 IfFalse = Pred2;
269 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
270 Pred1Br->getSuccessor(1) == BB) {
271 IfTrue = Pred2;
272 IfFalse = Pred1;
273 } else {
274 // We know that one arm of the conditional goes to BB, so the other must
275 // go somewhere unrelated, and this must not be an "if statement".
276 return 0;
277 }
278
279 // The only thing we have to watch out for here is to make sure that Pred2
280 // doesn't have incoming edges from other blocks. If it does, the condition
281 // doesn't dominate BB.
282 if (++pred_begin(Pred2) != pred_end(Pred2))
283 return 0;
284
285 return Pred1Br->getCondition();
286 }
287
288 // Ok, if we got here, both predecessors end with an unconditional branch to
289 // BB. Don't panic! If both blocks only have a single (identical)
290 // predecessor, and THAT is a conditional branch, then we're all ok!
291 if (pred_begin(Pred1) == pred_end(Pred1) ||
292 ++pred_begin(Pred1) != pred_end(Pred1) ||
293 pred_begin(Pred2) == pred_end(Pred2) ||
294 ++pred_begin(Pred2) != pred_end(Pred2) ||
295 *pred_begin(Pred1) != *pred_begin(Pred2))
296 return 0;
297
298 // Otherwise, if this is a conditional branch, then we can use it!
299 BasicBlock *CommonPred = *pred_begin(Pred1);
300 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
301 assert(BI->isConditional() && "Two successors but not conditional?");
302 if (BI->getSuccessor(0) == Pred1) {
303 IfTrue = Pred1;
304 IfFalse = Pred2;
305 } else {
306 IfTrue = Pred2;
307 IfFalse = Pred1;
308 }
309 return BI->getCondition();
310 }
311 return 0;
312}
313
314
315// If we have a merge point of an "if condition" as accepted above, return true
316// if the specified value dominates the block. We don't handle the true
317// generality of domination here, just a special case which works well enough
318// for us.
Chris Lattner45c35b12004-10-14 05:13:36 +0000319//
320// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
321// see if V (which must be an instruction) is cheap to compute and is
322// non-trapping. If both are true, the instruction is inserted into the set and
323// true is returned.
324static bool DominatesMergePoint(Value *V, BasicBlock *BB,
325 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000326 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000327 if (!I) {
328 // Non-instructions all dominate instructions, but not all constantexprs
329 // can be executed unconditionally.
330 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
331 if (C->canTrap())
332 return false;
333 return true;
334 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000335 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000336
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000337 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000338 // the bottom of this block.
339 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000340
Chris Lattner0aa56562004-04-09 22:50:22 +0000341 // If this instruction is defined in a block that contains an unconditional
342 // branch to BB, then it must be in the 'conditional' part of the "if
343 // statement".
344 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
345 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner45c35b12004-10-14 05:13:36 +0000346 if (!AggressiveInsts) return false;
Chris Lattner0aa56562004-04-09 22:50:22 +0000347 // Okay, it looks like the instruction IS in the "condition". Check to
348 // see if its a cheap instruction to unconditionally compute, and if it
349 // only uses stuff defined outside of the condition. If so, hoist it out.
350 switch (I->getOpcode()) {
351 default: return false; // Cannot hoist this out safely.
352 case Instruction::Load:
353 // We can hoist loads that are non-volatile and obviously cannot trap.
354 if (cast<LoadInst>(I)->isVolatile())
355 return false;
356 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spenceref784f02004-07-18 00:32:14 +0000357 !isa<Constant>(I->getOperand(0)))
Chris Lattner0aa56562004-04-09 22:50:22 +0000358 return false;
359
360 // Finally, we have to check to make sure there are no instructions
361 // before the load in its basic block, as we are going to hoist the loop
362 // out to its predecessor.
363 if (PBB->begin() != BasicBlock::iterator(I))
364 return false;
365 break;
366 case Instruction::Add:
367 case Instruction::Sub:
368 case Instruction::And:
369 case Instruction::Or:
370 case Instruction::Xor:
371 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +0000372 case Instruction::LShr:
373 case Instruction::AShr:
Reid Spencer266e42b2006-12-23 06:05:41 +0000374 case Instruction::ICmp:
375 case Instruction::FCmp:
Chris Lattner0aa56562004-04-09 22:50:22 +0000376 break; // These are all cheap and non-trapping instructions.
377 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000378
Chris Lattner0aa56562004-04-09 22:50:22 +0000379 // Okay, we can only really hoist these out if their operands are not
380 // defined in the conditional region.
381 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner45c35b12004-10-14 05:13:36 +0000382 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner0aa56562004-04-09 22:50:22 +0000383 return false;
Chris Lattner45c35b12004-10-14 05:13:36 +0000384 // Okay, it's safe to do this! Remember this instruction.
385 AggressiveInsts->insert(I);
Chris Lattner0aa56562004-04-09 22:50:22 +0000386 }
387
Chris Lattner18d1f192004-02-11 03:36:04 +0000388 return true;
389}
Chris Lattner466a0492002-05-21 20:50:24 +0000390
Reid Spencer266e42b2006-12-23 06:05:41 +0000391// GatherConstantSetEQs - Given a potentially 'or'd together collection of
392// icmp_eq instructions that compare a value against a constant, return the
393// value being compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000394static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000395 if (Instruction *Inst = dyn_cast<Instruction>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000396 if (Inst->getOpcode() == Instruction::ICmp &&
397 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000398 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000399 Values.push_back(C);
400 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000401 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000402 Values.push_back(C);
403 return Inst->getOperand(1);
404 }
405 } else if (Inst->getOpcode() == Instruction::Or) {
406 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
407 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
408 if (LHS == RHS)
409 return LHS;
410 }
411 return 0;
412}
413
414// GatherConstantSetNEs - Given a potentially 'and'd together collection of
415// setne instructions that compare a value against a constant, return the value
416// being compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000417static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000418 if (Instruction *Inst = dyn_cast<Instruction>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000419 if (Inst->getOpcode() == Instruction::ICmp &&
420 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000421 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000422 Values.push_back(C);
423 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000424 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000425 Values.push_back(C);
426 return Inst->getOperand(1);
427 }
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000428 } else if (Inst->getOpcode() == Instruction::And) {
429 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
430 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
431 if (LHS == RHS)
432 return LHS;
433 }
434 return 0;
435}
436
437
438
439/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
440/// bunch of comparisons of one value against constants, return the value and
441/// the constants being compared.
442static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000443 std::vector<ConstantInt*> &Values) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000444 if (Cond->getOpcode() == Instruction::Or) {
445 CompVal = GatherConstantSetEQs(Cond, Values);
446
447 // Return true to indicate that the condition is true if the CompVal is
448 // equal to one of the constants.
449 return true;
450 } else if (Cond->getOpcode() == Instruction::And) {
451 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000452
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000453 // Return false to indicate that the condition is false if the CompVal is
454 // equal to one of the constants.
455 return false;
456 }
457 return false;
458}
459
460/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
461/// has no side effects, nuke it. If it uses any instructions that become dead
462/// because the instruction is now gone, nuke them too.
463static void ErasePossiblyDeadInstructionTree(Instruction *I) {
Chris Lattnerc9009d92006-08-03 21:40:24 +0000464 if (!isInstructionTriviallyDead(I)) return;
465
466 std::vector<Instruction*> InstrsToInspect;
467 InstrsToInspect.push_back(I);
468
469 while (!InstrsToInspect.empty()) {
470 I = InstrsToInspect.back();
471 InstrsToInspect.pop_back();
472
473 if (!isInstructionTriviallyDead(I)) continue;
474
475 // If I is in the work list multiple times, remove previous instances.
476 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
477 if (InstrsToInspect[i] == I) {
478 InstrsToInspect.erase(InstrsToInspect.begin()+i);
479 --i, --e;
480 }
481
482 // Add operands of dead instruction to worklist.
483 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
484 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
485 InstrsToInspect.push_back(OpI);
486
487 // Remove dead instruction.
488 I->eraseFromParent();
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000489 }
490}
491
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000492// isValueEqualityComparison - Return true if the specified terminator checks to
493// see if a value is equal to constant integer value.
494static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattnera64923a2004-03-16 19:45:22 +0000495 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
496 // Do not permit merging of large switch instructions into their
497 // predecessors unless there is only one predecessor.
498 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
499 pred_end(SI->getParent())) > 128)
500 return 0;
501
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000502 return SI->getCondition();
Chris Lattnera64923a2004-03-16 19:45:22 +0000503 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000504 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
505 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000506 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
507 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
508 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
509 isa<ConstantInt>(ICI->getOperand(1)))
510 return ICI->getOperand(0);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000511 return 0;
512}
513
514// Given a value comparison instruction, decode all of the 'cases' that it
515// represents and return the 'default' block.
516static BasicBlock *
Misha Brukmanb1c93172005-04-21 23:48:37 +0000517GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000518 std::vector<std::pair<ConstantInt*,
519 BasicBlock*> > &Cases) {
520 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
521 Cases.reserve(SI->getNumCases());
522 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnercc6d75f2005-02-26 18:33:28 +0000523 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000524 return SI->getDefaultDest();
525 }
526
527 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000528 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
529 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
530 BI->getSuccessor(ICI->getPredicate() ==
531 ICmpInst::ICMP_NE)));
532 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000533}
534
535
Chris Lattner1cca9592005-02-24 06:17:52 +0000536// EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
537// in the list that match the specified block.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000538static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner1cca9592005-02-24 06:17:52 +0000539 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
540 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
541 if (Cases[i].second == BB) {
542 Cases.erase(Cases.begin()+i);
543 --i; --e;
544 }
545}
546
547// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
548// well.
549static bool
550ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
551 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
552 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
553
554 // Make V1 be smaller than V2.
555 if (V1->size() > V2->size())
556 std::swap(V1, V2);
557
558 if (V1->size() == 0) return false;
559 if (V1->size() == 1) {
560 // Just scan V2.
561 ConstantInt *TheVal = (*V1)[0].first;
562 for (unsigned i = 0, e = V2->size(); i != e; ++i)
563 if (TheVal == (*V2)[i].first)
564 return true;
565 }
566
567 // Otherwise, just sort both lists and compare element by element.
568 std::sort(V1->begin(), V1->end());
569 std::sort(V2->begin(), V2->end());
570 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
571 while (i1 != e1 && i2 != e2) {
572 if ((*V1)[i1].first == (*V2)[i2].first)
573 return true;
574 if ((*V1)[i1].first < (*V2)[i2].first)
575 ++i1;
576 else
577 ++i2;
578 }
579 return false;
580}
581
582// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
583// terminator instruction and its block is known to only have a single
584// predecessor block, check to see if that predecessor is also a value
585// comparison with the same value, and if that comparison determines the outcome
586// of this comparison. If so, simplify TI. This does a very limited form of
587// jump threading.
588static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
589 BasicBlock *Pred) {
590 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
591 if (!PredVal) return false; // Not a value comparison in predecessor.
592
593 Value *ThisVal = isValueEqualityComparison(TI);
594 assert(ThisVal && "This isn't a value comparison!!");
595 if (ThisVal != PredVal) return false; // Different predicates.
596
597 // Find out information about when control will move from Pred to TI's block.
598 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
599 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
600 PredCases);
601 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000602
Chris Lattner1cca9592005-02-24 06:17:52 +0000603 // Find information about how control leaves this block.
604 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
605 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
606 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
607
608 // If TI's block is the default block from Pred's comparison, potentially
609 // simplify TI based on this knowledge.
610 if (PredDef == TI->getParent()) {
611 // If we are here, we know that the value is none of those cases listed in
612 // PredCases. If there are any cases in ThisCases that are in PredCases, we
613 // can simplify TI.
614 if (ValuesOverlap(PredCases, ThisCases)) {
615 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
616 // Okay, one of the successors of this condbr is dead. Convert it to a
617 // uncond br.
618 assert(ThisCases.size() == 1 && "Branch can only have one case!");
619 Value *Cond = BTI->getCondition();
620 // Insert the new branch.
621 Instruction *NI = new BranchInst(ThisDef, TI);
622
623 // Remove PHI node entries for the dead edge.
624 ThisCases[0].second->removePredecessor(TI->getParent());
625
Bill Wendling4ae40102006-11-26 10:17:54 +0000626 DOUT << "Threading pred instr: " << *Pred->getTerminator()
627 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner1cca9592005-02-24 06:17:52 +0000628
629 TI->eraseFromParent(); // Nuke the old one.
630 // If condition is now dead, nuke it.
631 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
632 ErasePossiblyDeadInstructionTree(CondI);
633 return true;
634
635 } else {
636 SwitchInst *SI = cast<SwitchInst>(TI);
637 // Okay, TI has cases that are statically dead, prune them away.
638 std::set<Constant*> DeadCases;
639 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
640 DeadCases.insert(PredCases[i].first);
641
Bill Wendling4ae40102006-11-26 10:17:54 +0000642 DOUT << "Threading pred instr: " << *Pred->getTerminator()
643 << "Through successor TI: " << *TI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000644
645 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
646 if (DeadCases.count(SI->getCaseValue(i))) {
647 SI->getSuccessor(i)->removePredecessor(TI->getParent());
648 SI->removeCase(i);
649 }
650
Bill Wendling4ae40102006-11-26 10:17:54 +0000651 DOUT << "Leaving: " << *TI << "\n";
Chris Lattner1cca9592005-02-24 06:17:52 +0000652 return true;
653 }
654 }
655
656 } else {
657 // Otherwise, TI's block must correspond to some matched value. Find out
658 // which value (or set of values) this is.
659 ConstantInt *TIV = 0;
660 BasicBlock *TIBB = TI->getParent();
661 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
662 if (PredCases[i].second == TIBB)
663 if (TIV == 0)
664 TIV = PredCases[i].first;
665 else
666 return false; // Cannot handle multiple values coming to this block.
667 assert(TIV && "No edge from pred to succ?");
668
669 // Okay, we found the one constant that our value can be if we get into TI's
670 // BB. Find out which successor will unconditionally be branched to.
671 BasicBlock *TheRealDest = 0;
672 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
673 if (ThisCases[i].first == TIV) {
674 TheRealDest = ThisCases[i].second;
675 break;
676 }
677
678 // If not handled by any explicit cases, it is handled by the default case.
679 if (TheRealDest == 0) TheRealDest = ThisDef;
680
681 // Remove PHI node entries for dead edges.
682 BasicBlock *CheckEdge = TheRealDest;
683 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
684 if (*SI != CheckEdge)
685 (*SI)->removePredecessor(TIBB);
686 else
687 CheckEdge = 0;
688
689 // Insert the new branch.
690 Instruction *NI = new BranchInst(TheRealDest, TI);
691
Bill Wendling4ae40102006-11-26 10:17:54 +0000692 DOUT << "Threading pred instr: " << *Pred->getTerminator()
693 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner1cca9592005-02-24 06:17:52 +0000694 Instruction *Cond = 0;
695 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
696 Cond = dyn_cast<Instruction>(BI->getCondition());
697 TI->eraseFromParent(); // Nuke the old one.
698
699 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
700 return true;
701 }
702 return false;
703}
704
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000705// FoldValueComparisonIntoPredecessors - The specified terminator is a value
706// equality comparison instruction (either a switch or a branch on "X == c").
707// See if any of the predecessors of the terminator block are value comparisons
708// on the same value. If so, and if safe to do so, fold them together.
709static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
710 BasicBlock *BB = TI->getParent();
711 Value *CV = isValueEqualityComparison(TI); // CondVal
712 assert(CV && "Not a comparison?");
713 bool Changed = false;
714
715 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
716 while (!Preds.empty()) {
717 BasicBlock *Pred = Preds.back();
718 Preds.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000719
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000720 // See if the predecessor is a comparison with the same value.
721 TerminatorInst *PTI = Pred->getTerminator();
722 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
723
724 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
725 // Figure out which 'cases' to copy from SI to PSI.
726 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
727 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
728
729 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
730 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
731
732 // Based on whether the default edge from PTI goes to BB or not, fill in
733 // PredCases and PredDefault with the new switch cases we would like to
734 // build.
735 std::vector<BasicBlock*> NewSuccessors;
736
737 if (PredDefault == BB) {
738 // If this is the default destination from PTI, only the edges in TI
739 // that don't occur in PTI, or that branch to BB will be activated.
740 std::set<ConstantInt*> PTIHandled;
741 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
742 if (PredCases[i].second != BB)
743 PTIHandled.insert(PredCases[i].first);
744 else {
745 // The default destination is BB, we don't need explicit targets.
746 std::swap(PredCases[i], PredCases.back());
747 PredCases.pop_back();
748 --i; --e;
749 }
750
751 // Reconstruct the new switch statement we will be building.
752 if (PredDefault != BBDefault) {
753 PredDefault->removePredecessor(Pred);
754 PredDefault = BBDefault;
755 NewSuccessors.push_back(BBDefault);
756 }
757 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
758 if (!PTIHandled.count(BBCases[i].first) &&
759 BBCases[i].second != BBDefault) {
760 PredCases.push_back(BBCases[i]);
761 NewSuccessors.push_back(BBCases[i].second);
762 }
763
764 } else {
765 // If this is not the default destination from PSI, only the edges
766 // in SI that occur in PSI with a destination of BB will be
767 // activated.
768 std::set<ConstantInt*> PTIHandled;
769 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
770 if (PredCases[i].second == BB) {
771 PTIHandled.insert(PredCases[i].first);
772 std::swap(PredCases[i], PredCases.back());
773 PredCases.pop_back();
774 --i; --e;
775 }
776
777 // Okay, now we know which constants were sent to BB from the
778 // predecessor. Figure out where they will all go now.
779 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
780 if (PTIHandled.count(BBCases[i].first)) {
781 // If this is one we are capable of getting...
782 PredCases.push_back(BBCases[i]);
783 NewSuccessors.push_back(BBCases[i].second);
784 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
785 }
786
787 // If there are any constants vectored to BB that TI doesn't handle,
788 // they must go to the default destination of TI.
789 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
790 E = PTIHandled.end(); I != E; ++I) {
791 PredCases.push_back(std::make_pair(*I, BBDefault));
792 NewSuccessors.push_back(BBDefault);
793 }
794 }
795
796 // Okay, at this point, we know which new successor Pred will get. Make
797 // sure we update the number of entries in the PHI nodes for these
798 // successors.
799 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
800 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
801
802 // Now that the successors are updated, create the new Switch instruction.
Chris Lattnera35dfce2005-01-29 00:38:26 +0000803 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000804 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
805 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner3215bb62005-01-01 16:02:12 +0000806
807 Instruction *DeadCond = 0;
808 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
809 // If PTI is a branch, remember the condition.
810 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000811 Pred->getInstList().erase(PTI);
812
Chris Lattner3215bb62005-01-01 16:02:12 +0000813 // If the condition is dead now, remove the instruction tree.
814 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
815
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000816 // Okay, last check. If BB is still a successor of PSI, then we must
817 // have an infinite loop case. If so, add an infinitely looping block
818 // to handle the case to preserve the behavior of the code.
819 BasicBlock *InfLoopBlock = 0;
820 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
821 if (NewSI->getSuccessor(i) == BB) {
822 if (InfLoopBlock == 0) {
823 // Insert it at the end of the loop, because it's either code,
824 // or it won't matter if it's hot. :)
825 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
826 new BranchInst(InfLoopBlock, InfLoopBlock);
827 }
828 NewSI->setSuccessor(i, InfLoopBlock);
829 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000830
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000831 Changed = true;
832 }
833 }
834 return Changed;
835}
836
Chris Lattnerd683bdd2005-08-03 17:59:45 +0000837/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +0000838/// BB2, hoist any common code in the two blocks up into the branch block. The
839/// caller of this function guarantees that BI's block dominates BB1 and BB2.
840static bool HoistThenElseCodeToIf(BranchInst *BI) {
841 // This does very trivial matching, with limited scanning, to find identical
842 // instructions in the two blocks. In particular, we don't want to get into
843 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
844 // such, we currently just scan for obviously identical instructions in an
845 // identical order.
846 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
847 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
848
849 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
Reid Spencer266e42b2006-12-23 06:05:41 +0000850 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
851 isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
Chris Lattner389cfac2004-11-30 00:29:14 +0000852 return false;
853
854 // If we get here, we can hoist at least one instruction.
855 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +0000856
857 do {
858 // If we are hoisting the terminator instruction, don't move one (making a
859 // broken BB), instead clone it, and remove BI.
860 if (isa<TerminatorInst>(I1))
861 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000862
Chris Lattner389cfac2004-11-30 00:29:14 +0000863 // For a normal instruction, we just move one to right before the branch,
864 // then replace all uses of the other with the first. Finally, we remove
865 // the now redundant second instruction.
866 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
867 if (!I2->use_empty())
868 I2->replaceAllUsesWith(I1);
869 BB2->getInstList().erase(I2);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000870
Chris Lattner389cfac2004-11-30 00:29:14 +0000871 I1 = BB1->begin();
872 I2 = BB2->begin();
Chris Lattner389cfac2004-11-30 00:29:14 +0000873 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
874
875 return true;
876
877HoistTerminator:
878 // Okay, it is safe to hoist the terminator.
879 Instruction *NT = I1->clone();
880 BIParent->getInstList().insert(BI, NT);
881 if (NT->getType() != Type::VoidTy) {
882 I1->replaceAllUsesWith(NT);
883 I2->replaceAllUsesWith(NT);
884 NT->setName(I1->getName());
885 }
886
887 // Hoisting one of the terminators from our successor is a great thing.
888 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
889 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
890 // nodes, so we insert select instruction to compute the final result.
891 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
892 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
893 PHINode *PN;
894 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +0000895 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +0000896 Value *BB1V = PN->getIncomingValueForBlock(BB1);
897 Value *BB2V = PN->getIncomingValueForBlock(BB2);
898 if (BB1V != BB2V) {
899 // These values do not agree. Insert a select instruction before NT
900 // that determines the right value.
901 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
902 if (SI == 0)
903 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
904 BB1V->getName()+"."+BB2V->getName(), NT);
905 // Make the PHI node use the select for all incoming values for BB1/BB2
906 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
907 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
908 PN->setIncomingValue(i, SI);
909 }
910 }
911 }
912
913 // Update any PHI nodes in our new successors.
914 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
915 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000916
Chris Lattner389cfac2004-11-30 00:29:14 +0000917 BI->eraseFromParent();
918 return true;
919}
920
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000921/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
922/// across this block.
923static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
924 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +0000925 unsigned Size = 0;
926
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000927 // If this basic block contains anything other than a PHI (which controls the
928 // branch) and branch itself, bail out. FIXME: improve this in the future.
Chris Lattner6c701062005-09-20 01:48:40 +0000929 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
930 if (Size > 10) return false; // Don't clone large BB's.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000931
Chris Lattner6c701062005-09-20 01:48:40 +0000932 // We can only support instructions that are do not define values that are
933 // live outside of the current basic block.
934 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
935 UI != E; ++UI) {
936 Instruction *U = cast<Instruction>(*UI);
937 if (U->getParent() != BB || isa<PHINode>(U)) return false;
938 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000939
940 // Looks ok, continue checking.
941 }
Chris Lattner6c701062005-09-20 01:48:40 +0000942
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000943 return true;
944}
945
Chris Lattner748f9032005-09-19 23:49:37 +0000946/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
947/// that is defined in the same block as the branch and if any PHI entries are
948/// constants, thread edges corresponding to that entry to be branches to their
949/// ultimate destination.
950static bool FoldCondBranchOnPHI(BranchInst *BI) {
951 BasicBlock *BB = BI->getParent();
952 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +0000953 // NOTE: we currently cannot transform this case if the PHI node is used
954 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000955 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
956 return false;
Chris Lattner748f9032005-09-19 23:49:37 +0000957
958 // Degenerate case of a single entry PHI.
959 if (PN->getNumIncomingValues() == 1) {
960 if (PN->getIncomingValue(0) != PN)
961 PN->replaceAllUsesWith(PN->getIncomingValue(0));
962 else
963 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
964 PN->eraseFromParent();
965 return true;
966 }
967
968 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000969 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattner748f9032005-09-19 23:49:37 +0000970
971 // Okay, this is a simple enough basic block. See if any phi values are
972 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000973 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
974 ConstantInt *CB;
975 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
Reid Spencer542964f2007-01-11 18:21:29 +0000976 CB->getType() == Type::Int1Ty) {
Chris Lattner748f9032005-09-19 23:49:37 +0000977 // Okay, we now know that all edges from PredBB should be revectored to
978 // branch to RealDest.
979 BasicBlock *PredBB = PN->getIncomingBlock(i);
Reid Spencercddc9df2007-01-12 04:24:46 +0000980 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Chris Lattner748f9032005-09-19 23:49:37 +0000981
Chris Lattner6c701062005-09-20 01:48:40 +0000982 if (RealDest == BB) continue; // Skip self loops.
Chris Lattner748f9032005-09-19 23:49:37 +0000983
Chris Lattner6c701062005-09-20 01:48:40 +0000984 // The dest block might have PHI nodes, other predecessors and other
985 // difficult cases. Instead of being smart about this, just insert a new
986 // block that jumps to the destination block, effectively splitting
987 // the edge we are about to create.
988 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
989 RealDest->getParent(), RealDest);
990 new BranchInst(RealDest, EdgeBB);
991 PHINode *PN;
992 for (BasicBlock::iterator BBI = RealDest->begin();
993 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
994 Value *V = PN->getIncomingValueForBlock(BB);
995 PN->addIncoming(V, EdgeBB);
996 }
997
998 // BB may have instructions that are being threaded over. Clone these
999 // instructions into EdgeBB. We know that there will be no uses of the
1000 // cloned instructions outside of EdgeBB.
1001 BasicBlock::iterator InsertPt = EdgeBB->begin();
1002 std::map<Value*, Value*> TranslateMap; // Track translated values.
1003 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1004 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1005 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1006 } else {
1007 // Clone the instruction.
1008 Instruction *N = BBI->clone();
1009 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1010
1011 // Update operands due to translation.
1012 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1013 std::map<Value*, Value*>::iterator PI =
1014 TranslateMap.find(N->getOperand(i));
1015 if (PI != TranslateMap.end())
1016 N->setOperand(i, PI->second);
1017 }
1018
1019 // Check for trivial simplification.
1020 if (Constant *C = ConstantFoldInstruction(N)) {
Chris Lattner6c701062005-09-20 01:48:40 +00001021 TranslateMap[BBI] = C;
1022 delete N; // Constant folded away, don't need actual inst
1023 } else {
1024 // Insert the new instruction into its new home.
1025 EdgeBB->getInstList().insert(InsertPt, N);
1026 if (!BBI->use_empty())
1027 TranslateMap[BBI] = N;
1028 }
1029 }
1030 }
1031
Chris Lattner748f9032005-09-19 23:49:37 +00001032 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattner6c701062005-09-20 01:48:40 +00001033 // to EdgeBB instead.
Chris Lattner748f9032005-09-19 23:49:37 +00001034 TerminatorInst *PredBBTI = PredBB->getTerminator();
1035 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1036 if (PredBBTI->getSuccessor(i) == BB) {
1037 BB->removePredecessor(PredBB);
Chris Lattner6c701062005-09-20 01:48:40 +00001038 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattner748f9032005-09-19 23:49:37 +00001039 }
1040
Chris Lattner748f9032005-09-19 23:49:37 +00001041 // Recurse, simplifying any other constants.
1042 return FoldCondBranchOnPHI(BI) | true;
1043 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00001044 }
Chris Lattner748f9032005-09-19 23:49:37 +00001045
1046 return false;
1047}
1048
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001049/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1050/// PHI node, see if we can eliminate it.
1051static bool FoldTwoEntryPHINode(PHINode *PN) {
1052 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1053 // statement", which has a very simple dominance structure. Basically, we
1054 // are trying to find the condition that is being branched on, which
1055 // subsequently causes this merge to happen. We really want control
1056 // dependence information for this check, but simplifycfg can't keep it up
1057 // to date, and this catches most of the cases we care about anyway.
1058 //
1059 BasicBlock *BB = PN->getParent();
1060 BasicBlock *IfTrue, *IfFalse;
1061 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1062 if (!IfCond) return false;
1063
Chris Lattner95adf8f12006-11-18 19:19:36 +00001064 // Okay, we found that we can merge this two-entry phi node into a select.
1065 // Doing so would require us to fold *all* two entry phi nodes in this block.
1066 // At some point this becomes non-profitable (particularly if the target
1067 // doesn't support cmov's). Only do this transformation if there are two or
1068 // fewer PHI nodes in this block.
1069 unsigned NumPhis = 0;
1070 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1071 if (NumPhis > 2)
1072 return false;
1073
Bill Wendling4ae40102006-11-26 10:17:54 +00001074 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1075 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001076
1077 // Loop over the PHI's seeing if we can promote them all to select
1078 // instructions. While we are at it, keep track of the instructions
1079 // that need to be moved to the dominating block.
1080 std::set<Instruction*> AggressiveInsts;
1081
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001082 BasicBlock::iterator AfterPHIIt = BB->begin();
1083 while (isa<PHINode>(AfterPHIIt)) {
1084 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1085 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1086 if (PN->getIncomingValue(0) != PN)
1087 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1088 else
1089 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1090 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1091 &AggressiveInsts) ||
1092 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1093 &AggressiveInsts)) {
Chris Lattner3a978bf2005-09-23 07:23:18 +00001094 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001095 }
1096 }
1097
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001098 // If we all PHI nodes are promotable, check to make sure that all
1099 // instructions in the predecessor blocks can be promoted as well. If
1100 // not, we won't be able to get rid of the control flow, so it's not
1101 // worth promoting to select instructions.
1102 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1103 PN = cast<PHINode>(BB->begin());
1104 BasicBlock *Pred = PN->getIncomingBlock(0);
1105 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1106 IfBlock1 = Pred;
1107 DomBlock = *pred_begin(Pred);
1108 for (BasicBlock::iterator I = Pred->begin();
1109 !isa<TerminatorInst>(I); ++I)
1110 if (!AggressiveInsts.count(I)) {
1111 // This is not an aggressive instruction that we can promote.
1112 // Because of this, we won't be able to get rid of the control
1113 // flow, so the xform is not worth it.
1114 return false;
1115 }
1116 }
1117
1118 Pred = PN->getIncomingBlock(1);
1119 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1120 IfBlock2 = Pred;
1121 DomBlock = *pred_begin(Pred);
1122 for (BasicBlock::iterator I = Pred->begin();
1123 !isa<TerminatorInst>(I); ++I)
1124 if (!AggressiveInsts.count(I)) {
1125 // This is not an aggressive instruction that we can promote.
1126 // Because of this, we won't be able to get rid of the control
1127 // flow, so the xform is not worth it.
1128 return false;
1129 }
1130 }
1131
1132 // If we can still promote the PHI nodes after this gauntlet of tests,
1133 // do all of the PHI's now.
1134
1135 // Move all 'aggressive' instructions, which are defined in the
1136 // conditional parts of the if's up to the dominating block.
1137 if (IfBlock1) {
1138 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1139 IfBlock1->getInstList(),
1140 IfBlock1->begin(),
1141 IfBlock1->getTerminator());
1142 }
1143 if (IfBlock2) {
1144 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1145 IfBlock2->getInstList(),
1146 IfBlock2->begin(),
1147 IfBlock2->getTerminator());
1148 }
1149
1150 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1151 // Change the PHI node into a select instruction.
1152 Value *TrueVal =
1153 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1154 Value *FalseVal =
1155 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1156
1157 std::string Name = PN->getName(); PN->setName("");
1158 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1159 Name, AfterPHIIt));
1160 BB->getInstList().erase(PN);
1161 }
1162 return true;
1163}
Chris Lattner748f9032005-09-19 23:49:37 +00001164
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001165namespace {
1166 /// ConstantIntOrdering - This class implements a stable ordering of constant
1167 /// integers that does not depend on their address. This is important for
1168 /// applications that sort ConstantInt's to ensure uniqueness.
1169 struct ConstantIntOrdering {
1170 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001171 return LHS->getZExtValue() < RHS->getZExtValue();
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001172 }
1173 };
1174}
1175
Chris Lattner466a0492002-05-21 20:50:24 +00001176// SimplifyCFG - This function is used to do simplification of a CFG. For
1177// example, it adjusts branches to branches to eliminate the extra hop, it
1178// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +00001179// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +00001180//
1181// WARNING: The entry node of a function may not be simplified.
1182//
Chris Lattnerdf3c3422004-01-09 06:12:26 +00001183bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00001184 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00001185 Function *M = BB->getParent();
1186
1187 assert(BB && BB->getParent() && "Block not embedded in function!");
1188 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +00001189 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +00001190
Chris Lattner466a0492002-05-21 20:50:24 +00001191 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnera2ab4892004-02-24 07:23:58 +00001192 if (pred_begin(BB) == pred_end(BB) ||
1193 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Bill Wendling4ae40102006-11-26 10:17:54 +00001194 DOUT << "Removing BB: \n" << *BB;
Chris Lattner466a0492002-05-21 20:50:24 +00001195
1196 // Loop through all of our successors and make sure they know that one
1197 // of their predecessors is going away.
Chris Lattner95f16a32005-04-12 18:51:33 +00001198 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1199 SI->removePredecessor(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00001200
1201 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +00001202 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +00001203 // If this instruction is used, replace uses with an arbitrary
Chris Lattnereee90f72005-08-02 23:29:23 +00001204 // value. Because control flow can't get here, we don't care
Misha Brukmanb1c93172005-04-21 23:48:37 +00001205 // what we replace the value with. Note that since this block is
Chris Lattner466a0492002-05-21 20:50:24 +00001206 // unreachable, and all values contained within it must dominate their
1207 // uses, that all uses will eventually be removed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001208 if (!I.use_empty())
Chris Lattnereee90f72005-08-02 23:29:23 +00001209 // Make all users of this instruction use undef instead
1210 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001211
Chris Lattner466a0492002-05-21 20:50:24 +00001212 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +00001213 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +00001214 }
Chris Lattnerfda72b12002-06-25 16:12:52 +00001215 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00001216 return true;
1217 }
1218
Chris Lattner031340a2003-08-17 19:41:53 +00001219 // Check to see if we can constant propagate this terminator instruction
1220 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +00001221 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +00001222
Chris Lattnere42732e2004-02-16 06:35:48 +00001223 // If this is a returning block with only PHI nodes in it, fold the return
1224 // instruction into any unconditional branch predecessors.
Chris Lattner9f0db322004-04-02 18:13:43 +00001225 //
1226 // If any predecessor is a conditional branch that just selects among
1227 // different return values, fold the replace the branch/return with a select
1228 // and return.
Chris Lattnere42732e2004-02-16 06:35:48 +00001229 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1230 BasicBlock::iterator BBI = BB->getTerminator();
1231 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner9f0db322004-04-02 18:13:43 +00001232 // Find predecessors that end with branches.
Chris Lattnere42732e2004-02-16 06:35:48 +00001233 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner9f0db322004-04-02 18:13:43 +00001234 std::vector<BranchInst*> CondBranchPreds;
Chris Lattnere42732e2004-02-16 06:35:48 +00001235 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1236 TerminatorInst *PTI = (*PI)->getTerminator();
1237 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1238 if (BI->isUnconditional())
1239 UncondBranchPreds.push_back(*PI);
Chris Lattner9f0db322004-04-02 18:13:43 +00001240 else
1241 CondBranchPreds.push_back(BI);
Chris Lattnere42732e2004-02-16 06:35:48 +00001242 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001243
Chris Lattnere42732e2004-02-16 06:35:48 +00001244 // If we found some, do the transformation!
1245 if (!UncondBranchPreds.empty()) {
1246 while (!UncondBranchPreds.empty()) {
1247 BasicBlock *Pred = UncondBranchPreds.back();
Bill Wendling4ae40102006-11-26 10:17:54 +00001248 DOUT << "FOLDING: " << *BB
1249 << "INTO UNCOND BRANCH PRED: " << *Pred;
Chris Lattnere42732e2004-02-16 06:35:48 +00001250 UncondBranchPreds.pop_back();
1251 Instruction *UncondBranch = Pred->getTerminator();
1252 // Clone the return and add it to the end of the predecessor.
1253 Instruction *NewRet = RI->clone();
1254 Pred->getInstList().push_back(NewRet);
1255
1256 // If the return instruction returns a value, and if the value was a
1257 // PHI node in "BB", propagate the right value into the return.
1258 if (NewRet->getNumOperands() == 1)
1259 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1260 if (PN->getParent() == BB)
1261 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1262 // Update any PHI nodes in the returning block to realize that we no
1263 // longer branch to them.
1264 BB->removePredecessor(Pred);
1265 Pred->getInstList().erase(UncondBranch);
1266 }
1267
1268 // If we eliminated all predecessors of the block, delete the block now.
1269 if (pred_begin(BB) == pred_end(BB))
1270 // We know there are no successors, so just nuke the block.
1271 M->getBasicBlockList().erase(BB);
1272
Chris Lattnere42732e2004-02-16 06:35:48 +00001273 return true;
1274 }
Chris Lattner9f0db322004-04-02 18:13:43 +00001275
1276 // Check out all of the conditional branches going to this return
1277 // instruction. If any of them just select between returns, change the
1278 // branch itself into a select/return pair.
1279 while (!CondBranchPreds.empty()) {
1280 BranchInst *BI = CondBranchPreds.back();
1281 CondBranchPreds.pop_back();
1282 BasicBlock *TrueSucc = BI->getSuccessor(0);
1283 BasicBlock *FalseSucc = BI->getSuccessor(1);
1284 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1285
1286 // Check to see if the non-BB successor is also a return block.
1287 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1288 // Check to see if there are only PHI instructions in this block.
1289 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1290 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1291 // Okay, we found a branch that is going to two return nodes. If
1292 // there is no return value for this function, just change the
1293 // branch into a return.
1294 if (RI->getNumOperands() == 0) {
1295 TrueSucc->removePredecessor(BI->getParent());
1296 FalseSucc->removePredecessor(BI->getParent());
1297 new ReturnInst(0, BI);
1298 BI->getParent()->getInstList().erase(BI);
1299 return true;
1300 }
1301
1302 // Otherwise, figure out what the true and false return values are
1303 // so we can insert a new select instruction.
1304 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1305 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1306
1307 // Unwrap any PHI nodes in the return blocks.
1308 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1309 if (TVPN->getParent() == TrueSucc)
1310 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1311 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1312 if (FVPN->getParent() == FalseSucc)
1313 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1314
Chris Lattnerb8b11592006-10-20 00:42:07 +00001315 // In order for this transformation to be safe, we must be able to
1316 // unconditionally execute both operands to the return. This is
1317 // normally the case, but we could have a potentially-trapping
1318 // constant expression that prevents this transformation from being
1319 // safe.
1320 if ((!isa<ConstantExpr>(TrueValue) ||
1321 !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1322 (!isa<ConstantExpr>(TrueValue) ||
1323 !cast<ConstantExpr>(TrueValue)->canTrap())) {
1324 TrueSucc->removePredecessor(BI->getParent());
1325 FalseSucc->removePredecessor(BI->getParent());
Chris Lattnereed034b2004-04-02 18:15:10 +00001326
Chris Lattnerb8b11592006-10-20 00:42:07 +00001327 // Insert a new select instruction.
1328 Value *NewRetVal;
1329 Value *BrCond = BI->getCondition();
1330 if (TrueValue != FalseValue)
1331 NewRetVal = new SelectInst(BrCond, TrueValue,
1332 FalseValue, "retval", BI);
1333 else
1334 NewRetVal = TrueValue;
1335
Bill Wendling4ae40102006-11-26 10:17:54 +00001336 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1337 << "\n " << *BI << "Select = " << *NewRetVal
1338 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
Chris Lattner879ce782004-09-29 05:43:32 +00001339
Chris Lattnerb8b11592006-10-20 00:42:07 +00001340 new ReturnInst(NewRetVal, BI);
1341 BI->eraseFromParent();
1342 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1343 if (isInstructionTriviallyDead(BrCondI))
1344 BrCondI->eraseFromParent();
1345 return true;
1346 }
Chris Lattner9f0db322004-04-02 18:13:43 +00001347 }
1348 }
1349 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001350 }
Reid Spencerde46e482006-11-02 20:25:50 +00001351 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattner3cd98f02004-02-24 05:54:22 +00001352 // Check to see if the first instruction in this block is just an unwind.
1353 // If so, replace any invoke instructions which use this as an exception
Chris Lattner5823ac12004-07-20 01:17:38 +00001354 // destination with call instructions, and any unconditional branch
1355 // predecessor with an unwind.
Chris Lattner3cd98f02004-02-24 05:54:22 +00001356 //
1357 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1358 while (!Preds.empty()) {
1359 BasicBlock *Pred = Preds.back();
Chris Lattner5823ac12004-07-20 01:17:38 +00001360 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1361 if (BI->isUnconditional()) {
1362 Pred->getInstList().pop_back(); // nuke uncond branch
1363 new UnwindInst(Pred); // Use unwind.
1364 Changed = true;
1365 }
1366 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattner3cd98f02004-02-24 05:54:22 +00001367 if (II->getUnwindDest() == BB) {
1368 // Insert a new branch instruction before the invoke, because this
1369 // is now a fall through...
1370 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1371 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001372
Chris Lattner3cd98f02004-02-24 05:54:22 +00001373 // Insert the call now...
1374 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1375 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1376 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001377 CI->setCallingConv(II->getCallingConv());
Chris Lattner3cd98f02004-02-24 05:54:22 +00001378 // If the invoke produced a value, the Call now does instead
1379 II->replaceAllUsesWith(CI);
1380 delete II;
1381 Changed = true;
1382 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001383
Chris Lattner3cd98f02004-02-24 05:54:22 +00001384 Preds.pop_back();
1385 }
Chris Lattner90ea78e2004-02-24 16:09:21 +00001386
1387 // If this block is now dead, remove it.
1388 if (pred_begin(BB) == pred_end(BB)) {
1389 // We know there are no successors, so just nuke the block.
1390 M->getBasicBlockList().erase(BB);
1391 return true;
1392 }
1393
Chris Lattner1cca9592005-02-24 06:17:52 +00001394 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1395 if (isValueEqualityComparison(SI)) {
1396 // If we only have one predecessor, and if it is a branch on this value,
1397 // see if that predecessor totally determines the outcome of this switch.
1398 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1399 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1400 return SimplifyCFG(BB) || 1;
1401
1402 // If the block only contains the switch, see if we can fold the block
1403 // away into any preds.
1404 if (SI == &BB->front())
1405 if (FoldValueComparisonIntoPredecessors(SI))
1406 return SimplifyCFG(BB) || 1;
1407 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001408 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner733d6702005-08-03 00:11:16 +00001409 if (BI->isUnconditional()) {
1410 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1411 while (isa<PHINode>(*BBI)) ++BBI;
1412
1413 BasicBlock *Succ = BI->getSuccessor(0);
1414 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1415 Succ != BB) // Don't hurt infinite loops!
1416 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1417 return 1;
1418
1419 } else { // Conditional branch
Reid Spencerde46e482006-11-02 20:25:50 +00001420 if (isValueEqualityComparison(BI)) {
Chris Lattner1cca9592005-02-24 06:17:52 +00001421 // If we only have one predecessor, and if it is a branch on this value,
1422 // see if that predecessor totally determines the outcome of this
1423 // switch.
1424 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1425 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1426 return SimplifyCFG(BB) || 1;
1427
Chris Lattner2e93c422004-05-01 23:35:43 +00001428 // This block must be empty, except for the setcond inst, if it exists.
1429 BasicBlock::iterator I = BB->begin();
1430 if (&*I == BI ||
1431 (&*I == cast<Instruction>(BI->getCondition()) &&
1432 &*++I == BI))
1433 if (FoldValueComparisonIntoPredecessors(BI))
1434 return SimplifyCFG(BB) | true;
1435 }
Chris Lattner748f9032005-09-19 23:49:37 +00001436
1437 // If this is a branch on a phi node in the current block, thread control
1438 // through this block if any PHI node entries are constants.
1439 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1440 if (PN->getParent() == BI->getParent())
1441 if (FoldCondBranchOnPHI(BI))
1442 return SimplifyCFG(BB) | true;
Chris Lattner2e93c422004-05-01 23:35:43 +00001443
1444 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1445 // branches to us and one of our successors, fold the setcc into the
1446 // predecessor and use logical operations to pick the right destination.
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001447 BasicBlock *TrueDest = BI->getSuccessor(0);
1448 BasicBlock *FalseDest = BI->getSuccessor(1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001449 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
1450 if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1451 Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001452 Cond->getNext() == BI && Cond->hasOneUse() &&
1453 TrueDest != BB && FalseDest != BB)
Chris Lattner2e93c422004-05-01 23:35:43 +00001454 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1455 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner1e94ed62004-05-02 01:00:44 +00001456 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001457 BasicBlock *PredBlock = *PI;
Chris Lattner2e93c422004-05-01 23:35:43 +00001458 if (PBI->getSuccessor(0) == FalseDest ||
1459 PBI->getSuccessor(1) == TrueDest) {
1460 // Invert the predecessors condition test (xor it with true),
1461 // which allows us to write this code once.
1462 Value *NewCond =
1463 BinaryOperator::createNot(PBI->getCondition(),
1464 PBI->getCondition()->getName()+".not", PBI);
1465 PBI->setCondition(NewCond);
1466 BasicBlock *OldTrue = PBI->getSuccessor(0);
1467 BasicBlock *OldFalse = PBI->getSuccessor(1);
1468 PBI->setSuccessor(0, OldFalse);
1469 PBI->setSuccessor(1, OldTrue);
1470 }
1471
Chris Lattnerd9566512006-02-18 00:33:17 +00001472 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1473 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001474 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattner2e93c422004-05-01 23:35:43 +00001475 // two conditions together.
1476 Instruction *New = Cond->clone();
1477 New->setName(Cond->getName());
1478 Cond->setName(Cond->getName()+".old");
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001479 PredBlock->getInstList().insert(PBI, New);
Chris Lattner2e93c422004-05-01 23:35:43 +00001480 Instruction::BinaryOps Opcode =
1481 PBI->getSuccessor(0) == TrueDest ?
1482 Instruction::Or : Instruction::And;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001483 Value *NewCond =
Chris Lattner2e93c422004-05-01 23:35:43 +00001484 BinaryOperator::create(Opcode, PBI->getCondition(),
1485 New, "bothcond", PBI);
1486 PBI->setCondition(NewCond);
1487 if (PBI->getSuccessor(0) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001488 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001489 PBI->setSuccessor(0, TrueDest);
1490 }
1491 if (PBI->getSuccessor(1) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001492 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001493 PBI->setSuccessor(1, FalseDest);
1494 }
1495 return SimplifyCFG(BB) | 1;
1496 }
1497 }
Chris Lattner2e93c422004-05-01 23:35:43 +00001498
Chris Lattnerc59a3712005-09-23 18:47:20 +00001499 // Scan predessor blocks for conditional branchs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001500 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1501 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnerc59a3712005-09-23 18:47:20 +00001502 if (PBI != BI && PBI->isConditional()) {
1503
1504 // If this block ends with a branch instruction, and if there is a
Reid Spencercddc9df2007-01-12 04:24:46 +00001505 // predecessor that ends on a branch of the same condition, make
1506 // this conditional branch redundant.
Chris Lattnerc59a3712005-09-23 18:47:20 +00001507 if (PBI->getCondition() == BI->getCondition() &&
1508 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1509 // Okay, the outcome of this conditional branch is statically
1510 // knowable. If this block had a single pred, handle specially.
1511 if (BB->getSinglePredecessor()) {
1512 // Turn this into a branch on constant.
1513 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Reid Spencercddc9df2007-01-12 04:24:46 +00001514 BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
Chris Lattnerc59a3712005-09-23 18:47:20 +00001515 return SimplifyCFG(BB); // Nuke the branch on constant.
1516 }
1517
Reid Spencercddc9df2007-01-12 04:24:46 +00001518 // Otherwise, if there are multiple predecessors, insert a PHI
1519 // that merges in the constant and simplify the block result.
Chris Lattnerc59a3712005-09-23 18:47:20 +00001520 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Reid Spencer542964f2007-01-11 18:21:29 +00001521 PHINode *NewPN = new PHINode(Type::Int1Ty,
Reid Spencercddc9df2007-01-12 04:24:46 +00001522 BI->getCondition()->getName()+".pr",
1523 BB->begin());
Chris Lattnerc59a3712005-09-23 18:47:20 +00001524 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1525 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1526 PBI != BI && PBI->isConditional() &&
1527 PBI->getCondition() == BI->getCondition() &&
1528 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1529 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Reid Spencercddc9df2007-01-12 04:24:46 +00001530 NewPN->addIncoming(ConstantInt::get(Type::Int1Ty,
1531 CondIsTrue), *PI);
Chris Lattnerc59a3712005-09-23 18:47:20 +00001532 } else {
1533 NewPN->addIncoming(BI->getCondition(), *PI);
1534 }
1535
1536 BI->setCondition(NewPN);
1537 // This will thread the branch.
1538 return SimplifyCFG(BB) | true;
1539 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001540 }
1541
Chris Lattnerc59a3712005-09-23 18:47:20 +00001542 // If this is a conditional branch in an empty block, and if any
1543 // predecessors is a conditional branch to one of our destinations,
1544 // fold the conditions into logical ops and one cond br.
1545 if (&BB->front() == BI) {
1546 int PBIOp, BIOp;
1547 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1548 PBIOp = BIOp = 0;
1549 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1550 PBIOp = 0; BIOp = 1;
1551 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1552 PBIOp = 1; BIOp = 0;
1553 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1554 PBIOp = BIOp = 1;
1555 } else {
1556 PBIOp = BIOp = -1;
1557 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001558
Chris Lattnerd9566512006-02-18 00:33:17 +00001559 // Check to make sure that the other destination of this branch
1560 // isn't BB itself. If so, this is an infinite loop that will
1561 // keep getting unwound.
1562 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1563 PBIOp = BIOp = -1;
Chris Lattner95adf8f12006-11-18 19:19:36 +00001564
1565 // Do not perform this transformation if it would require
1566 // insertion of a large number of select instructions. For targets
1567 // without predication/cmovs, this is a big pessimization.
1568 if (PBIOp != -1) {
1569 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1570
1571 unsigned NumPhis = 0;
1572 for (BasicBlock::iterator II = CommonDest->begin();
1573 isa<PHINode>(II); ++II, ++NumPhis) {
1574 if (NumPhis > 2) {
1575 // Disable this xform.
1576 PBIOp = -1;
1577 break;
1578 }
1579 }
1580 }
Chris Lattnerb5c9d7a2006-06-12 20:18:01 +00001581
Chris Lattnerc59a3712005-09-23 18:47:20 +00001582 // Finally, if everything is ok, fold the branches to logical ops.
1583 if (PBIOp != -1) {
1584 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1585 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1586
Chris Lattnerb5c9d7a2006-06-12 20:18:01 +00001587 // If OtherDest *is* BB, then this is a basic block with just
1588 // a conditional branch in it, where one edge (OtherDesg) goes
1589 // back to the block. We know that the program doesn't get
1590 // stuck in the infinite loop, so the condition must be such
1591 // that OtherDest isn't branched through. Forward to CommonDest,
1592 // and avoid an infinite loop at optimizer time.
1593 if (OtherDest == BB)
1594 OtherDest = CommonDest;
1595
Bill Wendling4ae40102006-11-26 10:17:54 +00001596 DOUT << "FOLDING BRs:" << *PBI->getParent()
1597 << "AND: " << *BI->getParent();
Chris Lattnerc59a3712005-09-23 18:47:20 +00001598
1599 // BI may have other predecessors. Because of this, we leave
1600 // it alone, but modify PBI.
1601
1602 // Make sure we get to CommonDest on True&True directions.
1603 Value *PBICond = PBI->getCondition();
1604 if (PBIOp)
1605 PBICond = BinaryOperator::createNot(PBICond,
1606 PBICond->getName()+".not",
1607 PBI);
1608 Value *BICond = BI->getCondition();
1609 if (BIOp)
1610 BICond = BinaryOperator::createNot(BICond,
1611 BICond->getName()+".not",
1612 PBI);
1613 // Merge the conditions.
1614 Value *Cond =
1615 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1616
1617 // Modify PBI to branch on the new condition to the new dests.
1618 PBI->setCondition(Cond);
1619 PBI->setSuccessor(0, CommonDest);
1620 PBI->setSuccessor(1, OtherDest);
1621
1622 // OtherDest may have phi nodes. If so, add an entry from PBI's
1623 // block that are identical to the entries for BI's block.
1624 PHINode *PN;
1625 for (BasicBlock::iterator II = OtherDest->begin();
1626 (PN = dyn_cast<PHINode>(II)); ++II) {
1627 Value *V = PN->getIncomingValueForBlock(BB);
1628 PN->addIncoming(V, PBI->getParent());
1629 }
1630
1631 // We know that the CommonDest already had an edge from PBI to
1632 // it. If it has PHIs though, the PHIs may have different
1633 // entries for BB and PBI's BB. If so, insert a select to make
1634 // them agree.
1635 for (BasicBlock::iterator II = CommonDest->begin();
1636 (PN = dyn_cast<PHINode>(II)); ++II) {
1637 Value * BIV = PN->getIncomingValueForBlock(BB);
1638 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1639 Value *PBIV = PN->getIncomingValue(PBBIdx);
1640 if (BIV != PBIV) {
1641 // Insert a select in PBI to pick the right value.
1642 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1643 PBIV->getName()+".mux", PBI);
1644 PN->setIncomingValue(PBBIdx, NV);
1645 }
1646 }
1647
Bill Wendling4ae40102006-11-26 10:17:54 +00001648 DOUT << "INTO: " << *PBI->getParent();
Chris Lattnerc59a3712005-09-23 18:47:20 +00001649
1650 // This basic block is probably dead. We know it has at least
1651 // one fewer predecessor.
1652 return SimplifyCFG(BB) | true;
1653 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001654 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001655 }
Chris Lattnera2ab4892004-02-24 07:23:58 +00001656 }
Chris Lattner5edb2f32004-10-18 04:07:22 +00001657 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1658 // If there are any instructions immediately before the unreachable that can
1659 // be removed, do so.
1660 Instruction *Unreachable = BB->getTerminator();
1661 while (Unreachable != BB->begin()) {
1662 BasicBlock::iterator BBI = Unreachable;
1663 --BBI;
1664 if (isa<CallInst>(BBI)) break;
1665 // Delete this instruction
1666 BB->getInstList().erase(BBI);
1667 Changed = true;
1668 }
1669
1670 // If the unreachable instruction is the first in the block, take a gander
1671 // at all of the predecessors of this instruction, and simplify them.
1672 if (&BB->front() == Unreachable) {
1673 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1674 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1675 TerminatorInst *TI = Preds[i]->getTerminator();
1676
1677 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1678 if (BI->isUnconditional()) {
1679 if (BI->getSuccessor(0) == BB) {
1680 new UnreachableInst(TI);
1681 TI->eraseFromParent();
1682 Changed = true;
1683 }
1684 } else {
1685 if (BI->getSuccessor(0) == BB) {
1686 new BranchInst(BI->getSuccessor(1), BI);
1687 BI->eraseFromParent();
1688 } else if (BI->getSuccessor(1) == BB) {
1689 new BranchInst(BI->getSuccessor(0), BI);
1690 BI->eraseFromParent();
1691 Changed = true;
1692 }
1693 }
1694 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1695 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1696 if (SI->getSuccessor(i) == BB) {
Chris Lattner19f9f322005-05-20 22:19:54 +00001697 BB->removePredecessor(SI->getParent());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001698 SI->removeCase(i);
1699 --i; --e;
1700 Changed = true;
1701 }
1702 // If the default value is unreachable, figure out the most popular
1703 // destination and make it the default.
1704 if (SI->getSuccessor(0) == BB) {
1705 std::map<BasicBlock*, unsigned> Popularity;
1706 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1707 Popularity[SI->getSuccessor(i)]++;
1708
1709 // Find the most popular block.
1710 unsigned MaxPop = 0;
1711 BasicBlock *MaxBlock = 0;
1712 for (std::map<BasicBlock*, unsigned>::iterator
1713 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1714 if (I->second > MaxPop) {
1715 MaxPop = I->second;
1716 MaxBlock = I->first;
1717 }
1718 }
1719 if (MaxBlock) {
1720 // Make this the new default, allowing us to delete any explicit
1721 // edges to it.
1722 SI->setSuccessor(0, MaxBlock);
1723 Changed = true;
1724
Chris Lattner19f9f322005-05-20 22:19:54 +00001725 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1726 // it.
1727 if (isa<PHINode>(MaxBlock->begin()))
1728 for (unsigned i = 0; i != MaxPop-1; ++i)
1729 MaxBlock->removePredecessor(SI->getParent());
1730
Chris Lattner5edb2f32004-10-18 04:07:22 +00001731 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1732 if (SI->getSuccessor(i) == MaxBlock) {
1733 SI->removeCase(i);
1734 --i; --e;
1735 }
1736 }
1737 }
1738 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1739 if (II->getUnwindDest() == BB) {
1740 // Convert the invoke to a call instruction. This would be a good
1741 // place to note that the call does not throw though.
1742 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1743 II->removeFromParent(); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001744
Chris Lattner5edb2f32004-10-18 04:07:22 +00001745 // Insert the call now...
1746 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1747 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1748 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001749 CI->setCallingConv(II->getCallingConv());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001750 // If the invoke produced a value, the Call does now instead.
1751 II->replaceAllUsesWith(CI);
1752 delete II;
1753 Changed = true;
1754 }
1755 }
1756 }
1757
1758 // If this block is now dead, remove it.
1759 if (pred_begin(BB) == pred_end(BB)) {
1760 // We know there are no successors, so just nuke the block.
1761 M->getBasicBlockList().erase(BB);
1762 return true;
1763 }
1764 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001765 }
1766
Chris Lattner466a0492002-05-21 20:50:24 +00001767 // Merge basic blocks into their predecessor if there is only one distinct
1768 // pred, and if there is only one distinct successor of the predecessor, and
1769 // if there are no PHI nodes.
1770 //
Chris Lattner838b8452004-02-11 01:17:07 +00001771 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1772 BasicBlock *OnlyPred = *PI++;
1773 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1774 if (*PI != OnlyPred) {
1775 OnlyPred = 0; // There are multiple different predecessors...
1776 break;
1777 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001778
Chris Lattner838b8452004-02-11 01:17:07 +00001779 BasicBlock *OnlySucc = 0;
1780 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1781 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1782 // Check to see if there is only one distinct successor...
1783 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1784 OnlySucc = BB;
1785 for (; SI != SE; ++SI)
1786 if (*SI != OnlySucc) {
1787 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +00001788 break;
1789 }
Chris Lattner838b8452004-02-11 01:17:07 +00001790 }
1791
1792 if (OnlySucc) {
Bill Wendling4ae40102006-11-26 10:17:54 +00001793 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Chris Lattner838b8452004-02-11 01:17:07 +00001794
1795 // Resolve any PHI nodes at the start of the block. They are all
1796 // guaranteed to have exactly one entry if they exist, unless there are
1797 // multiple duplicate (but guaranteed to be equal) entries for the
1798 // incoming edges. This occurs when there are multiple edges from
1799 // OnlyPred to OnlySucc.
1800 //
1801 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1802 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1803 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +00001804 }
1805
Chris Lattner838b8452004-02-11 01:17:07 +00001806 // Delete the unconditional branch from the predecessor...
1807 OnlyPred->getInstList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001808
Chris Lattner838b8452004-02-11 01:17:07 +00001809 // Move all definitions in the successor to the predecessor...
1810 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001811
Chris Lattner838b8452004-02-11 01:17:07 +00001812 // Make all PHI nodes that referred to BB now refer to Pred as their
1813 // source...
1814 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001815
Chris Lattner838b8452004-02-11 01:17:07 +00001816 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +00001817
Misha Brukmanb1c93172005-04-21 23:48:37 +00001818 // Erase basic block from the function...
Chris Lattner838b8452004-02-11 01:17:07 +00001819 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001820
Chris Lattner838b8452004-02-11 01:17:07 +00001821 // Inherit predecessors name if it exists...
1822 if (!OldName.empty() && !OnlyPred->hasName())
1823 OnlyPred->setName(OldName);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001824
Chris Lattner838b8452004-02-11 01:17:07 +00001825 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00001826 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001827
Chris Lattner389cfac2004-11-30 00:29:14 +00001828 // Otherwise, if this block only has a single predecessor, and if that block
1829 // is a conditional branch, see if we can hoist any code from this block up
1830 // into our predecessor.
1831 if (OnlyPred)
Chris Lattner4fc998d2004-12-10 17:42:31 +00001832 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1833 if (BI->isConditional()) {
1834 // Get the other block.
1835 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1836 PI = pred_begin(OtherBB);
1837 ++PI;
1838 if (PI == pred_end(OtherBB)) {
1839 // We have a conditional branch to two blocks that are only reachable
1840 // from the condbr. We know that the condbr dominates the two blocks,
1841 // so see if there is any identical code in the "then" and "else"
1842 // blocks. If so, we can hoist it up to the branching block.
1843 Changed |= HoistThenElseCodeToIf(BI);
1844 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001845 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001846
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001847 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1848 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1849 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1850 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1851 Instruction *Cond = cast<Instruction>(BI->getCondition());
1852 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1853 // 'setne's and'ed together, collect them.
1854 Value *CompVal = 0;
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001855 std::vector<ConstantInt*> Values;
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001856 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
Chris Lattner03c49532007-01-15 02:27:26 +00001857 if (CompVal && CompVal->getType()->isInteger()) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001858 // There might be duplicate constants in the list, which the switch
1859 // instruction can't handle, remove them now.
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001860 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001861 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001862
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001863 // Figure out which block is which destination.
1864 BasicBlock *DefaultBB = BI->getSuccessor(1);
1865 BasicBlock *EdgeBB = BI->getSuccessor(0);
1866 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001867
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001868 // Create the new switch instruction now.
Chris Lattnera35dfce2005-01-29 00:38:26 +00001869 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001870
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001871 // Add all of the 'cases' to the switch instruction.
1872 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1873 New->addCase(Values[i], EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001874
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001875 // We added edges from PI to the EdgeBB. As such, if there were any
1876 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1877 // the number of edges added.
1878 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer66149462004-09-15 17:06:42 +00001879 isa<PHINode>(BBI); ++BBI) {
1880 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001881 Value *InVal = PN->getIncomingValueForBlock(*PI);
1882 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1883 PN->addIncoming(InVal, *PI);
1884 }
1885
1886 // Erase the old branch instruction.
1887 (*PI)->getInstList().erase(BI);
1888
1889 // Erase the potentially condition tree that was used to computed the
1890 // branch condition.
1891 ErasePossiblyDeadInstructionTree(Cond);
1892 return true;
1893 }
1894 }
1895
Chris Lattner18d1f192004-02-11 03:36:04 +00001896 // If there is a trivial two-entry PHI node in this basic block, and we can
1897 // eliminate it, do so now.
1898 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001899 if (PN->getNumIncomingValues() == 2)
1900 Changed |= FoldTwoEntryPHINode(PN);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001901
Chris Lattner031340a2003-08-17 19:41:53 +00001902 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00001903}