blob: 3b6b77f5fb8a4cab42f0cd51ceeb016ac3ca1dcd [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner01d1ee32002-05-21 20:50:24 +00009//
Chris Lattnerbb190ac2002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner218a8222004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner01d1ee32002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Devang Patel383d7ed2009-02-03 22:12:02 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson0a205a42009-07-05 22:41:43 +000019#include "llvm/LLVMContext.h"
Chris Lattner0d560082004-02-24 05:38:11 +000020#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000021#include "llvm/DerivedTypes.h"
Dale Johannesenf8bc3002009-05-13 18:25:07 +000022#include "llvm/GlobalVariable.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000023#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000028#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng502a4f52008-06-12 21:15:59 +000029#include "llvm/ADT/Statistic.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000030#include <algorithm>
31#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000032#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000033#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Evan Cheng502a4f52008-06-12 21:15:59 +000036STATISTIC(NumSpeculations, "Number of speculative executed instructions");
37
Chris Lattner2bdcb562005-08-03 00:19:45 +000038/// SafeToMergeTerminators - Return true if it is safe to merge these two
39/// terminator instructions together.
40///
41static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
42 if (SI1 == SI2) return false; // Can't merge with self!
43
44 // It is not safe to merge these two switch instructions if they have a common
45 // successor, and if that successor has a PHI node, and if *that* PHI node has
46 // conflicting incoming values from the two switch blocks.
47 BasicBlock *SI1BB = SI1->getParent();
48 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000049 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000050
51 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
52 if (SI1Succs.count(*I))
53 for (BasicBlock::iterator BBI = (*I)->begin();
54 isa<PHINode>(BBI); ++BBI) {
55 PHINode *PN = cast<PHINode>(BBI);
56 if (PN->getIncomingValueForBlock(SI1BB) !=
57 PN->getIncomingValueForBlock(SI2BB))
58 return false;
59 }
60
61 return true;
62}
63
64/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
65/// now be entries in it from the 'NewPred' block. The values that will be
66/// flowing into the PHI nodes will be the same as those coming in from
67/// ExistPred, an existing predecessor of Succ.
68static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
69 BasicBlock *ExistPred) {
70 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
71 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
72 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
73
Chris Lattner093a4382008-07-13 22:23:11 +000074 PHINode *PN;
75 for (BasicBlock::iterator I = Succ->begin();
76 (PN = dyn_cast<PHINode>(I)); ++I)
77 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +000078}
79
Bill Wendling5049fa62009-01-19 23:43:56 +000080/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
81/// almost-empty BB ending in an unconditional branch to Succ, into succ.
82///
83/// Assumption: Succ is the single successor for BB.
84///
Chris Lattner3b3efc72005-08-03 00:29:26 +000085static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000086 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000087
Matthijs Kooijman5e179a22008-05-23 09:09:41 +000088 DOUT << "Looking to fold " << BB->getNameStart() << " into "
89 << Succ->getNameStart() << "\n";
Dale Johannesenf33b1102009-03-19 17:23:29 +000090 // Shortcut, if there is only a single predecessor it must be BB and merging
Matthijs Kooijman5e179a22008-05-23 09:09:41 +000091 // is always safe
92 if (Succ->getSinglePredecessor()) return true;
93
94 typedef SmallPtrSet<Instruction*, 16> InstrSet;
95 InstrSet BBPHIs;
96
97 // Make a list of all phi nodes in BB
98 BasicBlock::iterator BBI = BB->begin();
99 while (isa<PHINode>(*BBI)) BBPHIs.insert(BBI++);
100
101 // Make a list of the predecessors of BB
102 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
103 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
104
105 // Use that list to make another list of common predecessors of BB and Succ
106 BlockSet CommonPreds;
107 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
108 PI != PE; ++PI)
109 if (BBPreds.count(*PI))
110 CommonPreds.insert(*PI);
111
112 // Shortcut, if there are no common predecessors, merging is always safe
Dan Gohmana8c763b2008-08-14 18:13:49 +0000113 if (CommonPreds.empty())
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000114 return true;
115
116 // Look at all the phi nodes in Succ, to see if they present a conflict when
117 // merging these blocks
118 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
119 PHINode *PN = cast<PHINode>(I);
120
121 // If the incoming value from BB is again a PHINode in
122 // BB which has the same incoming value for *PI as PN does, we can
123 // merge the phi nodes and then the blocks can still be merged
124 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
125 if (BBPN && BBPN->getParent() == BB) {
126 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
127 PI != PE; PI++) {
128 if (BBPN->getIncomingValueForBlock(*PI)
129 != PN->getIncomingValueForBlock(*PI)) {
130 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
131 << Succ->getNameStart() << " is conflicting with "
132 << BBPN->getNameStart() << " with regard to common predecessor "
133 << (*PI)->getNameStart() << "\n";
134 return false;
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000135 }
136 }
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000137 // Remove this phinode from the list of phis in BB, since it has been
138 // handled.
139 BBPHIs.erase(BBPN);
140 } else {
141 Value* Val = PN->getIncomingValueForBlock(BB);
142 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
143 PI != PE; PI++) {
144 // See if the incoming value for the common predecessor is equal to the
145 // one for BB, in which case this phi node will not prevent the merging
146 // of the block.
147 if (Val != PN->getIncomingValueForBlock(*PI)) {
148 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
149 << Succ->getNameStart() << " is conflicting with regard to common "
150 << "predecessor " << (*PI)->getNameStart() << "\n";
151 return false;
152 }
153 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000154 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000155 }
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000156
157 // If there are any other phi nodes in BB that don't have a phi node in Succ
158 // to merge with, they must be moved to Succ completely. However, for any
159 // predecessors of Succ, branches will be added to the phi node that just
160 // point to itself. So, for any common predecessors, this must not cause
161 // conflicts.
162 for (InstrSet::iterator I = BBPHIs.begin(), E = BBPHIs.end();
163 I != E; I++) {
164 PHINode *PN = cast<PHINode>(*I);
165 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
166 PI != PE; PI++)
167 if (PN->getIncomingValueForBlock(*PI) != PN) {
168 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
169 << BB->getNameStart() << " is conflicting with regard to common "
170 << "predecessor " << (*PI)->getNameStart() << "\n";
171 return false;
172 }
173 }
174
Chris Lattner8e75ee22005-12-03 18:25:58 +0000175 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000176}
177
Chris Lattner7e663482005-08-03 00:11:16 +0000178/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
179/// branch to Succ, and contains no instructions other than PHI nodes and the
180/// branch. If possible, eliminate BB.
181static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
182 BasicBlock *Succ) {
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000183 // Check to see if merging these blocks would cause conflicts for any of the
184 // phi nodes in BB or Succ. If not, we can safely merge.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000185 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner7e663482005-08-03 00:11:16 +0000186
Bill Wendling0d45a092006-11-26 10:17:54 +0000187 DOUT << "Killing Trivial BB: \n" << *BB;
Chris Lattner7e663482005-08-03 00:11:16 +0000188
Chris Lattner3b3efc72005-08-03 00:29:26 +0000189 if (isa<PHINode>(Succ->begin())) {
190 // If there is more than one pred of succ, and there are PHI nodes in
191 // the successor, then we need to add incoming edges for the PHI nodes
192 //
Chris Lattner82442432008-02-18 07:42:56 +0000193 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner3b3efc72005-08-03 00:29:26 +0000194
195 // Loop over all of the PHI nodes in the successor of BB.
196 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
197 PHINode *PN = cast<PHINode>(I);
198 Value *OldVal = PN->removeIncomingValue(BB, false);
199 assert(OldVal && "No entry in PHI for Pred BB!");
200
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000201 // If this incoming value is one of the PHI nodes in BB, the new entries
202 // in the PHI node are the entries from the old PHI.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000203 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
204 PHINode *OldValPN = cast<PHINode>(OldVal);
205 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000206 // Note that, since we are merging phi nodes and BB and Succ might
207 // have common predecessors, we could end up with a phi node with
208 // identical incoming branches. This will be cleaned up later (and
209 // will trigger asserts if we try to clean it up now, without also
210 // simplifying the corresponding conditional branch).
Chris Lattner3b3efc72005-08-03 00:29:26 +0000211 PN->addIncoming(OldValPN->getIncomingValue(i),
212 OldValPN->getIncomingBlock(i));
213 } else {
Chris Lattner82442432008-02-18 07:42:56 +0000214 // Add an incoming value for each of the new incoming values.
215 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
216 PN->addIncoming(OldVal, BBPreds[i]);
Chris Lattner3b3efc72005-08-03 00:29:26 +0000217 }
218 }
219 }
220
Chris Lattner7e663482005-08-03 00:11:16 +0000221 if (isa<PHINode>(&BB->front())) {
Bill Wendling13524bf2009-01-19 08:46:20 +0000222 SmallVector<BasicBlock*, 16>
223 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
Chris Lattner7e663482005-08-03 00:11:16 +0000224
225 // Move all PHI nodes in BB to Succ if they are alive, otherwise
226 // delete them.
Chris Lattner9e0dad42009-01-19 02:07:32 +0000227 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000228 if (PN->use_empty()) {
229 // Just remove the dead phi. This happens if Succ's PHIs were the only
230 // users of the PHI nodes.
231 PN->eraseFromParent();
Chris Lattner9e0dad42009-01-19 02:07:32 +0000232 continue;
Chris Lattner7e663482005-08-03 00:11:16 +0000233 }
Chris Lattner9e0dad42009-01-19 02:07:32 +0000234
235 // The instruction is alive, so this means that BB must dominate all
236 // predecessors of Succ (Since all uses of the PN are after its
237 // definition, so in Succ or a block dominated by Succ. If a predecessor
238 // of Succ would not be dominated by BB, PN would violate the def before
239 // use SSA demand). Therefore, we can simply move the phi node to the
240 // next block.
241 Succ->getInstList().splice(Succ->begin(),
242 BB->getInstList(), BB->begin());
243
244 // We need to add new entries for the PHI node to account for
245 // predecessors of Succ that the PHI node does not take into
246 // account. At this point, since we know that BB dominated succ and all
247 // of its predecessors, this means that we should any newly added
248 // incoming edges should use the PHI node itself as the value for these
249 // edges, because they are loop back edges.
250 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
251 if (OldSuccPreds[i] != BB)
252 PN->addIncoming(PN, OldSuccPreds[i]);
253 }
Chris Lattner7e663482005-08-03 00:11:16 +0000254 }
255
256 // Everything that jumped to BB now goes to Succ.
Chris Lattner7e663482005-08-03 00:11:16 +0000257 BB->replaceAllUsesWith(Succ);
Chris Lattner86cc4232007-02-11 01:37:51 +0000258 if (!Succ->hasName()) Succ->takeName(BB);
Chris Lattner7e663482005-08-03 00:11:16 +0000259 BB->eraseFromParent(); // Delete the old basic block.
Chris Lattner7e663482005-08-03 00:11:16 +0000260 return true;
261}
262
Chris Lattner723c66d2004-02-11 03:36:04 +0000263/// GetIfCondition - Given a basic block (BB) with two predecessors (and
264/// presumably PHI nodes in it), check to see if the merge at this block is due
265/// to an "if condition". If so, return the boolean condition that determines
266/// which entry into BB will be taken. Also, return by references the block
267/// that will be entered from if the condition is true, and the block that will
268/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000269///
Chris Lattner723c66d2004-02-11 03:36:04 +0000270///
271static Value *GetIfCondition(BasicBlock *BB,
272 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
273 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
274 "Function can only handle blocks with 2 predecessors!");
275 BasicBlock *Pred1 = *pred_begin(BB);
276 BasicBlock *Pred2 = *++pred_begin(BB);
277
278 // We can only handle branches. Other control flow will be lowered to
279 // branches if possible anyway.
280 if (!isa<BranchInst>(Pred1->getTerminator()) ||
281 !isa<BranchInst>(Pred2->getTerminator()))
282 return 0;
283 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
284 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
285
286 // Eliminate code duplication by ensuring that Pred1Br is conditional if
287 // either are.
288 if (Pred2Br->isConditional()) {
289 // If both branches are conditional, we don't have an "if statement". In
290 // reality, we could transform this case, but since the condition will be
291 // required anyway, we stand no chance of eliminating it, so the xform is
292 // probably not profitable.
293 if (Pred1Br->isConditional())
294 return 0;
295
296 std::swap(Pred1, Pred2);
297 std::swap(Pred1Br, Pred2Br);
298 }
299
300 if (Pred1Br->isConditional()) {
301 // If we found a conditional branch predecessor, make sure that it branches
302 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
303 if (Pred1Br->getSuccessor(0) == BB &&
304 Pred1Br->getSuccessor(1) == Pred2) {
305 IfTrue = Pred1;
306 IfFalse = Pred2;
307 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
308 Pred1Br->getSuccessor(1) == BB) {
309 IfTrue = Pred2;
310 IfFalse = Pred1;
311 } else {
312 // We know that one arm of the conditional goes to BB, so the other must
313 // go somewhere unrelated, and this must not be an "if statement".
314 return 0;
315 }
316
317 // The only thing we have to watch out for here is to make sure that Pred2
318 // doesn't have incoming edges from other blocks. If it does, the condition
319 // doesn't dominate BB.
320 if (++pred_begin(Pred2) != pred_end(Pred2))
321 return 0;
322
323 return Pred1Br->getCondition();
324 }
325
326 // Ok, if we got here, both predecessors end with an unconditional branch to
327 // BB. Don't panic! If both blocks only have a single (identical)
328 // predecessor, and THAT is a conditional branch, then we're all ok!
329 if (pred_begin(Pred1) == pred_end(Pred1) ||
330 ++pred_begin(Pred1) != pred_end(Pred1) ||
331 pred_begin(Pred2) == pred_end(Pred2) ||
332 ++pred_begin(Pred2) != pred_end(Pred2) ||
333 *pred_begin(Pred1) != *pred_begin(Pred2))
334 return 0;
335
336 // Otherwise, if this is a conditional branch, then we can use it!
337 BasicBlock *CommonPred = *pred_begin(Pred1);
338 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
339 assert(BI->isConditional() && "Two successors but not conditional?");
340 if (BI->getSuccessor(0) == Pred1) {
341 IfTrue = Pred1;
342 IfFalse = Pred2;
343 } else {
344 IfTrue = Pred2;
345 IfFalse = Pred1;
346 }
347 return BI->getCondition();
348 }
349 return 0;
350}
351
Bill Wendling5049fa62009-01-19 23:43:56 +0000352/// DominatesMergePoint - If we have a merge point of an "if condition" as
353/// accepted above, return true if the specified value dominates the block. We
354/// don't handle the true generality of domination here, just a special case
355/// which works well enough for us.
356///
357/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
358/// see if V (which must be an instruction) is cheap to compute and is
359/// non-trapping. If both are true, the instruction is inserted into the set
360/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000361static bool DominatesMergePoint(Value *V, BasicBlock *BB,
362 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000363 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000364 if (!I) {
365 // Non-instructions all dominate instructions, but not all constantexprs
366 // can be executed unconditionally.
367 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
368 if (C->canTrap())
369 return false;
370 return true;
371 }
Chris Lattner570751c2004-04-09 22:50:22 +0000372 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000373
Chris Lattnerda895d62005-02-27 06:18:25 +0000374 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000375 // the bottom of this block.
376 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000377
Chris Lattner570751c2004-04-09 22:50:22 +0000378 // If this instruction is defined in a block that contains an unconditional
379 // branch to BB, then it must be in the 'conditional' part of the "if
380 // statement".
381 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
382 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000383 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000384 // Okay, it looks like the instruction IS in the "condition". Check to
385 // see if its a cheap instruction to unconditionally compute, and if it
386 // only uses stuff defined outside of the condition. If so, hoist it out.
Eli Friedman0b79a772009-07-17 04:28:42 +0000387 if (!I->isSafeToSpeculativelyExecute())
388 return false;
389
Chris Lattner570751c2004-04-09 22:50:22 +0000390 switch (I->getOpcode()) {
391 default: return false; // Cannot hoist this out safely.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000392 case Instruction::Load: {
Eli Friedman0b79a772009-07-17 04:28:42 +0000393 // We have to check to make sure there are no instructions before the
394 // load in its basic block, as we are going to hoist the loop out to
395 // its predecessor.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000396 BasicBlock::iterator IP = PBB->begin();
397 while (isa<DbgInfoIntrinsic>(IP))
398 IP++;
399 if (IP != BasicBlock::iterator(I))
Chris Lattner570751c2004-04-09 22:50:22 +0000400 return false;
401 break;
Dale Johannesen3a56d142009-03-06 21:08:33 +0000402 }
Chris Lattner570751c2004-04-09 22:50:22 +0000403 case Instruction::Add:
404 case Instruction::Sub:
405 case Instruction::And:
406 case Instruction::Or:
407 case Instruction::Xor:
408 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000409 case Instruction::LShr:
410 case Instruction::AShr:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000411 case Instruction::ICmp:
Chris Lattner570751c2004-04-09 22:50:22 +0000412 break; // These are all cheap and non-trapping instructions.
413 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000414
Chris Lattner570751c2004-04-09 22:50:22 +0000415 // Okay, we can only really hoist these out if their operands are not
416 // defined in the conditional region.
Gabor Greiff7ea3632008-06-10 22:03:26 +0000417 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
418 if (!DominatesMergePoint(*i, BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000419 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000420 // Okay, it's safe to do this! Remember this instruction.
421 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000422 }
423
Chris Lattner723c66d2004-02-11 03:36:04 +0000424 return true;
425}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000426
Bill Wendling5049fa62009-01-19 23:43:56 +0000427/// GatherConstantSetEQs - Given a potentially 'or'd together collection of
428/// icmp_eq instructions that compare a value against a constant, return the
429/// value being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000430static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000431 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000432 if (Inst->getOpcode() == Instruction::ICmp &&
433 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000434 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000435 Values.push_back(C);
436 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000437 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000438 Values.push_back(C);
439 return Inst->getOperand(1);
440 }
441 } else if (Inst->getOpcode() == Instruction::Or) {
442 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
443 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
444 if (LHS == RHS)
445 return LHS;
446 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000447 }
Chris Lattner0d560082004-02-24 05:38:11 +0000448 return 0;
449}
450
Bill Wendling5049fa62009-01-19 23:43:56 +0000451/// GatherConstantSetNEs - Given a potentially 'and'd together collection of
452/// setne instructions that compare a value against a constant, return the value
453/// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000454static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000455 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000456 if (Inst->getOpcode() == Instruction::ICmp &&
457 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000458 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000459 Values.push_back(C);
460 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000461 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000462 Values.push_back(C);
463 return Inst->getOperand(1);
464 }
Chris Lattner0d560082004-02-24 05:38:11 +0000465 } else if (Inst->getOpcode() == Instruction::And) {
466 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
467 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
468 if (LHS == RHS)
469 return LHS;
470 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000471 }
Chris Lattner0d560082004-02-24 05:38:11 +0000472 return 0;
473}
474
Chris Lattner0d560082004-02-24 05:38:11 +0000475/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
476/// bunch of comparisons of one value against constants, return the value and
477/// the constants being compared.
478static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000479 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000480 if (Cond->getOpcode() == Instruction::Or) {
481 CompVal = GatherConstantSetEQs(Cond, Values);
482
483 // Return true to indicate that the condition is true if the CompVal is
484 // equal to one of the constants.
485 return true;
486 } else if (Cond->getOpcode() == Instruction::And) {
487 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000488
Chris Lattner0d560082004-02-24 05:38:11 +0000489 // Return false to indicate that the condition is false if the CompVal is
490 // equal to one of the constants.
491 return false;
492 }
493 return false;
494}
495
Eli Friedman080efb82008-12-16 20:54:32 +0000496static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
497 Instruction* Cond = 0;
498 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
499 Cond = dyn_cast<Instruction>(SI->getCondition());
500 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
501 if (BI->isConditional())
502 Cond = dyn_cast<Instruction>(BI->getCondition());
503 }
504
505 TI->eraseFromParent();
506 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
507}
508
Chris Lattner9fd49552008-11-27 23:25:44 +0000509/// isValueEqualityComparison - Return true if the specified terminator checks
510/// to see if a value is equal to constant integer value.
Chris Lattner542f1492004-02-28 21:28:10 +0000511static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000512 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
513 // Do not permit merging of large switch instructions into their
514 // predecessors unless there is only one predecessor.
515 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
516 pred_end(SI->getParent())) > 128)
517 return 0;
518
Chris Lattner542f1492004-02-28 21:28:10 +0000519 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000520 }
Chris Lattner542f1492004-02-28 21:28:10 +0000521 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
522 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000523 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
524 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
525 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
526 isa<ConstantInt>(ICI->getOperand(1)))
527 return ICI->getOperand(0);
Chris Lattner542f1492004-02-28 21:28:10 +0000528 return 0;
529}
530
Bill Wendling5049fa62009-01-19 23:43:56 +0000531/// GetValueEqualityComparisonCases - Given a value comparison instruction,
532/// decode all of the 'cases' that it represents and return the 'default' block.
Chris Lattner542f1492004-02-28 21:28:10 +0000533static BasicBlock *
Misha Brukmanfd939082005-04-21 23:48:37 +0000534GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000535 std::vector<std::pair<ConstantInt*,
536 BasicBlock*> > &Cases) {
537 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
538 Cases.reserve(SI->getNumCases());
539 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000540 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000541 return SI->getDefaultDest();
542 }
543
544 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000545 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
546 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
547 BI->getSuccessor(ICI->getPredicate() ==
548 ICmpInst::ICMP_NE)));
549 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000550}
551
552
Bill Wendling5049fa62009-01-19 23:43:56 +0000553/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
554/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000555static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000556 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
557 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
558 if (Cases[i].second == BB) {
559 Cases.erase(Cases.begin()+i);
560 --i; --e;
561 }
562}
563
Bill Wendling5049fa62009-01-19 23:43:56 +0000564/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
565/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000566static bool
567ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
568 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
569 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
570
571 // Make V1 be smaller than V2.
572 if (V1->size() > V2->size())
573 std::swap(V1, V2);
574
575 if (V1->size() == 0) return false;
576 if (V1->size() == 1) {
577 // Just scan V2.
578 ConstantInt *TheVal = (*V1)[0].first;
579 for (unsigned i = 0, e = V2->size(); i != e; ++i)
580 if (TheVal == (*V2)[i].first)
581 return true;
582 }
583
584 // Otherwise, just sort both lists and compare element by element.
585 std::sort(V1->begin(), V1->end());
586 std::sort(V2->begin(), V2->end());
587 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
588 while (i1 != e1 && i2 != e2) {
589 if ((*V1)[i1].first == (*V2)[i2].first)
590 return true;
591 if ((*V1)[i1].first < (*V2)[i2].first)
592 ++i1;
593 else
594 ++i2;
595 }
596 return false;
597}
598
Bill Wendling5049fa62009-01-19 23:43:56 +0000599/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
600/// terminator instruction and its block is known to only have a single
601/// predecessor block, check to see if that predecessor is also a value
602/// comparison with the same value, and if that comparison determines the
603/// outcome of this comparison. If so, simplify TI. This does a very limited
604/// form of jump threading.
Chris Lattner623369a2005-02-24 06:17:52 +0000605static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
606 BasicBlock *Pred) {
607 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
608 if (!PredVal) return false; // Not a value comparison in predecessor.
609
610 Value *ThisVal = isValueEqualityComparison(TI);
611 assert(ThisVal && "This isn't a value comparison!!");
612 if (ThisVal != PredVal) return false; // Different predicates.
613
614 // Find out information about when control will move from Pred to TI's block.
615 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
616 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
617 PredCases);
618 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000619
Chris Lattner623369a2005-02-24 06:17:52 +0000620 // Find information about how control leaves this block.
621 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
622 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
623 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
624
625 // If TI's block is the default block from Pred's comparison, potentially
626 // simplify TI based on this knowledge.
627 if (PredDef == TI->getParent()) {
628 // If we are here, we know that the value is none of those cases listed in
629 // PredCases. If there are any cases in ThisCases that are in PredCases, we
630 // can simplify TI.
631 if (ValuesOverlap(PredCases, ThisCases)) {
Eli Friedman080efb82008-12-16 20:54:32 +0000632 if (isa<BranchInst>(TI)) {
Chris Lattner623369a2005-02-24 06:17:52 +0000633 // Okay, one of the successors of this condbr is dead. Convert it to a
634 // uncond br.
635 assert(ThisCases.size() == 1 && "Branch can only have one case!");
Chris Lattner623369a2005-02-24 06:17:52 +0000636 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000637 Instruction *NI = BranchInst::Create(ThisDef, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000638
639 // Remove PHI node entries for the dead edge.
640 ThisCases[0].second->removePredecessor(TI->getParent());
641
Bill Wendling0d45a092006-11-26 10:17:54 +0000642 DOUT << "Threading pred instr: " << *Pred->getTerminator()
643 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000644
Eli Friedman080efb82008-12-16 20:54:32 +0000645 EraseTerminatorInstAndDCECond(TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000646 return true;
647
648 } else {
649 SwitchInst *SI = cast<SwitchInst>(TI);
650 // Okay, TI has cases that are statically dead, prune them away.
Chris Lattnerc9951232007-04-02 01:44:59 +0000651 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000652 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
653 DeadCases.insert(PredCases[i].first);
654
Bill Wendling0d45a092006-11-26 10:17:54 +0000655 DOUT << "Threading pred instr: " << *Pred->getTerminator()
656 << "Through successor TI: " << *TI;
Chris Lattner623369a2005-02-24 06:17:52 +0000657
658 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
659 if (DeadCases.count(SI->getCaseValue(i))) {
660 SI->getSuccessor(i)->removePredecessor(TI->getParent());
661 SI->removeCase(i);
662 }
663
Bill Wendling0d45a092006-11-26 10:17:54 +0000664 DOUT << "Leaving: " << *TI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000665 return true;
666 }
667 }
668
669 } else {
670 // Otherwise, TI's block must correspond to some matched value. Find out
671 // which value (or set of values) this is.
672 ConstantInt *TIV = 0;
673 BasicBlock *TIBB = TI->getParent();
674 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000675 if (PredCases[i].second == TIBB) {
Chris Lattner623369a2005-02-24 06:17:52 +0000676 if (TIV == 0)
677 TIV = PredCases[i].first;
678 else
679 return false; // Cannot handle multiple values coming to this block.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000680 }
Chris Lattner623369a2005-02-24 06:17:52 +0000681 assert(TIV && "No edge from pred to succ?");
682
683 // Okay, we found the one constant that our value can be if we get into TI's
684 // BB. Find out which successor will unconditionally be branched to.
685 BasicBlock *TheRealDest = 0;
686 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
687 if (ThisCases[i].first == TIV) {
688 TheRealDest = ThisCases[i].second;
689 break;
690 }
691
692 // If not handled by any explicit cases, it is handled by the default case.
693 if (TheRealDest == 0) TheRealDest = ThisDef;
694
695 // Remove PHI node entries for dead edges.
696 BasicBlock *CheckEdge = TheRealDest;
697 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
698 if (*SI != CheckEdge)
699 (*SI)->removePredecessor(TIBB);
700 else
701 CheckEdge = 0;
702
703 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000704 Instruction *NI = BranchInst::Create(TheRealDest, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000705
Bill Wendling0d45a092006-11-26 10:17:54 +0000706 DOUT << "Threading pred instr: " << *Pred->getTerminator()
707 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000708
Eli Friedman080efb82008-12-16 20:54:32 +0000709 EraseTerminatorInstAndDCECond(TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000710 return true;
711 }
712 return false;
713}
714
Dale Johannesenc81f5442009-03-12 21:01:11 +0000715namespace {
716 /// ConstantIntOrdering - This class implements a stable ordering of constant
717 /// integers that does not depend on their address. This is important for
718 /// applications that sort ConstantInt's to ensure uniqueness.
719 struct ConstantIntOrdering {
720 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
721 return LHS->getValue().ult(RHS->getValue());
722 }
723 };
724}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000725
Bill Wendling5049fa62009-01-19 23:43:56 +0000726/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
727/// equality comparison instruction (either a switch or a branch on "X == c").
728/// See if any of the predecessors of the terminator block are value comparisons
729/// on the same value. If so, and if safe to do so, fold them together.
Chris Lattner542f1492004-02-28 21:28:10 +0000730static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
731 BasicBlock *BB = TI->getParent();
732 Value *CV = isValueEqualityComparison(TI); // CondVal
733 assert(CV && "Not a comparison?");
734 bool Changed = false;
735
Chris Lattner82442432008-02-18 07:42:56 +0000736 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000737 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000738 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000739
Chris Lattner542f1492004-02-28 21:28:10 +0000740 // See if the predecessor is a comparison with the same value.
741 TerminatorInst *PTI = Pred->getTerminator();
742 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
743
744 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
745 // Figure out which 'cases' to copy from SI to PSI.
746 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
747 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
748
749 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
750 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
751
752 // Based on whether the default edge from PTI goes to BB or not, fill in
753 // PredCases and PredDefault with the new switch cases we would like to
754 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000755 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000756
757 if (PredDefault == BB) {
758 // If this is the default destination from PTI, only the edges in TI
759 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000760 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000761 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
762 if (PredCases[i].second != BB)
763 PTIHandled.insert(PredCases[i].first);
764 else {
765 // The default destination is BB, we don't need explicit targets.
766 std::swap(PredCases[i], PredCases.back());
767 PredCases.pop_back();
768 --i; --e;
769 }
770
771 // Reconstruct the new switch statement we will be building.
772 if (PredDefault != BBDefault) {
773 PredDefault->removePredecessor(Pred);
774 PredDefault = BBDefault;
775 NewSuccessors.push_back(BBDefault);
776 }
777 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
778 if (!PTIHandled.count(BBCases[i].first) &&
779 BBCases[i].second != BBDefault) {
780 PredCases.push_back(BBCases[i]);
781 NewSuccessors.push_back(BBCases[i].second);
782 }
783
784 } else {
785 // If this is not the default destination from PSI, only the edges
786 // in SI that occur in PSI with a destination of BB will be
787 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000788 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000789 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
790 if (PredCases[i].second == BB) {
791 PTIHandled.insert(PredCases[i].first);
792 std::swap(PredCases[i], PredCases.back());
793 PredCases.pop_back();
794 --i; --e;
795 }
796
797 // Okay, now we know which constants were sent to BB from the
798 // predecessor. Figure out where they will all go now.
799 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
800 if (PTIHandled.count(BBCases[i].first)) {
801 // If this is one we are capable of getting...
802 PredCases.push_back(BBCases[i]);
803 NewSuccessors.push_back(BBCases[i].second);
804 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
805 }
806
807 // If there are any constants vectored to BB that TI doesn't handle,
808 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000809 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
810 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000811 E = PTIHandled.end(); I != E; ++I) {
812 PredCases.push_back(std::make_pair(*I, BBDefault));
813 NewSuccessors.push_back(BBDefault);
814 }
815 }
816
817 // Okay, at this point, we know which new successor Pred will get. Make
818 // sure we update the number of entries in the PHI nodes for these
819 // successors.
820 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
821 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
822
823 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000824 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
825 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000826 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
827 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000828
Eli Friedman080efb82008-12-16 20:54:32 +0000829 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000830
Chris Lattner542f1492004-02-28 21:28:10 +0000831 // Okay, last check. If BB is still a successor of PSI, then we must
832 // have an infinite loop case. If so, add an infinitely looping block
833 // to handle the case to preserve the behavior of the code.
834 BasicBlock *InfLoopBlock = 0;
835 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
836 if (NewSI->getSuccessor(i) == BB) {
837 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000838 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000839 // or it won't matter if it's hot. :)
Gabor Greif051a9502008-04-06 20:25:17 +0000840 InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
841 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000842 }
843 NewSI->setSuccessor(i, InfLoopBlock);
844 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000845
Chris Lattner542f1492004-02-28 21:28:10 +0000846 Changed = true;
847 }
848 }
849 return Changed;
850}
851
Dale Johannesenc1f10402009-06-15 20:59:27 +0000852// isSafeToHoistInvoke - If we would need to insert a select that uses the
853// value of this invoke (comments in HoistThenElseCodeToIf explain why we
854// would need to do this), we can't hoist the invoke, as there is nowhere
855// to put the select in this case.
856static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
857 Instruction *I1, Instruction *I2) {
858 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
859 PHINode *PN;
860 for (BasicBlock::iterator BBI = SI->begin();
861 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
862 Value *BB1V = PN->getIncomingValueForBlock(BB1);
863 Value *BB2V = PN->getIncomingValueForBlock(BB2);
864 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
865 return false;
866 }
867 }
868 }
869 return true;
870}
871
Chris Lattner6306d072005-08-03 17:59:45 +0000872/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000873/// BB2, hoist any common code in the two blocks up into the branch block. The
874/// caller of this function guarantees that BI's block dominates BB1 and BB2.
875static bool HoistThenElseCodeToIf(BranchInst *BI) {
876 // This does very trivial matching, with limited scanning, to find identical
877 // instructions in the two blocks. In particular, we don't want to get into
878 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
879 // such, we currently just scan for obviously identical instructions in an
880 // identical order.
881 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
882 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
883
Devang Patel65085cf2009-02-04 00:03:08 +0000884 BasicBlock::iterator BB1_Itr = BB1->begin();
885 BasicBlock::iterator BB2_Itr = BB2->begin();
886
887 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
888 while (isa<DbgInfoIntrinsic>(I1))
889 I1 = BB1_Itr++;
890 while (isa<DbgInfoIntrinsic>(I2))
891 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000892 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
893 !I1->isIdenticalTo(I2) ||
894 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000895 return false;
896
897 // If we get here, we can hoist at least one instruction.
898 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000899
900 do {
901 // If we are hoisting the terminator instruction, don't move one (making a
902 // broken BB), instead clone it, and remove BI.
903 if (isa<TerminatorInst>(I1))
904 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000905
Chris Lattner37dc9382004-11-30 00:29:14 +0000906 // For a normal instruction, we just move one to right before the branch,
907 // then replace all uses of the other with the first. Finally, we remove
908 // the now redundant second instruction.
909 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
910 if (!I2->use_empty())
911 I2->replaceAllUsesWith(I1);
912 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000913
Devang Patel65085cf2009-02-04 00:03:08 +0000914 I1 = BB1_Itr++;
915 while (isa<DbgInfoIntrinsic>(I1))
916 I1 = BB1_Itr++;
917 I2 = BB2_Itr++;
918 while (isa<DbgInfoIntrinsic>(I2))
919 I2 = BB2_Itr++;
Chris Lattner37dc9382004-11-30 00:29:14 +0000920 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
921
922 return true;
923
924HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000925 // It may not be possible to hoist an invoke.
926 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
927 return true;
928
Chris Lattner37dc9382004-11-30 00:29:14 +0000929 // Okay, it is safe to hoist the terminator.
Owen Anderson333c4002009-07-09 23:48:35 +0000930 Instruction *NT = I1->clone(*BB1->getContext());
Chris Lattner37dc9382004-11-30 00:29:14 +0000931 BIParent->getInstList().insert(BI, NT);
932 if (NT->getType() != Type::VoidTy) {
933 I1->replaceAllUsesWith(NT);
934 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000935 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000936 }
937
938 // Hoisting one of the terminators from our successor is a great thing.
939 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
940 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
941 // nodes, so we insert select instruction to compute the final result.
942 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
943 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
944 PHINode *PN;
945 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000946 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000947 Value *BB1V = PN->getIncomingValueForBlock(BB1);
948 Value *BB2V = PN->getIncomingValueForBlock(BB2);
949 if (BB1V != BB2V) {
950 // These values do not agree. Insert a select instruction before NT
951 // that determines the right value.
952 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
953 if (SI == 0)
Gabor Greif051a9502008-04-06 20:25:17 +0000954 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
955 BB1V->getName()+"."+BB2V->getName(), NT);
Chris Lattner37dc9382004-11-30 00:29:14 +0000956 // Make the PHI node use the select for all incoming values for BB1/BB2
957 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
958 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
959 PN->setIncomingValue(i, SI);
960 }
961 }
962 }
963
964 // Update any PHI nodes in our new successors.
965 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
966 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000967
Eli Friedman080efb82008-12-16 20:54:32 +0000968 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000969 return true;
970}
971
Evan Cheng4d09efd2008-06-07 08:52:29 +0000972/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
973/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
974/// (for now, restricted to a single instruction that's side effect free) from
975/// the BB1 into the branch block to speculatively execute it.
976static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
977 // Only speculatively execution a single instruction (not counting the
978 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000979 Instruction *HInst = NULL;
980 Instruction *Term = BB1->getTerminator();
981 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
982 BBI != BBE; ++BBI) {
983 Instruction *I = BBI;
984 // Skip debug info.
985 if (isa<DbgInfoIntrinsic>(I)) continue;
986 if (I == Term) break;
987
988 if (!HInst)
989 HInst = I;
990 else
991 return false;
992 }
993 if (!HInst)
994 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000995
Evan Cheng797d9512008-06-11 19:18:20 +0000996 // Be conservative for now. FP select instruction can often be expensive.
997 Value *BrCond = BI->getCondition();
998 if (isa<Instruction>(BrCond) &&
999 cast<Instruction>(BrCond)->getOpcode() == Instruction::FCmp)
1000 return false;
1001
Evan Cheng4d09efd2008-06-07 08:52:29 +00001002 // If BB1 is actually on the false edge of the conditional branch, remember
1003 // to swap the select operands later.
1004 bool Invert = false;
1005 if (BB1 != BI->getSuccessor(0)) {
1006 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1007 Invert = true;
1008 }
1009
1010 // Turn
1011 // BB:
1012 // %t1 = icmp
1013 // br i1 %t1, label %BB1, label %BB2
1014 // BB1:
1015 // %t3 = add %t2, c
1016 // br label BB2
1017 // BB2:
1018 // =>
1019 // BB:
1020 // %t1 = icmp
1021 // %t4 = add %t2, c
1022 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +00001023 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +00001024 default: return false; // Not safe / profitable to hoist.
1025 case Instruction::Add:
1026 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001027 // Not worth doing for vector ops.
1028 if (isa<VectorType>(HInst->getType()))
Chris Lattner9dd3b612009-01-18 23:22:07 +00001029 return false;
1030 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001031 case Instruction::And:
1032 case Instruction::Or:
1033 case Instruction::Xor:
1034 case Instruction::Shl:
1035 case Instruction::LShr:
1036 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +00001037 // Don't mess with vector operations.
Devang Patel06b1e672009-03-06 06:00:17 +00001038 if (isa<VectorType>(HInst->getType()))
Evan Chenge5334ea2008-06-25 07:50:12 +00001039 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001040 break; // These are all cheap and non-trapping instructions.
1041 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001042
1043 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +00001044 if (HInst->use_empty()) {
1045 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001046 return true;
1047 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001048
1049 // Can we speculatively execute the instruction? And what is the value
1050 // if the condition is false? Consider the phi uses, if the incoming value
1051 // from the "if" block are all the same V, then V is the value of the
1052 // select if the condition is false.
1053 BasicBlock *BIParent = BI->getParent();
1054 SmallVector<PHINode*, 4> PHIUses;
1055 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001056
1057 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +00001058 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +00001059 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001060 // Ignore any user that is not a PHI node in BB2. These can only occur in
1061 // unreachable blocks, because they would not be dominated by the instr.
Evan Cheng4d09efd2008-06-07 08:52:29 +00001062 PHINode *PN = dyn_cast<PHINode>(UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001063 if (!PN || PN->getParent() != BB2)
1064 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001065 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001066
Evan Cheng4d09efd2008-06-07 08:52:29 +00001067 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
1068 if (!FalseV)
1069 FalseV = PHIV;
1070 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001071 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +00001072 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001073
1074 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +00001075
Evan Cheng502a4f52008-06-12 21:15:59 +00001076 // Do not hoist the instruction if any of its operands are defined but not
1077 // used in this BB. The transformation will prevent the operand from
1078 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +00001079 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1080 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +00001081 Instruction *OpI = dyn_cast<Instruction>(*i);
1082 if (OpI && OpI->getParent() == BIParent &&
1083 !OpI->isUsedInBasicBlock(BIParent))
1084 return false;
1085 }
1086
Devang Patel3d0a9a32008-09-18 22:50:42 +00001087 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +00001088 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +00001089 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +00001090 if (InsertPos != BIParent->begin())
1091 --InsertPos;
1092 // Skip debug info between condition and branch.
1093 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +00001094 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +00001095 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +00001096 SmallPtrSet<Instruction *, 4> BB1Insns;
1097 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
1098 BB1I != BB1E; ++BB1I)
1099 BB1Insns.insert(BB1I);
1100 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1101 UI != UE; ++UI) {
1102 Instruction *Use = cast<Instruction>(*UI);
1103 if (BB1Insns.count(Use)) {
1104 // If BrCond uses the instruction that place it just before
1105 // branch instruction.
1106 InsertPos = BI;
1107 break;
1108 }
1109 }
1110 } else
1111 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +00001112 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001113
1114 // Create a select whose true value is the speculatively executed value and
1115 // false value is the previously determined FalseV.
1116 SelectInst *SI;
1117 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +00001118 SI = SelectInst::Create(BrCond, FalseV, HInst,
1119 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001120 else
Devang Patel06b1e672009-03-06 06:00:17 +00001121 SI = SelectInst::Create(BrCond, HInst, FalseV,
1122 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001123
1124 // Make the PHI node use the select for all incoming values for "then" and
1125 // "if" blocks.
1126 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1127 PHINode *PN = PHIUses[i];
1128 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
1129 if (PN->getIncomingBlock(j) == BB1 ||
1130 PN->getIncomingBlock(j) == BIParent)
1131 PN->setIncomingValue(j, SI);
1132 }
1133
Evan Cheng502a4f52008-06-12 21:15:59 +00001134 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001135 return true;
1136}
1137
Chris Lattner2e42e362005-09-20 00:43:16 +00001138/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1139/// across this block.
1140static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1141 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001142 unsigned Size = 0;
1143
Devang Patel9200c892009-03-10 18:00:05 +00001144 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001145 if (isa<DbgInfoIntrinsic>(BBI))
1146 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001147 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001148 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001149
Dale Johannesen8483e542009-03-12 23:18:09 +00001150 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001151 // live outside of the current basic block.
1152 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1153 UI != E; ++UI) {
1154 Instruction *U = cast<Instruction>(*UI);
1155 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1156 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001157
1158 // Looks ok, continue checking.
1159 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001160
Chris Lattner2e42e362005-09-20 00:43:16 +00001161 return true;
1162}
1163
Chris Lattnereaba3a12005-09-19 23:49:37 +00001164/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1165/// that is defined in the same block as the branch and if any PHI entries are
1166/// constants, thread edges corresponding to that entry to be branches to their
1167/// ultimate destination.
1168static bool FoldCondBranchOnPHI(BranchInst *BI) {
1169 BasicBlock *BB = BI->getParent();
Owen Anderson07cf79e2009-07-06 23:00:19 +00001170 LLVMContext *Context = BB->getContext();
Chris Lattnereaba3a12005-09-19 23:49:37 +00001171 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001172 // NOTE: we currently cannot transform this case if the PHI node is used
1173 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001174 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1175 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001176
1177 // Degenerate case of a single entry PHI.
1178 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001179 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001180 return true;
1181 }
1182
1183 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001184 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001185
1186 // Okay, this is a simple enough basic block. See if any phi values are
1187 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001188 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1189 ConstantInt *CB;
1190 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001191 CB->getType() == Type::Int1Ty) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001192 // Okay, we now know that all edges from PredBB should be revectored to
1193 // branch to RealDest.
1194 BasicBlock *PredBB = PN->getIncomingBlock(i);
Reid Spencer579dca12007-01-12 04:24:46 +00001195 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001196
Chris Lattnere9487f02005-09-20 01:48:40 +00001197 if (RealDest == BB) continue; // Skip self loops.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001198
Chris Lattnere9487f02005-09-20 01:48:40 +00001199 // The dest block might have PHI nodes, other predecessors and other
1200 // difficult cases. Instead of being smart about this, just insert a new
1201 // block that jumps to the destination block, effectively splitting
1202 // the edge we are about to create.
Gabor Greif051a9502008-04-06 20:25:17 +00001203 BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
1204 RealDest->getParent(), RealDest);
1205 BranchInst::Create(RealDest, EdgeBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001206 PHINode *PN;
1207 for (BasicBlock::iterator BBI = RealDest->begin();
1208 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1209 Value *V = PN->getIncomingValueForBlock(BB);
1210 PN->addIncoming(V, EdgeBB);
1211 }
1212
1213 // BB may have instructions that are being threaded over. Clone these
1214 // instructions into EdgeBB. We know that there will be no uses of the
1215 // cloned instructions outside of EdgeBB.
1216 BasicBlock::iterator InsertPt = EdgeBB->begin();
1217 std::map<Value*, Value*> TranslateMap; // Track translated values.
1218 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1219 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1220 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1221 } else {
1222 // Clone the instruction.
Owen Anderson333c4002009-07-09 23:48:35 +00001223 Instruction *N = BBI->clone(*Context);
Chris Lattnere9487f02005-09-20 01:48:40 +00001224 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1225
1226 // Update operands due to translation.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001227 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1228 i != e; ++i) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001229 std::map<Value*, Value*>::iterator PI =
Gabor Greiff7ea3632008-06-10 22:03:26 +00001230 TranslateMap.find(*i);
Chris Lattnere9487f02005-09-20 01:48:40 +00001231 if (PI != TranslateMap.end())
Gabor Greiff7ea3632008-06-10 22:03:26 +00001232 *i = PI->second;
Chris Lattnere9487f02005-09-20 01:48:40 +00001233 }
1234
1235 // Check for trivial simplification.
Owen Anderson50895512009-07-06 18:42:36 +00001236 if (Constant *C = ConstantFoldInstruction(N, Context)) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001237 TranslateMap[BBI] = C;
1238 delete N; // Constant folded away, don't need actual inst
1239 } else {
1240 // Insert the new instruction into its new home.
1241 EdgeBB->getInstList().insert(InsertPt, N);
1242 if (!BBI->use_empty())
1243 TranslateMap[BBI] = N;
1244 }
1245 }
1246 }
1247
Chris Lattnereaba3a12005-09-19 23:49:37 +00001248 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattnere9487f02005-09-20 01:48:40 +00001249 // to EdgeBB instead.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001250 TerminatorInst *PredBBTI = PredBB->getTerminator();
1251 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1252 if (PredBBTI->getSuccessor(i) == BB) {
1253 BB->removePredecessor(PredBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001254 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattnereaba3a12005-09-19 23:49:37 +00001255 }
1256
Chris Lattnereaba3a12005-09-19 23:49:37 +00001257 // Recurse, simplifying any other constants.
1258 return FoldCondBranchOnPHI(BI) | true;
1259 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001260 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001261
1262 return false;
1263}
1264
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001265/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1266/// PHI node, see if we can eliminate it.
1267static bool FoldTwoEntryPHINode(PHINode *PN) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001268 LLVMContext *Context = PN->getParent()->getContext();
Owen Anderson0a205a42009-07-05 22:41:43 +00001269
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001270 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1271 // statement", which has a very simple dominance structure. Basically, we
1272 // are trying to find the condition that is being branched on, which
1273 // subsequently causes this merge to happen. We really want control
1274 // dependence information for this check, but simplifycfg can't keep it up
1275 // to date, and this catches most of the cases we care about anyway.
1276 //
1277 BasicBlock *BB = PN->getParent();
1278 BasicBlock *IfTrue, *IfFalse;
1279 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1280 if (!IfCond) return false;
1281
Chris Lattner822a8792006-11-18 19:19:36 +00001282 // Okay, we found that we can merge this two-entry phi node into a select.
1283 // Doing so would require us to fold *all* two entry phi nodes in this block.
1284 // At some point this becomes non-profitable (particularly if the target
1285 // doesn't support cmov's). Only do this transformation if there are two or
1286 // fewer PHI nodes in this block.
1287 unsigned NumPhis = 0;
1288 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1289 if (NumPhis > 2)
1290 return false;
1291
Bill Wendling0d45a092006-11-26 10:17:54 +00001292 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1293 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001294
1295 // Loop over the PHI's seeing if we can promote them all to select
1296 // instructions. While we are at it, keep track of the instructions
1297 // that need to be moved to the dominating block.
1298 std::set<Instruction*> AggressiveInsts;
1299
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001300 BasicBlock::iterator AfterPHIIt = BB->begin();
1301 while (isa<PHINode>(AfterPHIIt)) {
1302 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1303 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1304 if (PN->getIncomingValue(0) != PN)
1305 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1306 else
Owen Anderson0a205a42009-07-05 22:41:43 +00001307 PN->replaceAllUsesWith(Context->getUndef(PN->getType()));
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001308 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1309 &AggressiveInsts) ||
1310 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1311 &AggressiveInsts)) {
Chris Lattner055dc102005-09-23 07:23:18 +00001312 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001313 }
1314 }
1315
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001316 // If we all PHI nodes are promotable, check to make sure that all
1317 // instructions in the predecessor blocks can be promoted as well. If
1318 // not, we won't be able to get rid of the control flow, so it's not
1319 // worth promoting to select instructions.
1320 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1321 PN = cast<PHINode>(BB->begin());
1322 BasicBlock *Pred = PN->getIncomingBlock(0);
1323 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1324 IfBlock1 = Pred;
1325 DomBlock = *pred_begin(Pred);
1326 for (BasicBlock::iterator I = Pred->begin();
1327 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001328 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001329 // This is not an aggressive instruction that we can promote.
1330 // Because of this, we won't be able to get rid of the control
1331 // flow, so the xform is not worth it.
1332 return false;
1333 }
1334 }
1335
1336 Pred = PN->getIncomingBlock(1);
1337 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1338 IfBlock2 = Pred;
1339 DomBlock = *pred_begin(Pred);
1340 for (BasicBlock::iterator I = Pred->begin();
1341 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001342 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001343 // This is not an aggressive instruction that we can promote.
1344 // Because of this, we won't be able to get rid of the control
1345 // flow, so the xform is not worth it.
1346 return false;
1347 }
1348 }
1349
1350 // If we can still promote the PHI nodes after this gauntlet of tests,
1351 // do all of the PHI's now.
1352
1353 // Move all 'aggressive' instructions, which are defined in the
1354 // conditional parts of the if's up to the dominating block.
1355 if (IfBlock1) {
1356 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1357 IfBlock1->getInstList(),
1358 IfBlock1->begin(),
1359 IfBlock1->getTerminator());
1360 }
1361 if (IfBlock2) {
1362 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1363 IfBlock2->getInstList(),
1364 IfBlock2->begin(),
1365 IfBlock2->getTerminator());
1366 }
1367
1368 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1369 // Change the PHI node into a select instruction.
1370 Value *TrueVal =
1371 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1372 Value *FalseVal =
1373 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1374
Gabor Greif051a9502008-04-06 20:25:17 +00001375 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001376 PN->replaceAllUsesWith(NV);
1377 NV->takeName(PN);
1378
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001379 BB->getInstList().erase(PN);
1380 }
1381 return true;
1382}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001383
Devang Patel998cbb02009-02-05 21:46:41 +00001384/// isTerminatorFirstRelevantInsn - Return true if Term is very first
1385/// instruction ignoring Phi nodes and dbg intrinsics.
1386static bool isTerminatorFirstRelevantInsn(BasicBlock *BB, Instruction *Term) {
1387 BasicBlock::iterator BBI = Term;
1388 while (BBI != BB->begin()) {
1389 --BBI;
1390 if (!isa<DbgInfoIntrinsic>(BBI))
1391 break;
1392 }
Devang Patel0464a142009-02-10 22:14:17 +00001393
1394 if (isa<PHINode>(BBI) || &*BBI == Term || isa<DbgInfoIntrinsic>(BBI))
Devang Patel998cbb02009-02-05 21:46:41 +00001395 return true;
1396 return false;
1397}
1398
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001399/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1400/// to two returning blocks, try to merge them together into one return,
1401/// introducing a select if the return values disagree.
1402static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1403 assert(BI->isConditional() && "Must be a conditional branch");
1404 BasicBlock *TrueSucc = BI->getSuccessor(0);
1405 BasicBlock *FalseSucc = BI->getSuccessor(1);
1406 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1407 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1408
1409 // Check to ensure both blocks are empty (just a return) or optionally empty
1410 // with PHI nodes. If there are other instructions, merging would cause extra
1411 // computation on one path or the other.
Devang Patel2cc86a12009-02-05 00:30:42 +00001412 if (!isTerminatorFirstRelevantInsn(TrueSucc, TrueRet))
1413 return false;
1414 if (!isTerminatorFirstRelevantInsn(FalseSucc, FalseRet))
1415 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001416
1417 // Okay, we found a branch that is going to two return nodes. If
1418 // there is no return value for this function, just change the
1419 // branch into a return.
1420 if (FalseRet->getNumOperands() == 0) {
1421 TrueSucc->removePredecessor(BI->getParent());
1422 FalseSucc->removePredecessor(BI->getParent());
1423 ReturnInst::Create(0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001424 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001425 return true;
1426 }
1427
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001428 // Otherwise, figure out what the true and false return values are
1429 // so we can insert a new select instruction.
1430 Value *TrueValue = TrueRet->getReturnValue();
1431 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001432
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001433 // Unwrap any PHI nodes in the return blocks.
1434 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1435 if (TVPN->getParent() == TrueSucc)
1436 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1437 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1438 if (FVPN->getParent() == FalseSucc)
1439 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1440
1441 // In order for this transformation to be safe, we must be able to
1442 // unconditionally execute both operands to the return. This is
1443 // normally the case, but we could have a potentially-trapping
1444 // constant expression that prevents this transformation from being
1445 // safe.
1446 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1447 if (TCV->canTrap())
1448 return false;
1449 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1450 if (FCV->canTrap())
1451 return false;
1452
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001453 // Okay, we collected all the mapped values and checked them for sanity, and
1454 // defined to really do this transformation. First, update the CFG.
1455 TrueSucc->removePredecessor(BI->getParent());
1456 FalseSucc->removePredecessor(BI->getParent());
1457
1458 // Insert select instructions where needed.
1459 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001460 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001461 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001462 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1463 } else if (isa<UndefValue>(TrueValue)) {
1464 TrueValue = FalseValue;
1465 } else {
1466 TrueValue = SelectInst::Create(BrCond, TrueValue,
1467 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001468 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001469 }
1470
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001471 Value *RI = !TrueValue ?
1472 ReturnInst::Create(BI) :
1473 ReturnInst::Create(TrueValue, BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001474
1475 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1476 << "\n " << *BI << "NewRet = " << *RI
1477 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1478
Eli Friedman080efb82008-12-16 20:54:32 +00001479 EraseTerminatorInstAndDCECond(BI);
1480
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001481 return true;
1482}
1483
Chris Lattner1347e872008-07-13 21:12:01 +00001484/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1485/// and if a predecessor branches to us and one of our successors, fold the
1486/// setcc into the predecessor and use logical operations to pick the right
1487/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001488bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001489 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001490 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1491 if (Cond == 0) return false;
1492
Chris Lattner093a4382008-07-13 22:23:11 +00001493
Chris Lattner1347e872008-07-13 21:12:01 +00001494 // Only allow this if the condition is a simple instruction that can be
1495 // executed unconditionally. It must be in the same block as the branch, and
1496 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001497 BasicBlock::iterator FrontIt = BB->front();
1498 // Ignore dbg intrinsics.
1499 while(isa<DbgInfoIntrinsic>(FrontIt))
1500 ++FrontIt;
Chris Lattner1347e872008-07-13 21:12:01 +00001501 if ((!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
Devang Pateld0a203d2009-02-04 21:39:48 +00001502 Cond->getParent() != BB || &*FrontIt != Cond || !Cond->hasOneUse()) {
Chris Lattner1347e872008-07-13 21:12:01 +00001503 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001504 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001505
Chris Lattner1347e872008-07-13 21:12:01 +00001506 // Make sure the instruction after the condition is the cond branch.
1507 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001508 // Ingore dbg intrinsics.
1509 while(isa<DbgInfoIntrinsic>(CondIt))
1510 ++CondIt;
1511 if (&*CondIt != BI) {
1512 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001513 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001514 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001515
1516 // Cond is known to be a compare or binary operator. Check to make sure that
1517 // neither operand is a potentially-trapping constant expression.
1518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1519 if (CE->canTrap())
1520 return false;
1521 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1522 if (CE->canTrap())
1523 return false;
1524
Chris Lattner1347e872008-07-13 21:12:01 +00001525
1526 // Finally, don't infinitely unroll conditional loops.
1527 BasicBlock *TrueDest = BI->getSuccessor(0);
1528 BasicBlock *FalseDest = BI->getSuccessor(1);
1529 if (TrueDest == BB || FalseDest == BB)
1530 return false;
1531
1532 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1533 BasicBlock *PredBlock = *PI;
1534 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001535
Chris Lattner093a4382008-07-13 22:23:11 +00001536 // Check that we have two conditional branches. If there is a PHI node in
1537 // the common successor, verify that the same value flows in from both
1538 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001539 if (PBI == 0 || PBI->isUnconditional() ||
1540 !SafeToMergeTerminators(BI, PBI))
1541 continue;
1542
Chris Lattner36989092008-07-13 21:20:19 +00001543 Instruction::BinaryOps Opc;
1544 bool InvertPredCond = false;
1545
1546 if (PBI->getSuccessor(0) == TrueDest)
1547 Opc = Instruction::Or;
1548 else if (PBI->getSuccessor(1) == FalseDest)
1549 Opc = Instruction::And;
1550 else if (PBI->getSuccessor(0) == FalseDest)
1551 Opc = Instruction::And, InvertPredCond = true;
1552 else if (PBI->getSuccessor(1) == TrueDest)
1553 Opc = Instruction::Or, InvertPredCond = true;
1554 else
1555 continue;
1556
Chris Lattner6ff645b2009-01-19 23:03:13 +00001557 DOUT << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB;
1558
Chris Lattner36989092008-07-13 21:20:19 +00001559 // If we need to invert the condition in the pred block to match, do so now.
1560 if (InvertPredCond) {
Chris Lattner1347e872008-07-13 21:12:01 +00001561 Value *NewCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00001562 BinaryOperator::CreateNot(*BI->getParent()->getContext(),
1563 PBI->getCondition(),
Chris Lattner36989092008-07-13 21:20:19 +00001564 PBI->getCondition()->getName()+".not", PBI);
Chris Lattner1347e872008-07-13 21:12:01 +00001565 PBI->setCondition(NewCond);
1566 BasicBlock *OldTrue = PBI->getSuccessor(0);
1567 BasicBlock *OldFalse = PBI->getSuccessor(1);
1568 PBI->setSuccessor(0, OldFalse);
1569 PBI->setSuccessor(1, OldTrue);
1570 }
Chris Lattner70087f32008-07-13 21:15:11 +00001571
Chris Lattner36989092008-07-13 21:20:19 +00001572 // Clone Cond into the predecessor basic block, and or/and the
1573 // two conditions together.
Owen Anderson333c4002009-07-09 23:48:35 +00001574 Instruction *New = Cond->clone(*BB->getContext());
Chris Lattner36989092008-07-13 21:20:19 +00001575 PredBlock->getInstList().insert(PBI, New);
1576 New->takeName(Cond);
1577 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001578
Chris Lattner36989092008-07-13 21:20:19 +00001579 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1580 New, "or.cond", PBI);
1581 PBI->setCondition(NewCond);
1582 if (PBI->getSuccessor(0) == BB) {
1583 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1584 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001585 }
Chris Lattner36989092008-07-13 21:20:19 +00001586 if (PBI->getSuccessor(1) == BB) {
1587 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1588 PBI->setSuccessor(1, FalseDest);
1589 }
1590 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001591 }
1592 return false;
1593}
1594
Chris Lattner867661a2008-07-13 21:53:26 +00001595/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1596/// predecessor of another block, this function tries to simplify it. We know
1597/// that PBI and BI are both conditional branches, and BI is in one of the
1598/// successor blocks of PBI - PBI branches to BI.
1599static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1600 assert(PBI->isConditional() && BI->isConditional());
1601 BasicBlock *BB = BI->getParent();
Owen Anderson07cf79e2009-07-06 23:00:19 +00001602 LLVMContext *Context = BB->getContext();
Chris Lattner867661a2008-07-13 21:53:26 +00001603
1604 // If this block ends with a branch instruction, and if there is a
1605 // predecessor that ends on a branch of the same condition, make
1606 // this conditional branch redundant.
1607 if (PBI->getCondition() == BI->getCondition() &&
1608 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1609 // Okay, the outcome of this conditional branch is statically
1610 // knowable. If this block had a single pred, handle specially.
1611 if (BB->getSinglePredecessor()) {
1612 // Turn this into a branch on constant.
1613 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001614 BI->setCondition(Context->getConstantInt(Type::Int1Ty, CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001615 return true; // Nuke the branch on constant.
1616 }
1617
1618 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1619 // in the constant and simplify the block result. Subsequent passes of
1620 // simplifycfg will thread the block.
1621 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1622 PHINode *NewPN = PHINode::Create(Type::Int1Ty,
1623 BI->getCondition()->getName() + ".pr",
1624 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001625 // Okay, we're going to insert the PHI node. Since PBI is not the only
1626 // predecessor, compute the PHI'd conditional value for all of the preds.
1627 // Any predecessor where the condition is not computable we keep symbolic.
Chris Lattner867661a2008-07-13 21:53:26 +00001628 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1629 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1630 PBI != BI && PBI->isConditional() &&
1631 PBI->getCondition() == BI->getCondition() &&
1632 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1633 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001634 NewPN->addIncoming(Context->getConstantInt(Type::Int1Ty,
Chris Lattner867661a2008-07-13 21:53:26 +00001635 CondIsTrue), *PI);
1636 } else {
1637 NewPN->addIncoming(BI->getCondition(), *PI);
1638 }
1639
1640 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001641 return true;
1642 }
1643 }
1644
1645 // If this is a conditional branch in an empty block, and if any
1646 // predecessors is a conditional branch to one of our destinations,
1647 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001648 BasicBlock::iterator BBI = BB->begin();
1649 // Ignore dbg intrinsics.
1650 while (isa<DbgInfoIntrinsic>(BBI))
1651 ++BBI;
1652 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001653 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001654
1655
1656 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1657 if (CE->canTrap())
1658 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001659
1660 int PBIOp, BIOp;
1661 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1662 PBIOp = BIOp = 0;
1663 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1664 PBIOp = 0, BIOp = 1;
1665 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1666 PBIOp = 1, BIOp = 0;
1667 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1668 PBIOp = BIOp = 1;
1669 else
1670 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001671
Chris Lattnerb8245122008-07-13 22:04:41 +00001672 // Check to make sure that the other destination of this branch
1673 // isn't BB itself. If so, this is an infinite loop that will
1674 // keep getting unwound.
1675 if (PBI->getSuccessor(PBIOp) == BB)
1676 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001677
Chris Lattnerb8245122008-07-13 22:04:41 +00001678 // Do not perform this transformation if it would require
1679 // insertion of a large number of select instructions. For targets
1680 // without predication/cmovs, this is a big pessimization.
1681 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001682
Chris Lattnerb8245122008-07-13 22:04:41 +00001683 unsigned NumPhis = 0;
1684 for (BasicBlock::iterator II = CommonDest->begin();
1685 isa<PHINode>(II); ++II, ++NumPhis)
1686 if (NumPhis > 2) // Disable this xform.
1687 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001688
Chris Lattnerb8245122008-07-13 22:04:41 +00001689 // Finally, if everything is ok, fold the branches to logical ops.
1690 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1691
Chris Lattnerb8245122008-07-13 22:04:41 +00001692 DOUT << "FOLDING BRs:" << *PBI->getParent()
1693 << "AND: " << *BI->getParent();
1694
Chris Lattner093a4382008-07-13 22:23:11 +00001695
1696 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1697 // branch in it, where one edge (OtherDest) goes back to itself but the other
1698 // exits. We don't *know* that the program avoids the infinite loop
1699 // (even though that seems likely). If we do this xform naively, we'll end up
1700 // recursively unpeeling the loop. Since we know that (after the xform is
1701 // done) that the block *is* infinite if reached, we just make it an obviously
1702 // infinite loop with no cond branch.
1703 if (OtherDest == BB) {
1704 // Insert it at the end of the function, because it's either code,
1705 // or it won't matter if it's hot. :)
1706 BasicBlock *InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
1707 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1708 OtherDest = InfLoopBlock;
1709 }
1710
Chris Lattnerb8245122008-07-13 22:04:41 +00001711 DOUT << *PBI->getParent()->getParent();
1712
1713 // BI may have other predecessors. Because of this, we leave
1714 // it alone, but modify PBI.
1715
1716 // Make sure we get to CommonDest on True&True directions.
1717 Value *PBICond = PBI->getCondition();
1718 if (PBIOp)
Owen Anderson73c6b712009-07-13 20:58:05 +00001719 PBICond = BinaryOperator::CreateNot(*Context, PBICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001720 PBICond->getName()+".not",
1721 PBI);
1722 Value *BICond = BI->getCondition();
1723 if (BIOp)
Owen Anderson73c6b712009-07-13 20:58:05 +00001724 BICond = BinaryOperator::CreateNot(*Context, BICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001725 BICond->getName()+".not",
1726 PBI);
1727 // Merge the conditions.
1728 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1729
1730 // Modify PBI to branch on the new condition to the new dests.
1731 PBI->setCondition(Cond);
1732 PBI->setSuccessor(0, CommonDest);
1733 PBI->setSuccessor(1, OtherDest);
1734
1735 // OtherDest may have phi nodes. If so, add an entry from PBI's
1736 // block that are identical to the entries for BI's block.
1737 PHINode *PN;
1738 for (BasicBlock::iterator II = OtherDest->begin();
1739 (PN = dyn_cast<PHINode>(II)); ++II) {
1740 Value *V = PN->getIncomingValueForBlock(BB);
1741 PN->addIncoming(V, PBI->getParent());
1742 }
1743
1744 // We know that the CommonDest already had an edge from PBI to
1745 // it. If it has PHIs though, the PHIs may have different
1746 // entries for BB and PBI's BB. If so, insert a select to make
1747 // them agree.
1748 for (BasicBlock::iterator II = CommonDest->begin();
1749 (PN = dyn_cast<PHINode>(II)); ++II) {
1750 Value *BIV = PN->getIncomingValueForBlock(BB);
1751 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1752 Value *PBIV = PN->getIncomingValue(PBBIdx);
1753 if (BIV != PBIV) {
1754 // Insert a select in PBI to pick the right value.
1755 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1756 PBIV->getName()+".mux", PBI);
1757 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001758 }
1759 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001760
1761 DOUT << "INTO: " << *PBI->getParent();
1762
1763 DOUT << *PBI->getParent()->getParent();
1764
1765 // This basic block is probably dead. We know it has at least
1766 // one fewer predecessor.
1767 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001768}
1769
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001770
Bill Wendling5049fa62009-01-19 23:43:56 +00001771/// SimplifyCFG - This function is used to do simplification of a CFG. For
1772/// example, it adjusts branches to branches to eliminate the extra hop, it
1773/// eliminates unreachable basic blocks, and does other "peephole" optimization
1774/// of the CFG. It returns true if a modification was made.
1775///
1776/// WARNING: The entry node of a function may not be simplified.
1777///
Chris Lattnerf7703df2004-01-09 06:12:26 +00001778bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001779 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001780 Function *M = BB->getParent();
1781
1782 assert(BB && BB->getParent() && "Block not embedded in function!");
1783 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Dan Gohmanecb7a772007-03-22 16:38:57 +00001784 assert(&BB->getParent()->getEntryBlock() != BB &&
1785 "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001786
Chris Lattner5a5c9a52008-11-27 07:54:38 +00001787 // Remove basic blocks that have no predecessors... or that just have themself
1788 // as a predecessor. These are unreachable.
1789 if (pred_begin(BB) == pred_end(BB) || BB->getSinglePredecessor() == BB) {
Bill Wendling0d45a092006-11-26 10:17:54 +00001790 DOUT << "Removing BB: \n" << *BB;
Chris Lattner71af9b02008-12-03 06:40:52 +00001791 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001792 return true;
1793 }
1794
Chris Lattner694e37f2003-08-17 19:41:53 +00001795 // Check to see if we can constant propagate this terminator instruction
1796 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001797 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00001798
Dan Gohman882d87d2008-03-11 21:53:06 +00001799 // If there is a trivial two-entry PHI node in this basic block, and we can
1800 // eliminate it, do so now.
1801 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1802 if (PN->getNumIncomingValues() == 2)
1803 Changed |= FoldTwoEntryPHINode(PN);
1804
Chris Lattner19831ec2004-02-16 06:35:48 +00001805 // If this is a returning block with only PHI nodes in it, fold the return
1806 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +00001807 //
1808 // If any predecessor is a conditional branch that just selects among
1809 // different return values, fold the replace the branch/return with a select
1810 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +00001811 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel2cc86a12009-02-05 00:30:42 +00001812 if (isTerminatorFirstRelevantInsn(BB, BB->getTerminator())) {
Chris Lattner147af6b2004-04-02 18:13:43 +00001813 // Find predecessors that end with branches.
Chris Lattner82442432008-02-18 07:42:56 +00001814 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1815 SmallVector<BranchInst*, 8> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +00001816 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1817 TerminatorInst *PTI = (*PI)->getTerminator();
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001818 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001819 if (BI->isUnconditional())
1820 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001821 else
1822 CondBranchPreds.push_back(BI);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001823 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001824 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001825
Chris Lattner19831ec2004-02-16 06:35:48 +00001826 // If we found some, do the transformation!
Bill Wendling1c855032009-03-03 19:25:16 +00001827 if (!UncondBranchPreds.empty()) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001828 while (!UncondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001829 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
Bill Wendling0d45a092006-11-26 10:17:54 +00001830 DOUT << "FOLDING: " << *BB
1831 << "INTO UNCOND BRANCH PRED: " << *Pred;
Chris Lattner19831ec2004-02-16 06:35:48 +00001832 Instruction *UncondBranch = Pred->getTerminator();
1833 // Clone the return and add it to the end of the predecessor.
Owen Anderson333c4002009-07-09 23:48:35 +00001834 Instruction *NewRet = RI->clone(*BB->getContext());
Chris Lattner19831ec2004-02-16 06:35:48 +00001835 Pred->getInstList().push_back(NewRet);
1836
Devang Patel5622f072009-02-24 00:05:16 +00001837 BasicBlock::iterator BBI = RI;
1838 if (BBI != BB->begin()) {
1839 // Move region end info into the predecessor.
1840 if (DbgRegionEndInst *DREI = dyn_cast<DbgRegionEndInst>(--BBI))
1841 DREI->moveBefore(NewRet);
1842 }
1843
Chris Lattner19831ec2004-02-16 06:35:48 +00001844 // If the return instruction returns a value, and if the value was a
1845 // PHI node in "BB", propagate the right value into the return.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001846 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1847 i != e; ++i)
1848 if (PHINode *PN = dyn_cast<PHINode>(*i))
Chris Lattner19831ec2004-02-16 06:35:48 +00001849 if (PN->getParent() == BB)
Gabor Greiff7ea3632008-06-10 22:03:26 +00001850 *i = PN->getIncomingValueForBlock(Pred);
Chris Lattnerffba5822008-04-28 00:19:07 +00001851
Chris Lattner19831ec2004-02-16 06:35:48 +00001852 // Update any PHI nodes in the returning block to realize that we no
1853 // longer branch to them.
1854 BB->removePredecessor(Pred);
1855 Pred->getInstList().erase(UncondBranch);
1856 }
1857
1858 // If we eliminated all predecessors of the block, delete the block now.
1859 if (pred_begin(BB) == pred_end(BB))
1860 // We know there are no successors, so just nuke the block.
Devang Patel5622f072009-02-24 00:05:16 +00001861 M->getBasicBlockList().erase(BB);
Chris Lattner19831ec2004-02-16 06:35:48 +00001862
Chris Lattner19831ec2004-02-16 06:35:48 +00001863 return true;
1864 }
Chris Lattner147af6b2004-04-02 18:13:43 +00001865
1866 // Check out all of the conditional branches going to this return
1867 // instruction. If any of them just select between returns, change the
1868 // branch itself into a select/return pair.
1869 while (!CondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001870 BranchInst *BI = CondBranchPreds.pop_back_val();
Chris Lattner147af6b2004-04-02 18:13:43 +00001871
1872 // Check to see if the non-BB successor is also a return block.
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001873 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1874 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1875 SimplifyCondBranchToTwoReturns(BI))
1876 return true;
Chris Lattner147af6b2004-04-02 18:13:43 +00001877 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001878 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001879 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattnere14ea082004-02-24 05:54:22 +00001880 // Check to see if the first instruction in this block is just an unwind.
1881 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001882 // destination with call instructions, and any unconditional branch
1883 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001884 //
Chris Lattner82442432008-02-18 07:42:56 +00001885 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnere14ea082004-02-24 05:54:22 +00001886 while (!Preds.empty()) {
1887 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001888 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
Nick Lewycky280a6e62008-04-25 16:53:59 +00001889 if (BI->isUnconditional()) {
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001890 Pred->getInstList().pop_back(); // nuke uncond branch
1891 new UnwindInst(Pred); // Use unwind.
1892 Changed = true;
1893 }
Nick Lewycky3f4cc312008-03-09 07:50:37 +00001894 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001895 if (II->getUnwindDest() == BB) {
1896 // Insert a new branch instruction before the invoke, because this
1897 // is now a fall through...
Gabor Greif051a9502008-04-06 20:25:17 +00001898 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattnere14ea082004-02-24 05:54:22 +00001899 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001900
Chris Lattnere14ea082004-02-24 05:54:22 +00001901 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00001902 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00001903 CallInst *CI = CallInst::Create(II->getCalledValue(),
Gabor Greiff7ea3632008-06-10 22:03:26 +00001904 Args.begin(), Args.end(),
1905 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001906 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00001907 CI->setAttributes(II->getAttributes());
Chris Lattnere14ea082004-02-24 05:54:22 +00001908 // If the invoke produced a value, the Call now does instead
1909 II->replaceAllUsesWith(CI);
1910 delete II;
1911 Changed = true;
1912 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001913
Chris Lattnere14ea082004-02-24 05:54:22 +00001914 Preds.pop_back();
1915 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001916
1917 // If this block is now dead, remove it.
1918 if (pred_begin(BB) == pred_end(BB)) {
1919 // We know there are no successors, so just nuke the block.
1920 M->getBasicBlockList().erase(BB);
1921 return true;
1922 }
1923
Chris Lattner623369a2005-02-24 06:17:52 +00001924 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1925 if (isValueEqualityComparison(SI)) {
1926 // If we only have one predecessor, and if it is a branch on this value,
1927 // see if that predecessor totally determines the outcome of this switch.
1928 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1929 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1930 return SimplifyCFG(BB) || 1;
1931
1932 // If the block only contains the switch, see if we can fold the block
1933 // away into any preds.
Zhou Sheng9a7c7432009-02-25 15:34:27 +00001934 BasicBlock::iterator BBI = BB->begin();
1935 // Ignore dbg intrinsics.
1936 while (isa<DbgInfoIntrinsic>(BBI))
1937 ++BBI;
1938 if (SI == &*BBI)
Chris Lattner623369a2005-02-24 06:17:52 +00001939 if (FoldValueComparisonIntoPredecessors(SI))
1940 return SimplifyCFG(BB) || 1;
1941 }
Chris Lattner542f1492004-02-28 21:28:10 +00001942 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001943 if (BI->isUnconditional()) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001944 BasicBlock::iterator BBI = BB->getFirstNonPHI();
Chris Lattner7e663482005-08-03 00:11:16 +00001945
1946 BasicBlock *Succ = BI->getSuccessor(0);
Devang Pateld0a203d2009-02-04 21:39:48 +00001947 // Ignore dbg intrinsics.
1948 while (isa<DbgInfoIntrinsic>(BBI))
1949 ++BBI;
Chris Lattner7e663482005-08-03 00:11:16 +00001950 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1951 Succ != BB) // Don't hurt infinite loops!
1952 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
Chris Lattner1347e872008-07-13 21:12:01 +00001953 return true;
Chris Lattner7e663482005-08-03 00:11:16 +00001954
1955 } else { // Conditional branch
Reid Spencer3ed469c2006-11-02 20:25:50 +00001956 if (isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001957 // If we only have one predecessor, and if it is a branch on this value,
1958 // see if that predecessor totally determines the outcome of this
1959 // switch.
1960 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1961 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1962 return SimplifyCFG(BB) || 1;
1963
Chris Lattnere67fa052004-05-01 23:35:43 +00001964 // This block must be empty, except for the setcond inst, if it exists.
Devang Patel556b20a2009-02-04 01:06:11 +00001965 // Ignore dbg intrinsics.
Chris Lattnere67fa052004-05-01 23:35:43 +00001966 BasicBlock::iterator I = BB->begin();
Devang Pateld0a203d2009-02-04 21:39:48 +00001967 // Ignore dbg intrinsics.
Devang Patel556b20a2009-02-04 01:06:11 +00001968 while (isa<DbgInfoIntrinsic>(I))
Devang Pateld0a203d2009-02-04 21:39:48 +00001969 ++I;
1970 if (&*I == BI) {
Chris Lattnere67fa052004-05-01 23:35:43 +00001971 if (FoldValueComparisonIntoPredecessors(BI))
1972 return SimplifyCFG(BB) | true;
Devang Pateld0a203d2009-02-04 21:39:48 +00001973 } else if (&*I == cast<Instruction>(BI->getCondition())){
1974 ++I;
1975 // Ignore dbg intrinsics.
1976 while (isa<DbgInfoIntrinsic>(I))
1977 ++I;
1978 if(&*I == BI) {
1979 if (FoldValueComparisonIntoPredecessors(BI))
1980 return SimplifyCFG(BB) | true;
1981 }
1982 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001983 }
Devang Pateld0a203d2009-02-04 21:39:48 +00001984
Chris Lattnereaba3a12005-09-19 23:49:37 +00001985 // If this is a branch on a phi node in the current block, thread control
1986 // through this block if any PHI node entries are constants.
1987 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1988 if (PN->getParent() == BI->getParent())
1989 if (FoldCondBranchOnPHI(BI))
1990 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00001991
1992 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1993 // branches to us and one of our successors, fold the setcc into the
1994 // predecessor and use logical operations to pick the right destination.
Chris Lattner1347e872008-07-13 21:12:01 +00001995 if (FoldBranchToCommonDest(BI))
1996 return SimplifyCFG(BB) | 1;
Chris Lattnere67fa052004-05-01 23:35:43 +00001997
Chris Lattner867661a2008-07-13 21:53:26 +00001998
1999 // Scan predecessor blocks for conditional branches.
Chris Lattner2e42e362005-09-20 00:43:16 +00002000 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2001 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner867661a2008-07-13 21:53:26 +00002002 if (PBI != BI && PBI->isConditional())
2003 if (SimplifyCondBranchToCondBranch(PBI, BI))
2004 return SimplifyCFG(BB) | true;
Chris Lattnerd52c2612004-02-24 07:23:58 +00002005 }
Chris Lattner698f96f2004-10-18 04:07:22 +00002006 } else if (isa<UnreachableInst>(BB->getTerminator())) {
2007 // If there are any instructions immediately before the unreachable that can
2008 // be removed, do so.
2009 Instruction *Unreachable = BB->getTerminator();
2010 while (Unreachable != BB->begin()) {
2011 BasicBlock::iterator BBI = Unreachable;
2012 --BBI;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002013 // Do not delete instructions that can have side effects, like calls
2014 // (which may never return) and volatile loads and stores.
Dale Johannesen80b8a622009-03-12 17:42:45 +00002015 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002016
2017 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2018 if (SI->isVolatile())
2019 break;
2020
2021 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2022 if (LI->isVolatile())
2023 break;
2024
Chris Lattner698f96f2004-10-18 04:07:22 +00002025 // Delete this instruction
2026 BB->getInstList().erase(BBI);
2027 Changed = true;
2028 }
2029
2030 // If the unreachable instruction is the first in the block, take a gander
2031 // at all of the predecessors of this instruction, and simplify them.
2032 if (&BB->front() == Unreachable) {
Chris Lattner82442432008-02-18 07:42:56 +00002033 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner698f96f2004-10-18 04:07:22 +00002034 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2035 TerminatorInst *TI = Preds[i]->getTerminator();
2036
2037 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2038 if (BI->isUnconditional()) {
2039 if (BI->getSuccessor(0) == BB) {
2040 new UnreachableInst(TI);
2041 TI->eraseFromParent();
2042 Changed = true;
2043 }
2044 } else {
2045 if (BI->getSuccessor(0) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002046 BranchInst::Create(BI->getSuccessor(1), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002047 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002048 } else if (BI->getSuccessor(1) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002049 BranchInst::Create(BI->getSuccessor(0), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002050 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002051 Changed = true;
2052 }
2053 }
2054 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2055 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2056 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00002057 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00002058 SI->removeCase(i);
2059 --i; --e;
2060 Changed = true;
2061 }
2062 // If the default value is unreachable, figure out the most popular
2063 // destination and make it the default.
2064 if (SI->getSuccessor(0) == BB) {
2065 std::map<BasicBlock*, unsigned> Popularity;
2066 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2067 Popularity[SI->getSuccessor(i)]++;
2068
2069 // Find the most popular block.
2070 unsigned MaxPop = 0;
2071 BasicBlock *MaxBlock = 0;
2072 for (std::map<BasicBlock*, unsigned>::iterator
2073 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2074 if (I->second > MaxPop) {
2075 MaxPop = I->second;
2076 MaxBlock = I->first;
2077 }
2078 }
2079 if (MaxBlock) {
2080 // Make this the new default, allowing us to delete any explicit
2081 // edges to it.
2082 SI->setSuccessor(0, MaxBlock);
2083 Changed = true;
2084
Chris Lattner42eb7522005-05-20 22:19:54 +00002085 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2086 // it.
2087 if (isa<PHINode>(MaxBlock->begin()))
2088 for (unsigned i = 0; i != MaxPop-1; ++i)
2089 MaxBlock->removePredecessor(SI->getParent());
2090
Chris Lattner698f96f2004-10-18 04:07:22 +00002091 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2092 if (SI->getSuccessor(i) == MaxBlock) {
2093 SI->removeCase(i);
2094 --i; --e;
2095 }
2096 }
2097 }
2098 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2099 if (II->getUnwindDest() == BB) {
2100 // Convert the invoke to a call instruction. This would be a good
2101 // place to note that the call does not throw though.
Gabor Greif051a9502008-04-06 20:25:17 +00002102 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattner698f96f2004-10-18 04:07:22 +00002103 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00002104
Chris Lattner698f96f2004-10-18 04:07:22 +00002105 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00002106 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00002107 CallInst *CI = CallInst::Create(II->getCalledValue(),
2108 Args.begin(), Args.end(),
2109 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00002110 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00002111 CI->setAttributes(II->getAttributes());
Chris Lattner698f96f2004-10-18 04:07:22 +00002112 // If the invoke produced a value, the Call does now instead.
2113 II->replaceAllUsesWith(CI);
2114 delete II;
2115 Changed = true;
2116 }
2117 }
2118 }
2119
2120 // If this block is now dead, remove it.
2121 if (pred_begin(BB) == pred_end(BB)) {
2122 // We know there are no successors, so just nuke the block.
2123 M->getBasicBlockList().erase(BB);
2124 return true;
2125 }
2126 }
Chris Lattner19831ec2004-02-16 06:35:48 +00002127 }
2128
Chris Lattner01d1ee32002-05-21 20:50:24 +00002129 // Merge basic blocks into their predecessor if there is only one distinct
2130 // pred, and if there is only one distinct successor of the predecessor, and
2131 // if there are no PHI nodes.
2132 //
Owen Andersoncfa94192008-07-18 17:49:43 +00002133 if (MergeBlockIntoPredecessor(BB))
2134 return true;
2135
2136 // Otherwise, if this block only has a single predecessor, and if that block
2137 // is a conditional branch, see if we can hoist any code from this block up
2138 // into our predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00002139 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
2140 BasicBlock *OnlyPred = *PI++;
2141 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
2142 if (*PI != OnlyPred) {
2143 OnlyPred = 0; // There are multiple different predecessors...
2144 break;
2145 }
Owen Andersoncfa94192008-07-18 17:49:43 +00002146
Chris Lattner37dc9382004-11-30 00:29:14 +00002147 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00002148 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
2149 if (BI->isConditional()) {
2150 // Get the other block.
2151 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
2152 PI = pred_begin(OtherBB);
2153 ++PI;
Owen Andersoncfa94192008-07-18 17:49:43 +00002154
Chris Lattner76134372004-12-10 17:42:31 +00002155 if (PI == pred_end(OtherBB)) {
2156 // We have a conditional branch to two blocks that are only reachable
2157 // from the condbr. We know that the condbr dominates the two blocks,
2158 // so see if there is any identical code in the "then" and "else"
2159 // blocks. If so, we can hoist it up to the branching block.
2160 Changed |= HoistThenElseCodeToIf(BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00002161 } else {
Owen Andersoncfa94192008-07-18 17:49:43 +00002162 BasicBlock* OnlySucc = NULL;
Evan Cheng4d09efd2008-06-07 08:52:29 +00002163 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
2164 SI != SE; ++SI) {
2165 if (!OnlySucc)
2166 OnlySucc = *SI;
2167 else if (*SI != OnlySucc) {
2168 OnlySucc = 0; // There are multiple distinct successors!
2169 break;
2170 }
2171 }
2172
2173 if (OnlySucc == OtherBB) {
2174 // If BB's only successor is the other successor of the predecessor,
2175 // i.e. a triangle, see if we can hoist any code from this block up
2176 // to the "if" block.
2177 Changed |= SpeculativelyExecuteBB(BI, BB);
2178 }
Chris Lattner76134372004-12-10 17:42:31 +00002179 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002180 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002181
Chris Lattner0d560082004-02-24 05:38:11 +00002182 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2183 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2184 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2185 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
2186 Instruction *Cond = cast<Instruction>(BI->getCondition());
2187 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2188 // 'setne's and'ed together, collect them.
2189 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00002190 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00002191 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
Chris Lattner42a75512007-01-15 02:27:26 +00002192 if (CompVal && CompVal->getType()->isInteger()) {
Chris Lattner0d560082004-02-24 05:38:11 +00002193 // There might be duplicate constants in the list, which the switch
2194 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00002195 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00002196 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00002197
Chris Lattner0d560082004-02-24 05:38:11 +00002198 // Figure out which block is which destination.
2199 BasicBlock *DefaultBB = BI->getSuccessor(1);
2200 BasicBlock *EdgeBB = BI->getSuccessor(0);
2201 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002202
Chris Lattner0d560082004-02-24 05:38:11 +00002203 // Create the new switch instruction now.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00002204 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
2205 Values.size(), BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00002206
Chris Lattner0d560082004-02-24 05:38:11 +00002207 // Add all of the 'cases' to the switch instruction.
2208 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2209 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002210
Chris Lattner0d560082004-02-24 05:38:11 +00002211 // We added edges from PI to the EdgeBB. As such, if there were any
2212 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2213 // the number of edges added.
2214 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00002215 isa<PHINode>(BBI); ++BBI) {
2216 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00002217 Value *InVal = PN->getIncomingValueForBlock(*PI);
2218 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2219 PN->addIncoming(InVal, *PI);
2220 }
2221
2222 // Erase the old branch instruction.
Eli Friedman080efb82008-12-16 20:54:32 +00002223 EraseTerminatorInstAndDCECond(BI);
Chris Lattner0d560082004-02-24 05:38:11 +00002224 return true;
2225 }
2226 }
2227
Chris Lattner694e37f2003-08-17 19:41:53 +00002228 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002229}