blob: 9bb61b6041cedc521b60932f221787b2b3f531cf [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"
Chris Lattner0d560082004-02-24 05:38:11 +000019#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000020#include "llvm/DerivedTypes.h"
Dale Johannesenf8bc3002009-05-13 18:25:07 +000021#include "llvm/GlobalVariable.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000022#include "llvm/Analysis/InstructionSimplify.h"
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000023#include "llvm/Target/TargetData.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman2c635662009-10-30 22:39:04 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000027#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng502a4f52008-06-12 21:15:59 +000028#include "llvm/ADT/Statistic.h"
Chris Lattner6d4d21e2010-12-13 02:00:58 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000030#include "llvm/Support/CFG.h"
Chris Lattnere27db742010-12-17 06:20:15 +000031#include "llvm/Support/ConstantRange.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000034#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000035#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000036#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Evan Cheng502a4f52008-06-12 21:15:59 +000039STATISTIC(NumSpeculations, "Number of speculative executed instructions");
40
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000041namespace {
42class SimplifyCFGOpt {
43 const TargetData *const TD;
44
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000045 Value *isValueEqualityComparison(TerminatorInst *TI);
46 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
47 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
48 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
49 BasicBlock *Pred);
50 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI);
51
Chris Lattner3d512132010-12-13 06:25:44 +000052 bool SimplifyReturn(ReturnInst *RI);
53 bool SimplifyUnwind(UnwindInst *UI);
54 bool SimplifyUnreachable(UnreachableInst *UI);
55 bool SimplifySwitch(SwitchInst *SI);
56 bool SimplifyIndirectBr(IndirectBrInst *IBI);
57 bool SimplifyUncondBranch(BranchInst *BI);
58 bool SimplifyCondBranch(BranchInst *BI);
59
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000060public:
61 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
62 bool run(BasicBlock *BB);
63};
64}
65
Chris Lattner2bdcb562005-08-03 00:19:45 +000066/// SafeToMergeTerminators - Return true if it is safe to merge these two
67/// terminator instructions together.
68///
69static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
70 if (SI1 == SI2) return false; // Can't merge with self!
71
72 // It is not safe to merge these two switch instructions if they have a common
73 // successor, and if that successor has a PHI node, and if *that* PHI node has
74 // conflicting incoming values from the two switch blocks.
75 BasicBlock *SI1BB = SI1->getParent();
76 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000077 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000078
79 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
80 if (SI1Succs.count(*I))
81 for (BasicBlock::iterator BBI = (*I)->begin();
82 isa<PHINode>(BBI); ++BBI) {
83 PHINode *PN = cast<PHINode>(BBI);
84 if (PN->getIncomingValueForBlock(SI1BB) !=
85 PN->getIncomingValueForBlock(SI2BB))
86 return false;
87 }
88
89 return true;
90}
91
92/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
93/// now be entries in it from the 'NewPred' block. The values that will be
94/// flowing into the PHI nodes will be the same as those coming in from
95/// ExistPred, an existing predecessor of Succ.
96static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
97 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +000098 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
99
Chris Lattner093a4382008-07-13 22:23:11 +0000100 PHINode *PN;
101 for (BasicBlock::iterator I = Succ->begin();
102 (PN = dyn_cast<PHINode>(I)); ++I)
103 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000104}
105
Chris Lattner7e663482005-08-03 00:11:16 +0000106
Chris Lattner73c50a62010-12-14 07:00:00 +0000107/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
108/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000109/// to an "if condition". If so, return the boolean condition that determines
110/// which entry into BB will be taken. Also, return by references the block
111/// that will be entered from if the condition is true, and the block that will
112/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000113///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000114/// This does no checking to see if the true/false blocks have large or unsavory
115/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000116static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
117 BasicBlock *&IfFalse) {
118 PHINode *SomePHI = cast<PHINode>(BB->begin());
119 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000120 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000121 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
122 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000123
124 // We can only handle branches. Other control flow will be lowered to
125 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000126 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
127 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
128 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000129 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000130
131 // Eliminate code duplication by ensuring that Pred1Br is conditional if
132 // either are.
133 if (Pred2Br->isConditional()) {
134 // If both branches are conditional, we don't have an "if statement". In
135 // reality, we could transform this case, but since the condition will be
136 // required anyway, we stand no chance of eliminating it, so the xform is
137 // probably not profitable.
138 if (Pred1Br->isConditional())
139 return 0;
140
141 std::swap(Pred1, Pred2);
142 std::swap(Pred1Br, Pred2Br);
143 }
144
145 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000146 // The only thing we have to watch out for here is to make sure that Pred2
147 // doesn't have incoming edges from other blocks. If it does, the condition
148 // doesn't dominate BB.
149 if (Pred2->getSinglePredecessor() == 0)
150 return 0;
151
Chris Lattner723c66d2004-02-11 03:36:04 +0000152 // If we found a conditional branch predecessor, make sure that it branches
153 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
154 if (Pred1Br->getSuccessor(0) == BB &&
155 Pred1Br->getSuccessor(1) == Pred2) {
156 IfTrue = Pred1;
157 IfFalse = Pred2;
158 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
159 Pred1Br->getSuccessor(1) == BB) {
160 IfTrue = Pred2;
161 IfFalse = Pred1;
162 } else {
163 // We know that one arm of the conditional goes to BB, so the other must
164 // go somewhere unrelated, and this must not be an "if statement".
165 return 0;
166 }
167
Chris Lattner723c66d2004-02-11 03:36:04 +0000168 return Pred1Br->getCondition();
169 }
170
171 // Ok, if we got here, both predecessors end with an unconditional branch to
172 // BB. Don't panic! If both blocks only have a single (identical)
173 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000174 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
175 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000176 return 0;
177
178 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000179 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
180 if (BI == 0) return 0;
181
182 assert(BI->isConditional() && "Two successors but not conditional?");
183 if (BI->getSuccessor(0) == Pred1) {
184 IfTrue = Pred1;
185 IfFalse = Pred2;
186 } else {
187 IfTrue = Pred2;
188 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000189 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000190 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000191}
192
Bill Wendling5049fa62009-01-19 23:43:56 +0000193/// DominatesMergePoint - If we have a merge point of an "if condition" as
194/// accepted above, return true if the specified value dominates the block. We
195/// don't handle the true generality of domination here, just a special case
196/// which works well enough for us.
197///
198/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
199/// see if V (which must be an instruction) is cheap to compute and is
200/// non-trapping. If both are true, the instruction is inserted into the set
201/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000202static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Chris Lattner44da7ca2010-12-14 07:41:39 +0000203 SmallPtrSet<Instruction*, 4> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000204 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000205 if (!I) {
206 // Non-instructions all dominate instructions, but not all constantexprs
207 // can be executed unconditionally.
208 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
209 if (C->canTrap())
210 return false;
211 return true;
212 }
Chris Lattner570751c2004-04-09 22:50:22 +0000213 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000214
Chris Lattnerda895d62005-02-27 06:18:25 +0000215 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000216 // the bottom of this block.
217 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000218
Chris Lattner570751c2004-04-09 22:50:22 +0000219 // If this instruction is defined in a block that contains an unconditional
220 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000221 // statement". If not, it definitely dominates the region.
222 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
223 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
224 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000225
Chris Lattner44da7ca2010-12-14 07:41:39 +0000226 // If we aren't allowing aggressive promotion anymore, then don't consider
227 // instructions in the 'if region'.
228 if (AggressiveInsts == 0) return false;
229
230 // Okay, it looks like the instruction IS in the "condition". Check to
231 // see if it's a cheap instruction to unconditionally compute, and if it
232 // only uses stuff defined outside of the condition. If so, hoist it out.
233 if (!I->isSafeToSpeculativelyExecute())
234 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000235
Chris Lattner44da7ca2010-12-14 07:41:39 +0000236 switch (I->getOpcode()) {
237 default: return false; // Cannot hoist this out safely.
238 case Instruction::Load:
239 // We have to check to make sure there are no instructions before the
240 // load in its basic block, as we are going to hoist the load out to its
241 // predecessor.
242 if (PBB->getFirstNonPHIOrDbg() != I)
243 return false;
244 break;
245 case Instruction::Add:
246 case Instruction::Sub:
247 case Instruction::And:
248 case Instruction::Or:
249 case Instruction::Xor:
250 case Instruction::Shl:
251 case Instruction::LShr:
252 case Instruction::AShr:
253 case Instruction::ICmp:
254 break; // These are all cheap and non-trapping instructions.
255 }
Chris Lattner570751c2004-04-09 22:50:22 +0000256
Chris Lattner44da7ca2010-12-14 07:41:39 +0000257 // Okay, we can only really hoist these out if their operands are not
258 // defined in the conditional region.
259 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
260 if (!DominatesMergePoint(*i, BB, 0))
261 return false;
262 // Okay, it's safe to do this! Remember this instruction.
263 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000264 return true;
265}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000266
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000267/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
268/// and PointerNullValue. Return NULL if value is not a constant int.
Chris Lattner28acc132010-12-13 03:30:12 +0000269static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000270 // Normal constant int.
271 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000272 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000273 return CI;
274
275 // This is some kind of pointer constant. Turn it into a pointer-sized
276 // ConstantInt if possible.
277 const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
278
279 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
280 if (isa<ConstantPointerNull>(V))
281 return ConstantInt::get(PtrTy, 0);
282
283 // IntToPtr const int.
284 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
285 if (CE->getOpcode() == Instruction::IntToPtr)
286 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
287 // The constant is very likely to have the right type already.
288 if (CI->getType() == PtrTy)
289 return CI;
290 else
291 return cast<ConstantInt>
292 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
293 }
294 return 0;
295}
296
Chris Lattner0aa749b2010-12-13 04:26:26 +0000297/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
298/// collection of icmp eq/ne instructions that compare a value against a
299/// constant, return the value being compared, and stick the constant into the
300/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000301static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000302GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
303 const TargetData *TD, bool isEQ) {
304 Instruction *I = dyn_cast<Instruction>(V);
305 if (I == 0) return 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000306
Chris Lattner7312a222010-12-13 04:50:38 +0000307 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000308 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Chris Lattnere27db742010-12-17 06:20:15 +0000309 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
310 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000311 Vals.push_back(C);
312 return I->getOperand(0);
313 }
Chris Lattnere27db742010-12-17 06:20:15 +0000314
315 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
316 // the set.
317 ConstantRange Span =
318 ConstantRange::makeICmpRegion(ICI->getPredicate(),
319 ConstantRange(C->getValue()));
320
321 // If this is an and/!= check then we want to optimize "x ugt 2" into
322 // x != 0 && x != 1.
323 if (!isEQ)
324 Span = Span.inverse();
325
326 // If there are a ton of values, we don't want to make a ginormous switch.
327 if (Span.getSetSize().getZExtValue() > 8 || Span.isEmptySet() ||
328 // We don't handle wrapped sets yet.
329 Span.isWrappedSet())
330 return 0;
331
332 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
333 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
334 return I->getOperand(0);
335 }
Chris Lattner662269d2010-12-13 04:18:32 +0000336 return 0;
337 }
338
Chris Lattner7312a222010-12-13 04:50:38 +0000339 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000340 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000341 return 0;
Chris Lattner662269d2010-12-13 04:18:32 +0000342
Chris Lattner7312a222010-12-13 04:50:38 +0000343 unsigned NumValsBeforeLHS = Vals.size();
Chris Lattner0aa749b2010-12-13 04:26:26 +0000344 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
345 isEQ)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000346 unsigned NumVals = Vals.size();
Chris Lattner0aa749b2010-12-13 04:26:26 +0000347 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
348 isEQ)) {
349 if (LHS == RHS)
350 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000351 Vals.resize(NumVals);
Chris Lattner0aa749b2010-12-13 04:26:26 +0000352 }
Chris Lattner7312a222010-12-13 04:50:38 +0000353
354 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
355 // set it and return success.
356 if (Extra == 0 || Extra == I->getOperand(1)) {
357 Extra = I->getOperand(1);
358 return LHS;
359 }
360
361 Vals.resize(NumValsBeforeLHS);
362 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000363 }
Chris Lattner7312a222010-12-13 04:50:38 +0000364
365 // If the LHS can't be folded in, but Extra is available and RHS can, try to
366 // use LHS as Extra.
367 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000368 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000369 Extra = I->getOperand(0);
370 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
371 isEQ))
372 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000373 assert(Vals.size() == NumValsBeforeLHS);
374 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000375 }
376
Chris Lattner0d560082004-02-24 05:38:11 +0000377 return 0;
378}
Chris Lattner0aa749b2010-12-13 04:26:26 +0000379
Eli Friedman080efb82008-12-16 20:54:32 +0000380static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
381 Instruction* Cond = 0;
382 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
383 Cond = dyn_cast<Instruction>(SI->getCondition());
384 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
385 if (BI->isConditional())
386 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000387 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
388 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000389 }
390
391 TI->eraseFromParent();
392 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
393}
394
Chris Lattner9fd49552008-11-27 23:25:44 +0000395/// isValueEqualityComparison - Return true if the specified terminator checks
396/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000397Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
398 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000399 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
400 // Do not permit merging of large switch instructions into their
401 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000402 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
403 pred_end(SI->getParent())) <= 128)
404 CV = SI->getCondition();
405 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000406 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000407 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
408 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
409 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000410 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000411 CV = ICI->getOperand(0);
412
413 // Unwrap any lossless ptrtoint cast.
414 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
415 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
416 CV = PTII->getOperand(0);
417 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000418}
419
Bill Wendling5049fa62009-01-19 23:43:56 +0000420/// GetValueEqualityComparisonCases - Given a value comparison instruction,
421/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000422BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000423GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000424 std::vector<std::pair<ConstantInt*,
425 BasicBlock*> > &Cases) {
426 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
427 Cases.reserve(SI->getNumCases());
428 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000429 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000430 return SI->getDefaultDest();
431 }
432
433 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000434 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Chris Lattner28acc132010-12-13 03:30:12 +0000435 Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000436 BI->getSuccessor(ICI->getPredicate() ==
437 ICmpInst::ICMP_NE)));
438 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000439}
440
441
Bill Wendling5049fa62009-01-19 23:43:56 +0000442/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
443/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000444static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000445 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
446 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
447 if (Cases[i].second == BB) {
448 Cases.erase(Cases.begin()+i);
449 --i; --e;
450 }
451}
452
Bill Wendling5049fa62009-01-19 23:43:56 +0000453/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
454/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000455static bool
456ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
457 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
458 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
459
460 // Make V1 be smaller than V2.
461 if (V1->size() > V2->size())
462 std::swap(V1, V2);
463
464 if (V1->size() == 0) return false;
465 if (V1->size() == 1) {
466 // Just scan V2.
467 ConstantInt *TheVal = (*V1)[0].first;
468 for (unsigned i = 0, e = V2->size(); i != e; ++i)
469 if (TheVal == (*V2)[i].first)
470 return true;
471 }
472
473 // Otherwise, just sort both lists and compare element by element.
Chris Lattnerfca20f52010-12-13 03:24:30 +0000474 array_pod_sort(V1->begin(), V1->end());
475 array_pod_sort(V2->begin(), V2->end());
Chris Lattner623369a2005-02-24 06:17:52 +0000476 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
477 while (i1 != e1 && i2 != e2) {
478 if ((*V1)[i1].first == (*V2)[i2].first)
479 return true;
480 if ((*V1)[i1].first < (*V2)[i2].first)
481 ++i1;
482 else
483 ++i2;
484 }
485 return false;
486}
487
Bill Wendling5049fa62009-01-19 23:43:56 +0000488/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
489/// terminator instruction and its block is known to only have a single
490/// predecessor block, check to see if that predecessor is also a value
491/// comparison with the same value, and if that comparison determines the
492/// outcome of this comparison. If so, simplify TI. This does a very limited
493/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000494bool SimplifyCFGOpt::
495SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
496 BasicBlock *Pred) {
Chris Lattner623369a2005-02-24 06:17:52 +0000497 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
498 if (!PredVal) return false; // Not a value comparison in predecessor.
499
500 Value *ThisVal = isValueEqualityComparison(TI);
501 assert(ThisVal && "This isn't a value comparison!!");
502 if (ThisVal != PredVal) return false; // Different predicates.
503
504 // Find out information about when control will move from Pred to TI's block.
505 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
506 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
507 PredCases);
508 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000509
Chris Lattner623369a2005-02-24 06:17:52 +0000510 // Find information about how control leaves this block.
511 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
512 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
513 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
514
515 // If TI's block is the default block from Pred's comparison, potentially
516 // simplify TI based on this knowledge.
517 if (PredDef == TI->getParent()) {
518 // If we are here, we know that the value is none of those cases listed in
519 // PredCases. If there are any cases in ThisCases that are in PredCases, we
520 // can simplify TI.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000521 if (!ValuesOverlap(PredCases, ThisCases))
522 return false;
523
524 if (isa<BranchInst>(TI)) {
525 // Okay, one of the successors of this condbr is dead. Convert it to a
526 // uncond br.
527 assert(ThisCases.size() == 1 && "Branch can only have one case!");
528 // Insert the new branch.
529 Instruction *NI = BranchInst::Create(ThisDef, TI);
530 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000531
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000532 // Remove PHI node entries for the dead edge.
533 ThisCases[0].second->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000534
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000535 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
536 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000537
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000538 EraseTerminatorInstAndDCECond(TI);
539 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000540 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000541
542 SwitchInst *SI = cast<SwitchInst>(TI);
543 // Okay, TI has cases that are statically dead, prune them away.
544 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000545 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000546 DeadCases.insert(PredCases[i].first);
Chris Lattner623369a2005-02-24 06:17:52 +0000547
David Greene89d6fd32010-01-05 01:26:52 +0000548 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000549 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000550
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000551 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
552 if (DeadCases.count(SI->getCaseValue(i))) {
553 SI->getSuccessor(i)->removePredecessor(TI->getParent());
554 SI->removeCase(i);
555 }
556
557 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000558 return true;
559 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000560
561 // Otherwise, TI's block must correspond to some matched value. Find out
562 // which value (or set of values) this is.
563 ConstantInt *TIV = 0;
564 BasicBlock *TIBB = TI->getParent();
565 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
566 if (PredCases[i].second == TIBB) {
567 if (TIV != 0)
568 return false; // Cannot handle multiple values coming to this block.
569 TIV = PredCases[i].first;
570 }
571 assert(TIV && "No edge from pred to succ?");
572
573 // Okay, we found the one constant that our value can be if we get into TI's
574 // BB. Find out which successor will unconditionally be branched to.
575 BasicBlock *TheRealDest = 0;
576 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
577 if (ThisCases[i].first == TIV) {
578 TheRealDest = ThisCases[i].second;
579 break;
580 }
581
582 // If not handled by any explicit cases, it is handled by the default case.
583 if (TheRealDest == 0) TheRealDest = ThisDef;
584
585 // Remove PHI node entries for dead edges.
586 BasicBlock *CheckEdge = TheRealDest;
587 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
588 if (*SI != CheckEdge)
589 (*SI)->removePredecessor(TIBB);
590 else
591 CheckEdge = 0;
592
593 // Insert the new branch.
594 Instruction *NI = BranchInst::Create(TheRealDest, TI);
595 (void) NI;
596
597 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
598 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
599
600 EraseTerminatorInstAndDCECond(TI);
601 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000602}
603
Dale Johannesenc81f5442009-03-12 21:01:11 +0000604namespace {
605 /// ConstantIntOrdering - This class implements a stable ordering of constant
606 /// integers that does not depend on their address. This is important for
607 /// applications that sort ConstantInt's to ensure uniqueness.
608 struct ConstantIntOrdering {
609 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
610 return LHS->getValue().ult(RHS->getValue());
611 }
612 };
613}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000614
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000615static int ConstantIntSortPredicate(const void *P1, const void *P2) {
616 const ConstantInt *LHS = *(const ConstantInt**)P1;
617 const ConstantInt *RHS = *(const ConstantInt**)P2;
Chris Lattnerba3c8152010-12-15 04:52:41 +0000618 if (LHS->getValue().ult(RHS->getValue()))
619 return 1;
620 if (LHS->getValue() == RHS->getValue())
621 return 0;
622 return -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000623}
624
Bill Wendling5049fa62009-01-19 23:43:56 +0000625/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
626/// equality comparison instruction (either a switch or a branch on "X == c").
627/// See if any of the predecessors of the terminator block are value comparisons
628/// on the same value. If so, and if safe to do so, fold them together.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000629bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
Chris Lattner542f1492004-02-28 21:28:10 +0000630 BasicBlock *BB = TI->getParent();
631 Value *CV = isValueEqualityComparison(TI); // CondVal
632 assert(CV && "Not a comparison?");
633 bool Changed = false;
634
Chris Lattner82442432008-02-18 07:42:56 +0000635 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000636 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000637 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000638
Chris Lattner542f1492004-02-28 21:28:10 +0000639 // See if the predecessor is a comparison with the same value.
640 TerminatorInst *PTI = Pred->getTerminator();
641 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
642
643 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
644 // Figure out which 'cases' to copy from SI to PSI.
645 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
646 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
647
648 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
649 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
650
651 // Based on whether the default edge from PTI goes to BB or not, fill in
652 // PredCases and PredDefault with the new switch cases we would like to
653 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000654 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000655
656 if (PredDefault == BB) {
657 // If this is the default destination from PTI, only the edges in TI
658 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000659 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000660 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
661 if (PredCases[i].second != BB)
662 PTIHandled.insert(PredCases[i].first);
663 else {
664 // The default destination is BB, we don't need explicit targets.
665 std::swap(PredCases[i], PredCases.back());
666 PredCases.pop_back();
667 --i; --e;
668 }
669
670 // Reconstruct the new switch statement we will be building.
671 if (PredDefault != BBDefault) {
672 PredDefault->removePredecessor(Pred);
673 PredDefault = BBDefault;
674 NewSuccessors.push_back(BBDefault);
675 }
676 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
677 if (!PTIHandled.count(BBCases[i].first) &&
678 BBCases[i].second != BBDefault) {
679 PredCases.push_back(BBCases[i]);
680 NewSuccessors.push_back(BBCases[i].second);
681 }
682
683 } else {
684 // If this is not the default destination from PSI, only the edges
685 // in SI that occur in PSI with a destination of BB will be
686 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000687 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000688 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
689 if (PredCases[i].second == BB) {
690 PTIHandled.insert(PredCases[i].first);
691 std::swap(PredCases[i], PredCases.back());
692 PredCases.pop_back();
693 --i; --e;
694 }
695
696 // Okay, now we know which constants were sent to BB from the
697 // predecessor. Figure out where they will all go now.
698 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
699 if (PTIHandled.count(BBCases[i].first)) {
700 // If this is one we are capable of getting...
701 PredCases.push_back(BBCases[i]);
702 NewSuccessors.push_back(BBCases[i].second);
703 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
704 }
705
706 // If there are any constants vectored to BB that TI doesn't handle,
707 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000708 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
709 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000710 E = PTIHandled.end(); I != E; ++I) {
711 PredCases.push_back(std::make_pair(*I, BBDefault));
712 NewSuccessors.push_back(BBDefault);
713 }
714 }
715
716 // Okay, at this point, we know which new successor Pred will get. Make
717 // sure we update the number of entries in the PHI nodes for these
718 // successors.
719 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
720 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
721
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000722 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000723 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000724 assert(TD && "Cannot switch on pointer without TargetData");
725 CV = new PtrToIntInst(CV, TD->getIntPtrType(CV->getContext()),
726 "magicptr", PTI);
727 }
728
Chris Lattner542f1492004-02-28 21:28:10 +0000729 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000730 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
731 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000732 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
733 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000734
Eli Friedman080efb82008-12-16 20:54:32 +0000735 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000736
Chris Lattner542f1492004-02-28 21:28:10 +0000737 // Okay, last check. If BB is still a successor of PSI, then we must
738 // have an infinite loop case. If so, add an infinitely looping block
739 // to handle the case to preserve the behavior of the code.
740 BasicBlock *InfLoopBlock = 0;
741 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
742 if (NewSI->getSuccessor(i) == BB) {
743 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000744 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000745 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +0000746 InfLoopBlock = BasicBlock::Create(BB->getContext(),
747 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +0000748 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000749 }
750 NewSI->setSuccessor(i, InfLoopBlock);
751 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000752
Chris Lattner542f1492004-02-28 21:28:10 +0000753 Changed = true;
754 }
755 }
756 return Changed;
757}
758
Dale Johannesenc1f10402009-06-15 20:59:27 +0000759// isSafeToHoistInvoke - If we would need to insert a select that uses the
760// value of this invoke (comments in HoistThenElseCodeToIf explain why we
761// would need to do this), we can't hoist the invoke, as there is nowhere
762// to put the select in this case.
763static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
764 Instruction *I1, Instruction *I2) {
765 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
766 PHINode *PN;
767 for (BasicBlock::iterator BBI = SI->begin();
768 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
769 Value *BB1V = PN->getIncomingValueForBlock(BB1);
770 Value *BB2V = PN->getIncomingValueForBlock(BB2);
771 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
772 return false;
773 }
774 }
775 }
776 return true;
777}
778
Chris Lattner6306d072005-08-03 17:59:45 +0000779/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000780/// BB2, hoist any common code in the two blocks up into the branch block. The
781/// caller of this function guarantees that BI's block dominates BB1 and BB2.
782static bool HoistThenElseCodeToIf(BranchInst *BI) {
783 // This does very trivial matching, with limited scanning, to find identical
784 // instructions in the two blocks. In particular, we don't want to get into
785 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
786 // such, we currently just scan for obviously identical instructions in an
787 // identical order.
788 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
789 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
790
Devang Patel65085cf2009-02-04 00:03:08 +0000791 BasicBlock::iterator BB1_Itr = BB1->begin();
792 BasicBlock::iterator BB2_Itr = BB2->begin();
793
794 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
795 while (isa<DbgInfoIntrinsic>(I1))
796 I1 = BB1_Itr++;
797 while (isa<DbgInfoIntrinsic>(I2))
798 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000799 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000800 !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +0000801 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000802 return false;
803
804 // If we get here, we can hoist at least one instruction.
805 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000806
807 do {
808 // If we are hoisting the terminator instruction, don't move one (making a
809 // broken BB), instead clone it, and remove BI.
810 if (isa<TerminatorInst>(I1))
811 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000812
Chris Lattner37dc9382004-11-30 00:29:14 +0000813 // For a normal instruction, we just move one to right before the branch,
814 // then replace all uses of the other with the first. Finally, we remove
815 // the now redundant second instruction.
816 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
817 if (!I2->use_empty())
818 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000819 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +0000820 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000821
Devang Patel65085cf2009-02-04 00:03:08 +0000822 I1 = BB1_Itr++;
823 while (isa<DbgInfoIntrinsic>(I1))
824 I1 = BB1_Itr++;
825 I2 = BB2_Itr++;
826 while (isa<DbgInfoIntrinsic>(I2))
827 I2 = BB2_Itr++;
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000828 } while (I1->getOpcode() == I2->getOpcode() &&
829 I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +0000830
831 return true;
832
833HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000834 // It may not be possible to hoist an invoke.
835 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
836 return true;
837
Chris Lattner37dc9382004-11-30 00:29:14 +0000838 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +0000839 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +0000840 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +0000841 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000842 I1->replaceAllUsesWith(NT);
843 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000844 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000845 }
846
847 // Hoisting one of the terminators from our successor is a great thing.
848 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
849 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
850 // nodes, so we insert select instruction to compute the final result.
851 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
852 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
853 PHINode *PN;
854 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000855 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000856 Value *BB1V = PN->getIncomingValueForBlock(BB1);
857 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000858 if (BB1V == BB2V) continue;
859
860 // These values do not agree. Insert a select instruction before NT
861 // that determines the right value.
862 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
863 if (SI == 0)
864 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
865 BB1V->getName()+"."+BB2V->getName(), NT);
866 // Make the PHI node use the select for all incoming values for BB1/BB2
867 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
868 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
869 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000870 }
871 }
872
873 // Update any PHI nodes in our new successors.
874 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
875 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000876
Eli Friedman080efb82008-12-16 20:54:32 +0000877 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000878 return true;
879}
880
Evan Cheng4d09efd2008-06-07 08:52:29 +0000881/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
882/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
883/// (for now, restricted to a single instruction that's side effect free) from
884/// the BB1 into the branch block to speculatively execute it.
885static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
886 // Only speculatively execution a single instruction (not counting the
887 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000888 Instruction *HInst = NULL;
889 Instruction *Term = BB1->getTerminator();
890 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
891 BBI != BBE; ++BBI) {
892 Instruction *I = BBI;
893 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000894 if (isa<DbgInfoIntrinsic>(I)) continue;
895 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +0000896
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000897 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +0000898 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000899 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +0000900 }
901 if (!HInst)
902 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000903
Evan Cheng797d9512008-06-11 19:18:20 +0000904 // Be conservative for now. FP select instruction can often be expensive.
905 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000906 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +0000907 return false;
908
Evan Cheng4d09efd2008-06-07 08:52:29 +0000909 // If BB1 is actually on the false edge of the conditional branch, remember
910 // to swap the select operands later.
911 bool Invert = false;
912 if (BB1 != BI->getSuccessor(0)) {
913 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
914 Invert = true;
915 }
916
917 // Turn
918 // BB:
919 // %t1 = icmp
920 // br i1 %t1, label %BB1, label %BB2
921 // BB1:
922 // %t3 = add %t2, c
923 // br label BB2
924 // BB2:
925 // =>
926 // BB:
927 // %t1 = icmp
928 // %t4 = add %t2, c
929 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +0000930 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +0000931 default: return false; // Not safe / profitable to hoist.
932 case Instruction::Add:
933 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000934 // Not worth doing for vector ops.
Duncan Sands1df98592010-02-16 11:11:14 +0000935 if (HInst->getType()->isVectorTy())
Chris Lattner9dd3b612009-01-18 23:22:07 +0000936 return false;
937 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000938 case Instruction::And:
939 case Instruction::Or:
940 case Instruction::Xor:
941 case Instruction::Shl:
942 case Instruction::LShr:
943 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +0000944 // Don't mess with vector operations.
Duncan Sands1df98592010-02-16 11:11:14 +0000945 if (HInst->getType()->isVectorTy())
Evan Chenge5334ea2008-06-25 07:50:12 +0000946 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000947 break; // These are all cheap and non-trapping instructions.
948 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000949
950 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +0000951 if (HInst->use_empty()) {
952 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000953 return true;
954 }
Evan Cheng4d09efd2008-06-07 08:52:29 +0000955
956 // Can we speculatively execute the instruction? And what is the value
957 // if the condition is false? Consider the phi uses, if the incoming value
958 // from the "if" block are all the same V, then V is the value of the
959 // select if the condition is false.
960 BasicBlock *BIParent = BI->getParent();
961 SmallVector<PHINode*, 4> PHIUses;
962 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000963
964 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +0000965 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +0000966 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000967 // Ignore any user that is not a PHI node in BB2. These can only occur in
968 // unreachable blocks, because they would not be dominated by the instr.
Gabor Greif20361b92010-07-22 11:43:44 +0000969 PHINode *PN = dyn_cast<PHINode>(*UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000970 if (!PN || PN->getParent() != BB2)
971 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000972 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000973
Evan Cheng4d09efd2008-06-07 08:52:29 +0000974 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
975 if (!FalseV)
976 FalseV = PHIV;
977 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000978 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +0000979 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000980
981 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +0000982
Evan Cheng502a4f52008-06-12 21:15:59 +0000983 // Do not hoist the instruction if any of its operands are defined but not
984 // used in this BB. The transformation will prevent the operand from
985 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +0000986 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
987 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +0000988 Instruction *OpI = dyn_cast<Instruction>(*i);
989 if (OpI && OpI->getParent() == BIParent &&
990 !OpI->isUsedInBasicBlock(BIParent))
991 return false;
992 }
993
Devang Patel3d0a9a32008-09-18 22:50:42 +0000994 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +0000995 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +0000996 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +0000997 if (InsertPos != BIParent->begin())
998 --InsertPos;
999 // Skip debug info between condition and branch.
1000 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +00001001 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +00001002 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +00001003 SmallPtrSet<Instruction *, 4> BB1Insns;
1004 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
1005 BB1I != BB1E; ++BB1I)
1006 BB1Insns.insert(BB1I);
1007 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1008 UI != UE; ++UI) {
1009 Instruction *Use = cast<Instruction>(*UI);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001010 if (!BB1Insns.count(Use)) continue;
1011
1012 // If BrCond uses the instruction that place it just before
1013 // branch instruction.
1014 InsertPos = BI;
1015 break;
Devang Patel3d0a9a32008-09-18 22:50:42 +00001016 }
1017 } else
1018 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +00001019 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001020
1021 // Create a select whose true value is the speculatively executed value and
1022 // false value is the previously determined FalseV.
1023 SelectInst *SI;
1024 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +00001025 SI = SelectInst::Create(BrCond, FalseV, HInst,
1026 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001027 else
Devang Patel06b1e672009-03-06 06:00:17 +00001028 SI = SelectInst::Create(BrCond, HInst, FalseV,
1029 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001030
1031 // Make the PHI node use the select for all incoming values for "then" and
1032 // "if" blocks.
1033 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1034 PHINode *PN = PHIUses[i];
1035 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001036 if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
Evan Cheng4d09efd2008-06-07 08:52:29 +00001037 PN->setIncomingValue(j, SI);
1038 }
1039
Evan Cheng502a4f52008-06-12 21:15:59 +00001040 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001041 return true;
1042}
1043
Chris Lattner2e42e362005-09-20 00:43:16 +00001044/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1045/// across this block.
1046static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1047 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001048 unsigned Size = 0;
1049
Devang Patel9200c892009-03-10 18:00:05 +00001050 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001051 if (isa<DbgInfoIntrinsic>(BBI))
1052 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001053 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001054 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001055
Dale Johannesen8483e542009-03-12 23:18:09 +00001056 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001057 // live outside of the current basic block.
1058 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1059 UI != E; ++UI) {
1060 Instruction *U = cast<Instruction>(*UI);
1061 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1062 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001063
1064 // Looks ok, continue checking.
1065 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001066
Chris Lattner2e42e362005-09-20 00:43:16 +00001067 return true;
1068}
1069
Chris Lattnereaba3a12005-09-19 23:49:37 +00001070/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1071/// that is defined in the same block as the branch and if any PHI entries are
1072/// constants, thread edges corresponding to that entry to be branches to their
1073/// ultimate destination.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001074static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001075 BasicBlock *BB = BI->getParent();
1076 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001077 // NOTE: we currently cannot transform this case if the PHI node is used
1078 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001079 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1080 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001081
1082 // Degenerate case of a single entry PHI.
1083 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001084 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001085 return true;
1086 }
1087
1088 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001089 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001090
1091 // Okay, this is a simple enough basic block. See if any phi values are
1092 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001093 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001094 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1095 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1096
1097 // Okay, we now know that all edges from PredBB should be revectored to
1098 // branch to RealDest.
1099 BasicBlock *PredBB = PN->getIncomingBlock(i);
1100 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1101
1102 if (RealDest == BB) continue; // Skip self loops.
1103
1104 // The dest block might have PHI nodes, other predecessors and other
1105 // difficult cases. Instead of being smart about this, just insert a new
1106 // block that jumps to the destination block, effectively splitting
1107 // the edge we are about to create.
1108 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1109 RealDest->getName()+".critedge",
1110 RealDest->getParent(), RealDest);
1111 BranchInst::Create(RealDest, EdgeBB);
Chris Lattner6de0a282010-12-14 07:09:42 +00001112
1113 // Update PHI nodes.
1114 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001115
1116 // BB may have instructions that are being threaded over. Clone these
1117 // instructions into EdgeBB. We know that there will be no uses of the
1118 // cloned instructions outside of EdgeBB.
1119 BasicBlock::iterator InsertPt = EdgeBB->begin();
1120 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1121 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1122 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1123 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1124 continue;
1125 }
1126 // Clone the instruction.
1127 Instruction *N = BBI->clone();
1128 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1129
1130 // Update operands due to translation.
1131 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1132 i != e; ++i) {
1133 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1134 if (PI != TranslateMap.end())
1135 *i = PI->second;
1136 }
1137
1138 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001139 if (Value *V = SimplifyInstruction(N, TD)) {
1140 TranslateMap[BBI] = V;
1141 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001142 } else {
1143 // Insert the new instruction into its new home.
1144 EdgeBB->getInstList().insert(InsertPt, N);
1145 if (!BBI->use_empty())
1146 TranslateMap[BBI] = N;
1147 }
1148 }
1149
1150 // Loop over all of the edges from PredBB to BB, changing them to branch
1151 // to EdgeBB instead.
1152 TerminatorInst *PredBBTI = PredBB->getTerminator();
1153 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1154 if (PredBBTI->getSuccessor(i) == BB) {
1155 BB->removePredecessor(PredBB);
1156 PredBBTI->setSuccessor(i, EdgeBB);
1157 }
1158
1159 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001160 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001161 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001162
1163 return false;
1164}
1165
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001166/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1167/// PHI node, see if we can eliminate it.
Chris Lattner73c50a62010-12-14 07:00:00 +00001168static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001169 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1170 // statement", which has a very simple dominance structure. Basically, we
1171 // are trying to find the condition that is being branched on, which
1172 // subsequently causes this merge to happen. We really want control
1173 // dependence information for this check, but simplifycfg can't keep it up
1174 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001175 BasicBlock *BB = PN->getParent();
1176 BasicBlock *IfTrue, *IfFalse;
1177 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001178 if (!IfCond ||
1179 // Don't bother if the branch will be constant folded trivially.
1180 isa<ConstantInt>(IfCond))
1181 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001182
Chris Lattner822a8792006-11-18 19:19:36 +00001183 // Okay, we found that we can merge this two-entry phi node into a select.
1184 // Doing so would require us to fold *all* two entry phi nodes in this block.
1185 // At some point this becomes non-profitable (particularly if the target
1186 // doesn't support cmov's). Only do this transformation if there are two or
1187 // fewer PHI nodes in this block.
1188 unsigned NumPhis = 0;
1189 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1190 if (NumPhis > 2)
1191 return false;
1192
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001193 // Loop over the PHI's seeing if we can promote them all to select
1194 // instructions. While we are at it, keep track of the instructions
1195 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001196 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001197
Chris Lattner3aff13b2010-12-14 08:46:09 +00001198 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1199 PHINode *PN = cast<PHINode>(II++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001200 if (Value *V = SimplifyInstruction(PN, TD)) {
1201 PN->replaceAllUsesWith(V);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001202 PN->eraseFromParent();
Chris Lattner07ff3532010-12-14 07:20:29 +00001203 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001204 }
Chris Lattner07ff3532010-12-14 07:20:29 +00001205
1206 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts) ||
1207 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts))
1208 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001209 }
1210
Chris Lattner44da7ca2010-12-14 07:41:39 +00001211 // If we folded the the first phi, PN dangles at this point. Refresh it. If
1212 // we ran out of PHIs then we simplified them all.
1213 PN = dyn_cast<PHINode>(BB->begin());
1214 if (PN == 0) return true;
1215
Chris Lattner3aff13b2010-12-14 08:46:09 +00001216 // Don't fold i1 branches on PHIs which contain binary operators. These can
1217 // often be turned into switches and other things.
1218 if (PN->getType()->isIntegerTy(1) &&
1219 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1220 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1221 isa<BinaryOperator>(IfCond)))
1222 return false;
1223
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001224 // If we all PHI nodes are promotable, check to make sure that all
1225 // instructions in the predecessor blocks can be promoted as well. If
1226 // not, we won't be able to get rid of the control flow, so it's not
1227 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001228 BasicBlock *DomBlock = 0;
1229 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1230 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1231 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1232 IfBlock1 = 0;
1233 } else {
1234 DomBlock = *pred_begin(IfBlock1);
1235 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001236 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001237 // This is not an aggressive instruction that we can promote.
1238 // Because of this, we won't be able to get rid of the control
1239 // flow, so the xform is not worth it.
1240 return false;
1241 }
1242 }
1243
Chris Lattner44da7ca2010-12-14 07:41:39 +00001244 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1245 IfBlock2 = 0;
1246 } else {
1247 DomBlock = *pred_begin(IfBlock2);
1248 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001249 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001250 // This is not an aggressive instruction that we can promote.
1251 // Because of this, we won't be able to get rid of the control
1252 // flow, so the xform is not worth it.
1253 return false;
1254 }
1255 }
Chris Lattnere0b18e52010-12-14 07:23:10 +00001256
1257 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001258 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001259
1260 // If we can still promote the PHI nodes after this gauntlet of tests,
1261 // do all of the PHI's now.
Chris Lattner3aff13b2010-12-14 08:46:09 +00001262 Instruction *InsertPt = DomBlock->getTerminator();
1263
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001264 // Move all 'aggressive' instructions, which are defined in the
1265 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001266 if (IfBlock1)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001267 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001268 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001269 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001270 if (IfBlock2)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001271 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001272 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001273 IfBlock2->getTerminator());
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001274
1275 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1276 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001277 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1278 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001279
Chris Lattner3aff13b2010-12-14 08:46:09 +00001280 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", InsertPt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001281 PN->replaceAllUsesWith(NV);
1282 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001283 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001284 }
Chris Lattner60d410d2010-12-14 08:01:53 +00001285
1286 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1287 // has been flattened. Change DomBlock to jump directly to our new block to
1288 // avoid other simplifycfg's kicking in on the diamond.
1289 TerminatorInst *OldTI = DomBlock->getTerminator();
1290 BranchInst::Create(BB, OldTI);
1291 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001292 return true;
1293}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001294
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001295/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1296/// to two returning blocks, try to merge them together into one return,
1297/// introducing a select if the return values disagree.
1298static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1299 assert(BI->isConditional() && "Must be a conditional branch");
1300 BasicBlock *TrueSucc = BI->getSuccessor(0);
1301 BasicBlock *FalseSucc = BI->getSuccessor(1);
1302 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1303 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1304
1305 // Check to ensure both blocks are empty (just a return) or optionally empty
1306 // with PHI nodes. If there are other instructions, merging would cause extra
1307 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001308 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001309 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001310 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001311 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001312
1313 // Okay, we found a branch that is going to two return nodes. If
1314 // there is no return value for this function, just change the
1315 // branch into a return.
1316 if (FalseRet->getNumOperands() == 0) {
1317 TrueSucc->removePredecessor(BI->getParent());
1318 FalseSucc->removePredecessor(BI->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +00001319 ReturnInst::Create(BI->getContext(), 0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001320 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001321 return true;
1322 }
1323
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001324 // Otherwise, figure out what the true and false return values are
1325 // so we can insert a new select instruction.
1326 Value *TrueValue = TrueRet->getReturnValue();
1327 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001328
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001329 // Unwrap any PHI nodes in the return blocks.
1330 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1331 if (TVPN->getParent() == TrueSucc)
1332 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1333 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1334 if (FVPN->getParent() == FalseSucc)
1335 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1336
1337 // In order for this transformation to be safe, we must be able to
1338 // unconditionally execute both operands to the return. This is
1339 // normally the case, but we could have a potentially-trapping
1340 // constant expression that prevents this transformation from being
1341 // safe.
1342 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1343 if (TCV->canTrap())
1344 return false;
1345 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1346 if (FCV->canTrap())
1347 return false;
1348
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001349 // Okay, we collected all the mapped values and checked them for sanity, and
1350 // defined to really do this transformation. First, update the CFG.
1351 TrueSucc->removePredecessor(BI->getParent());
1352 FalseSucc->removePredecessor(BI->getParent());
1353
1354 // Insert select instructions where needed.
1355 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001356 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001357 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001358 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1359 } else if (isa<UndefValue>(TrueValue)) {
1360 TrueValue = FalseValue;
1361 } else {
1362 TrueValue = SelectInst::Create(BrCond, TrueValue,
1363 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001364 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001365 }
1366
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001367 Value *RI = !TrueValue ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001368 ReturnInst::Create(BI->getContext(), BI) :
1369 ReturnInst::Create(BI->getContext(), TrueValue, BI);
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001370 (void) RI;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001371
David Greene89d6fd32010-01-05 01:26:52 +00001372 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001373 << "\n " << *BI << "NewRet = " << *RI
1374 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001375
Eli Friedman080efb82008-12-16 20:54:32 +00001376 EraseTerminatorInstAndDCECond(BI);
1377
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001378 return true;
1379}
1380
Chris Lattner1347e872008-07-13 21:12:01 +00001381/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1382/// and if a predecessor branches to us and one of our successors, fold the
1383/// setcc into the predecessor and use logical operations to pick the right
1384/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001385bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001386 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001387 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Owen Andersone84178a2010-07-14 19:52:16 +00001388 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1389 Cond->getParent() != BB || !Cond->hasOneUse())
1390 return false;
Chris Lattner093a4382008-07-13 22:23:11 +00001391
Chris Lattner1347e872008-07-13 21:12:01 +00001392 // Only allow this if the condition is a simple instruction that can be
1393 // executed unconditionally. It must be in the same block as the branch, and
1394 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001395 BasicBlock::iterator FrontIt = BB->front();
1396 // Ignore dbg intrinsics.
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001397 while (isa<DbgInfoIntrinsic>(FrontIt))
Devang Pateld0a203d2009-02-04 21:39:48 +00001398 ++FrontIt;
Owen Andersone84178a2010-07-14 19:52:16 +00001399
1400 // Allow a single instruction to be hoisted in addition to the compare
1401 // that feeds the branch. We later ensure that any values that _it_ uses
1402 // were also live in the predecessor, so that we don't unnecessarily create
1403 // register pressure or inhibit out-of-order execution.
1404 Instruction *BonusInst = 0;
1405 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001406 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1407 FrontIt->isSafeToSpeculativelyExecute()) {
Owen Andersone84178a2010-07-14 19:52:16 +00001408 BonusInst = &*FrontIt;
1409 ++FrontIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001410 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001411
Owen Andersone84178a2010-07-14 19:52:16 +00001412 // Only a single bonus inst is allowed.
1413 if (&*FrontIt != Cond)
1414 return false;
1415
Chris Lattner1347e872008-07-13 21:12:01 +00001416 // Make sure the instruction after the condition is the cond branch.
1417 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001418 // Ingore dbg intrinsics.
1419 while(isa<DbgInfoIntrinsic>(CondIt))
1420 ++CondIt;
1421 if (&*CondIt != BI) {
1422 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001423 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001424 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001425
1426 // Cond is known to be a compare or binary operator. Check to make sure that
1427 // neither operand is a potentially-trapping constant expression.
1428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1429 if (CE->canTrap())
1430 return false;
1431 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1432 if (CE->canTrap())
1433 return false;
1434
Chris Lattner1347e872008-07-13 21:12:01 +00001435
1436 // Finally, don't infinitely unroll conditional loops.
1437 BasicBlock *TrueDest = BI->getSuccessor(0);
1438 BasicBlock *FalseDest = BI->getSuccessor(1);
1439 if (TrueDest == BB || FalseDest == BB)
1440 return false;
1441
1442 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1443 BasicBlock *PredBlock = *PI;
1444 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001445
Chris Lattner093a4382008-07-13 22:23:11 +00001446 // Check that we have two conditional branches. If there is a PHI node in
1447 // the common successor, verify that the same value flows in from both
1448 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001449 if (PBI == 0 || PBI->isUnconditional() ||
1450 !SafeToMergeTerminators(BI, PBI))
1451 continue;
1452
Owen Andersone84178a2010-07-14 19:52:16 +00001453 // Ensure that any values used in the bonus instruction are also used
1454 // by the terminator of the predecessor. This means that those values
1455 // must already have been resolved, so we won't be inhibiting the
1456 // out-of-order core by speculating them earlier.
1457 if (BonusInst) {
1458 // Collect the values used by the bonus inst
1459 SmallPtrSet<Value*, 4> UsedValues;
1460 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1461 OE = BonusInst->op_end(); OI != OE; ++OI) {
1462 Value* V = *OI;
1463 if (!isa<Constant>(V))
1464 UsedValues.insert(V);
1465 }
1466
1467 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1468 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1469
1470 // Walk up to four levels back up the use-def chain of the predecessor's
1471 // terminator to see if all those values were used. The choice of four
1472 // levels is arbitrary, to provide a compile-time-cost bound.
1473 while (!Worklist.empty()) {
1474 std::pair<Value*, unsigned> Pair = Worklist.back();
1475 Worklist.pop_back();
1476
1477 if (Pair.second >= 4) continue;
1478 UsedValues.erase(Pair.first);
1479 if (UsedValues.empty()) break;
1480
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001481 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001482 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1483 OI != OE; ++OI)
1484 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1485 }
1486 }
1487
1488 if (!UsedValues.empty()) return false;
1489 }
1490
Chris Lattner36989092008-07-13 21:20:19 +00001491 Instruction::BinaryOps Opc;
1492 bool InvertPredCond = false;
1493
1494 if (PBI->getSuccessor(0) == TrueDest)
1495 Opc = Instruction::Or;
1496 else if (PBI->getSuccessor(1) == FalseDest)
1497 Opc = Instruction::And;
1498 else if (PBI->getSuccessor(0) == FalseDest)
1499 Opc = Instruction::And, InvertPredCond = true;
1500 else if (PBI->getSuccessor(1) == TrueDest)
1501 Opc = Instruction::Or, InvertPredCond = true;
1502 else
1503 continue;
1504
David Greene89d6fd32010-01-05 01:26:52 +00001505 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Chris Lattner6ff645b2009-01-19 23:03:13 +00001506
Chris Lattner36989092008-07-13 21:20:19 +00001507 // If we need to invert the condition in the pred block to match, do so now.
1508 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001509 Value *NewCond = PBI->getCondition();
1510
1511 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1512 CmpInst *CI = cast<CmpInst>(NewCond);
1513 CI->setPredicate(CI->getInversePredicate());
1514 } else {
1515 NewCond = BinaryOperator::CreateNot(NewCond,
Chris Lattner36989092008-07-13 21:20:19 +00001516 PBI->getCondition()->getName()+".not", PBI);
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001517 }
1518
Chris Lattner1347e872008-07-13 21:12:01 +00001519 PBI->setCondition(NewCond);
1520 BasicBlock *OldTrue = PBI->getSuccessor(0);
1521 BasicBlock *OldFalse = PBI->getSuccessor(1);
1522 PBI->setSuccessor(0, OldFalse);
1523 PBI->setSuccessor(1, OldTrue);
1524 }
Chris Lattner70087f32008-07-13 21:15:11 +00001525
Owen Andersone84178a2010-07-14 19:52:16 +00001526 // If we have a bonus inst, clone it into the predecessor block.
1527 Instruction *NewBonus = 0;
1528 if (BonusInst) {
1529 NewBonus = BonusInst->clone();
1530 PredBlock->getInstList().insert(PBI, NewBonus);
1531 NewBonus->takeName(BonusInst);
1532 BonusInst->setName(BonusInst->getName()+".old");
1533 }
1534
Chris Lattner36989092008-07-13 21:20:19 +00001535 // Clone Cond into the predecessor basic block, and or/and the
1536 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00001537 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00001538 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00001539 PredBlock->getInstList().insert(PBI, New);
1540 New->takeName(Cond);
1541 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001542
Chris Lattner36989092008-07-13 21:20:19 +00001543 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1544 New, "or.cond", PBI);
1545 PBI->setCondition(NewCond);
1546 if (PBI->getSuccessor(0) == BB) {
1547 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1548 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001549 }
Chris Lattner36989092008-07-13 21:20:19 +00001550 if (PBI->getSuccessor(1) == BB) {
1551 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1552 PBI->setSuccessor(1, FalseDest);
1553 }
Chris Lattner117f8cf2010-12-14 05:57:30 +00001554 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001555 }
1556 return false;
1557}
1558
Chris Lattner867661a2008-07-13 21:53:26 +00001559/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1560/// predecessor of another block, this function tries to simplify it. We know
1561/// that PBI and BI are both conditional branches, and BI is in one of the
1562/// successor blocks of PBI - PBI branches to BI.
1563static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1564 assert(PBI->isConditional() && BI->isConditional());
1565 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00001566
Chris Lattner867661a2008-07-13 21:53:26 +00001567 // If this block ends with a branch instruction, and if there is a
1568 // predecessor that ends on a branch of the same condition, make
1569 // this conditional branch redundant.
1570 if (PBI->getCondition() == BI->getCondition() &&
1571 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1572 // Okay, the outcome of this conditional branch is statically
1573 // knowable. If this block had a single pred, handle specially.
1574 if (BB->getSinglePredecessor()) {
1575 // Turn this into a branch on constant.
1576 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001577 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1578 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001579 return true; // Nuke the branch on constant.
1580 }
1581
1582 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1583 // in the constant and simplify the block result. Subsequent passes of
1584 // simplifycfg will thread the block.
1585 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001586 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Chris Lattner867661a2008-07-13 21:53:26 +00001587 BI->getCondition()->getName() + ".pr",
1588 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001589 // Okay, we're going to insert the PHI node. Since PBI is not the only
1590 // predecessor, compute the PHI'd conditional value for all of the preds.
1591 // Any predecessor where the condition is not computable we keep symbolic.
Gabor Greif62539832010-07-12 10:59:23 +00001592 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1593 BasicBlock *P = *PI;
1594 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00001595 PBI != BI && PBI->isConditional() &&
1596 PBI->getCondition() == BI->getCondition() &&
1597 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1598 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001599 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00001600 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001601 } else {
Gabor Greif62539832010-07-12 10:59:23 +00001602 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001603 }
Gabor Greif62539832010-07-12 10:59:23 +00001604 }
Chris Lattner867661a2008-07-13 21:53:26 +00001605
1606 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001607 return true;
1608 }
1609 }
1610
1611 // If this is a conditional branch in an empty block, and if any
1612 // predecessors is a conditional branch to one of our destinations,
1613 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001614 BasicBlock::iterator BBI = BB->begin();
1615 // Ignore dbg intrinsics.
1616 while (isa<DbgInfoIntrinsic>(BBI))
1617 ++BBI;
1618 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001619 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001620
1621
1622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1623 if (CE->canTrap())
1624 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001625
1626 int PBIOp, BIOp;
1627 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1628 PBIOp = BIOp = 0;
1629 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1630 PBIOp = 0, BIOp = 1;
1631 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1632 PBIOp = 1, BIOp = 0;
1633 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1634 PBIOp = BIOp = 1;
1635 else
1636 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001637
Chris Lattnerb8245122008-07-13 22:04:41 +00001638 // Check to make sure that the other destination of this branch
1639 // isn't BB itself. If so, this is an infinite loop that will
1640 // keep getting unwound.
1641 if (PBI->getSuccessor(PBIOp) == BB)
1642 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001643
Chris Lattnerb8245122008-07-13 22:04:41 +00001644 // Do not perform this transformation if it would require
1645 // insertion of a large number of select instructions. For targets
1646 // without predication/cmovs, this is a big pessimization.
1647 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001648
Chris Lattnerb8245122008-07-13 22:04:41 +00001649 unsigned NumPhis = 0;
1650 for (BasicBlock::iterator II = CommonDest->begin();
1651 isa<PHINode>(II); ++II, ++NumPhis)
1652 if (NumPhis > 2) // Disable this xform.
1653 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001654
Chris Lattnerb8245122008-07-13 22:04:41 +00001655 // Finally, if everything is ok, fold the branches to logical ops.
1656 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1657
David Greene89d6fd32010-01-05 01:26:52 +00001658 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00001659 << "AND: " << *BI->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001660
Chris Lattner093a4382008-07-13 22:23:11 +00001661
1662 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1663 // branch in it, where one edge (OtherDest) goes back to itself but the other
1664 // exits. We don't *know* that the program avoids the infinite loop
1665 // (even though that seems likely). If we do this xform naively, we'll end up
1666 // recursively unpeeling the loop. Since we know that (after the xform is
1667 // done) that the block *is* infinite if reached, we just make it an obviously
1668 // infinite loop with no cond branch.
1669 if (OtherDest == BB) {
1670 // Insert it at the end of the function, because it's either code,
1671 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001672 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1673 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00001674 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1675 OtherDest = InfLoopBlock;
1676 }
1677
David Greene89d6fd32010-01-05 01:26:52 +00001678 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001679
1680 // BI may have other predecessors. Because of this, we leave
1681 // it alone, but modify PBI.
1682
1683 // Make sure we get to CommonDest on True&True directions.
1684 Value *PBICond = PBI->getCondition();
1685 if (PBIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001686 PBICond = BinaryOperator::CreateNot(PBICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001687 PBICond->getName()+".not",
1688 PBI);
1689 Value *BICond = BI->getCondition();
1690 if (BIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001691 BICond = BinaryOperator::CreateNot(BICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001692 BICond->getName()+".not",
1693 PBI);
1694 // Merge the conditions.
1695 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1696
1697 // Modify PBI to branch on the new condition to the new dests.
1698 PBI->setCondition(Cond);
1699 PBI->setSuccessor(0, CommonDest);
1700 PBI->setSuccessor(1, OtherDest);
1701
1702 // OtherDest may have phi nodes. If so, add an entry from PBI's
1703 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00001704 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Chris Lattnerb8245122008-07-13 22:04:41 +00001705
1706 // We know that the CommonDest already had an edge from PBI to
1707 // it. If it has PHIs though, the PHIs may have different
1708 // entries for BB and PBI's BB. If so, insert a select to make
1709 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00001710 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00001711 for (BasicBlock::iterator II = CommonDest->begin();
1712 (PN = dyn_cast<PHINode>(II)); ++II) {
1713 Value *BIV = PN->getIncomingValueForBlock(BB);
1714 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1715 Value *PBIV = PN->getIncomingValue(PBBIdx);
1716 if (BIV != PBIV) {
1717 // Insert a select in PBI to pick the right value.
1718 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1719 PBIV->getName()+".mux", PBI);
1720 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001721 }
1722 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001723
David Greene89d6fd32010-01-05 01:26:52 +00001724 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1725 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001726
1727 // This basic block is probably dead. We know it has at least
1728 // one fewer predecessor.
1729 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001730}
1731
Frits van Bommel7ac40c32010-12-05 18:29:03 +00001732// SimplifyIndirectBrOnSelect - Replaces
1733// (indirectbr (select cond, blockaddress(@fn, BlockA),
1734// blockaddress(@fn, BlockB)))
1735// with
1736// (br cond, BlockA, BlockB).
1737static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1738 // Check that both operands of the select are block addresses.
1739 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1740 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1741 if (!TBA || !FBA)
1742 return false;
1743
1744 // Extract the actual blocks.
1745 BasicBlock *TrueBB = TBA->getBasicBlock();
1746 BasicBlock *FalseBB = FBA->getBasicBlock();
1747
1748 // Remove any superfluous successor edges from the CFG.
1749 // First, figure out which successors to preserve.
1750 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1751 // successor.
1752 BasicBlock *KeepEdge1 = TrueBB;
1753 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1754
1755 // Then remove the rest.
1756 for (unsigned I = 0, E = IBI->getNumSuccessors(); I != E; ++I) {
1757 BasicBlock *Succ = IBI->getSuccessor(I);
1758 // Make sure only to keep exactly one copy of each edge.
1759 if (Succ == KeepEdge1)
1760 KeepEdge1 = 0;
1761 else if (Succ == KeepEdge2)
1762 KeepEdge2 = 0;
1763 else
1764 Succ->removePredecessor(IBI->getParent());
1765 }
1766
1767 // Insert an appropriate new terminator.
1768 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1769 if (TrueBB == FalseBB)
1770 // We were only looking for one successor, and it was present.
1771 // Create an unconditional branch to it.
1772 BranchInst::Create(TrueBB, IBI);
1773 else
1774 // We found both of the successors we were looking for.
1775 // Create a conditional branch sharing the condition of the select.
1776 BranchInst::Create(TrueBB, FalseBB, SI->getCondition(), IBI);
1777 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1778 // Neither of the selected blocks were successors, so this
1779 // indirectbr must be unreachable.
1780 new UnreachableInst(IBI->getContext(), IBI);
1781 } else {
1782 // One of the selected values was a successor, but the other wasn't.
1783 // Insert an unconditional branch to the one that was found;
1784 // the edge to the one that wasn't must be unreachable.
1785 if (KeepEdge1 == 0)
1786 // Only TrueBB was found.
1787 BranchInst::Create(TrueBB, IBI);
1788 else
1789 // Only FalseBB was found.
1790 BranchInst::Create(FalseBB, IBI);
1791 }
1792
1793 EraseTerminatorInstAndDCECond(IBI);
1794 return true;
1795}
1796
Chris Lattner61c77442010-12-13 03:18:54 +00001797/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
1798/// instruction (a seteq/setne with a constant) as the only instruction in a
1799/// block that ends with an uncond branch. We are looking for a very specific
1800/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
1801/// this case, we merge the first two "or's of icmp" into a switch, but then the
1802/// default value goes to an uncond block with a seteq in it, we get something
1803/// like:
1804///
1805/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
1806/// DEFAULT:
1807/// %tmp = icmp eq i8 %A, 92
1808/// br label %end
1809/// end:
1810/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
1811///
1812/// We prefer to split the edge to 'end' so that there is a true/false entry to
1813/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001814static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
1815 const TargetData *TD) {
Chris Lattner61c77442010-12-13 03:18:54 +00001816 BasicBlock *BB = ICI->getParent();
1817 // If the block has any PHIs in it or the icmp has multiple uses, it is too
1818 // complex.
1819 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
1820
1821 Value *V = ICI->getOperand(0);
1822 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
1823
1824 // The pattern we're looking for is where our only predecessor is a switch on
1825 // 'V' and this block is the default case for the switch. In this case we can
1826 // fold the compared value into the switch to simplify things.
1827 BasicBlock *Pred = BB->getSinglePredecessor();
1828 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
1829
1830 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
1831 if (SI->getCondition() != V)
1832 return false;
1833
1834 // If BB is reachable on a non-default case, then we simply know the value of
1835 // V in this block. Substitute it and constant fold the icmp instruction
1836 // away.
1837 if (SI->getDefaultDest() != BB) {
1838 ConstantInt *VVal = SI->findCaseDest(BB);
1839 assert(VVal && "Should have a unique destination value");
1840 ICI->setOperand(0, VVal);
1841
Chris Lattner302ba6f2010-12-14 06:17:25 +00001842 if (Value *V = SimplifyInstruction(ICI, TD)) {
1843 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00001844 ICI->eraseFromParent();
1845 }
1846 // BB is now empty, so it is likely to simplify away.
1847 return SimplifyCFG(BB) | true;
1848 }
1849
Chris Lattnerabf70672010-12-13 03:43:57 +00001850 // Ok, the block is reachable from the default dest. If the constant we're
1851 // comparing exists in one of the other edges, then we can constant fold ICI
1852 // and zap it.
1853 if (SI->findCaseValue(Cst) != 0) {
1854 Value *V;
1855 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1856 V = ConstantInt::getFalse(BB->getContext());
1857 else
1858 V = ConstantInt::getTrue(BB->getContext());
1859
1860 ICI->replaceAllUsesWith(V);
1861 ICI->eraseFromParent();
1862 // BB is now empty, so it is likely to simplify away.
1863 return SimplifyCFG(BB) | true;
1864 }
1865
Chris Lattner61c77442010-12-13 03:18:54 +00001866 // The use of the icmp has to be in the 'end' block, by the only PHI node in
1867 // the block.
1868 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
1869 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
1870 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
1871 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
1872 return false;
1873
1874 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
1875 // true in the PHI.
1876 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
1877 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
1878
1879 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1880 std::swap(DefaultCst, NewCst);
1881
1882 // Replace ICI (which is used by the PHI for the default value) with true or
1883 // false depending on if it is EQ or NE.
1884 ICI->replaceAllUsesWith(DefaultCst);
1885 ICI->eraseFromParent();
1886
1887 // Okay, the switch goes to this block on a default value. Add an edge from
1888 // the switch to the merge point on the compared value.
1889 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
1890 BB->getParent(), BB);
1891 SI->addCase(Cst, NewBB);
1892
1893 // NewBB branches to the phi block, add the uncond branch and the phi entry.
1894 BranchInst::Create(SuccBlock, NewBB);
1895 PHIUse->addIncoming(NewCst, NewBB);
1896 return true;
1897}
1898
Chris Lattner97fdb892010-12-13 05:03:41 +00001899/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
1900/// Check to see if it is branching on an or/and chain of icmp instructions, and
1901/// fold it into a switch instruction if so.
1902static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD) {
1903 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1904 if (Cond == 0) return false;
1905
1906
1907 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1908 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1909 // 'setne's and'ed together, collect them.
1910 Value *CompVal = 0;
1911 std::vector<ConstantInt*> Values;
1912 bool TrueWhenEqual = true;
1913 Value *ExtraCase = 0;
1914
1915 if (Cond->getOpcode() == Instruction::Or) {
1916 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true);
1917 } else if (Cond->getOpcode() == Instruction::And) {
1918 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false);
1919 TrueWhenEqual = false;
1920 }
1921
1922 // If we didn't have a multiply compared value, fail.
1923 if (CompVal == 0) return false;
1924
1925 // There might be duplicate constants in the list, which the switch
1926 // instruction can't handle, remove them now.
1927 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
1928 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1929
1930 // If Extra was used, we require at least two switch values to do the
1931 // transformation. A switch with one value is just an cond branch.
1932 if (ExtraCase && Values.size() < 2) return false;
1933
1934 // Figure out which block is which destination.
1935 BasicBlock *DefaultBB = BI->getSuccessor(1);
1936 BasicBlock *EdgeBB = BI->getSuccessor(0);
1937 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1938
1939 BasicBlock *BB = BI->getParent();
1940
Chris Lattner302ba6f2010-12-14 06:17:25 +00001941 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00001942 << " cases into SWITCH. BB is:\n" << *BB);
1943
Chris Lattner97fdb892010-12-13 05:03:41 +00001944 // If there are any extra values that couldn't be folded into the switch
1945 // then we evaluate them with an explicit branch first. Split the block
1946 // right before the condbr to handle it.
1947 if (ExtraCase) {
1948 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
1949 // Remove the uncond branch added to the old block.
1950 TerminatorInst *OldTI = BB->getTerminator();
1951
Chris Lattner117f8cf2010-12-14 05:57:30 +00001952 if (TrueWhenEqual)
1953 BranchInst::Create(EdgeBB, NewBB, ExtraCase, OldTI);
1954 else
1955 BranchInst::Create(NewBB, EdgeBB, ExtraCase, OldTI);
1956
Chris Lattner97fdb892010-12-13 05:03:41 +00001957 OldTI->eraseFromParent();
Chris Lattner97bd89e2010-12-13 05:34:18 +00001958
1959 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
1960 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00001961 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001962
1963 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
1964 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00001965 BB = NewBB;
1966 }
1967
1968 // Convert pointer to int before we switch.
1969 if (CompVal->getType()->isPointerTy()) {
1970 assert(TD && "Cannot switch on pointer without TargetData");
1971 CompVal = new PtrToIntInst(CompVal,
1972 TD->getIntPtrType(CompVal->getContext()),
1973 "magicptr", BI);
1974 }
1975
1976 // Create the new switch instruction now.
Chris Lattner3d512132010-12-13 06:25:44 +00001977 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB, Values.size(), BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00001978
1979 // Add all of the 'cases' to the switch instruction.
1980 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1981 New->addCase(Values[i], EdgeBB);
1982
1983 // We added edges from PI to the EdgeBB. As such, if there were any
1984 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1985 // the number of edges added.
1986 for (BasicBlock::iterator BBI = EdgeBB->begin();
1987 isa<PHINode>(BBI); ++BBI) {
1988 PHINode *PN = cast<PHINode>(BBI);
1989 Value *InVal = PN->getIncomingValueForBlock(BB);
1990 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1991 PN->addIncoming(InVal, BB);
1992 }
1993
1994 // Erase the old branch instruction.
1995 EraseTerminatorInstAndDCECond(BI);
Chris Lattner117f8cf2010-12-14 05:57:30 +00001996
Chris Lattner302ba6f2010-12-14 06:17:25 +00001997 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00001998 return true;
1999}
2000
Chris Lattner3d512132010-12-13 06:25:44 +00002001bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI) {
2002 BasicBlock *BB = RI->getParent();
2003 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2004
2005 // Find predecessors that end with branches.
2006 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2007 SmallVector<BranchInst*, 8> CondBranchPreds;
2008 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2009 BasicBlock *P = *PI;
2010 TerminatorInst *PTI = P->getTerminator();
2011 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2012 if (BI->isUnconditional())
2013 UncondBranchPreds.push_back(P);
2014 else
2015 CondBranchPreds.push_back(BI);
2016 }
2017 }
2018
2019 // If we found some, do the transformation!
2020 if (!UncondBranchPreds.empty()) {
2021 while (!UncondBranchPreds.empty()) {
2022 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2023 DEBUG(dbgs() << "FOLDING: " << *BB
2024 << "INTO UNCOND BRANCH PRED: " << *Pred);
2025 Instruction *UncondBranch = Pred->getTerminator();
2026 // Clone the return and add it to the end of the predecessor.
2027 Instruction *NewRet = RI->clone();
2028 Pred->getInstList().push_back(NewRet);
2029
2030 // If the return instruction returns a value, and if the value was a
2031 // PHI node in "BB", propagate the right value into the return.
2032 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
2033 i != e; ++i)
2034 if (PHINode *PN = dyn_cast<PHINode>(*i))
2035 if (PN->getParent() == BB)
2036 *i = PN->getIncomingValueForBlock(Pred);
2037
2038 // Update any PHI nodes in the returning block to realize that we no
2039 // longer branch to them.
2040 BB->removePredecessor(Pred);
Chris Lattner302ba6f2010-12-14 06:17:25 +00002041 UncondBranch->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002042 }
2043
2044 // If we eliminated all predecessors of the block, delete the block now.
2045 if (pred_begin(BB) == pred_end(BB))
2046 // We know there are no successors, so just nuke the block.
2047 BB->eraseFromParent();
2048
2049 return true;
2050 }
2051
2052 // Check out all of the conditional branches going to this return
2053 // instruction. If any of them just select between returns, change the
2054 // branch itself into a select/return pair.
2055 while (!CondBranchPreds.empty()) {
2056 BranchInst *BI = CondBranchPreds.pop_back_val();
2057
2058 // Check to see if the non-BB successor is also a return block.
2059 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2060 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2061 SimplifyCondBranchToTwoReturns(BI))
2062 return true;
2063 }
2064 return false;
2065}
2066
2067bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI) {
2068 // Check to see if the first instruction in this block is just an unwind.
2069 // If so, replace any invoke instructions which use this as an exception
2070 // destination with call instructions.
2071 BasicBlock *BB = UI->getParent();
2072 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2073
2074 bool Changed = false;
2075 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2076 while (!Preds.empty()) {
2077 BasicBlock *Pred = Preds.back();
2078 InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
2079 if (II && II->getUnwindDest() == BB) {
2080 // Insert a new branch instruction before the invoke, because this
2081 // is now a fall through.
2082 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2083 Pred->getInstList().remove(II); // Take out of symbol table
2084
2085 // Insert the call now.
2086 SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
2087 CallInst *CI = CallInst::Create(II->getCalledValue(),
2088 Args.begin(), Args.end(),
2089 II->getName(), BI);
2090 CI->setCallingConv(II->getCallingConv());
2091 CI->setAttributes(II->getAttributes());
2092 // If the invoke produced a value, the Call now does instead.
2093 II->replaceAllUsesWith(CI);
2094 delete II;
2095 Changed = true;
2096 }
2097
2098 Preds.pop_back();
2099 }
2100
2101 // If this block is now dead (and isn't the entry block), remove it.
2102 if (pred_begin(BB) == pred_end(BB) &&
2103 BB != &BB->getParent()->getEntryBlock()) {
2104 // We know there are no successors, so just nuke the block.
2105 BB->eraseFromParent();
2106 return true;
2107 }
2108
2109 return Changed;
2110}
2111
2112bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2113 BasicBlock *BB = UI->getParent();
2114
2115 bool Changed = false;
2116
2117 // If there are any instructions immediately before the unreachable that can
2118 // be removed, do so.
2119 while (UI != BB->begin()) {
2120 BasicBlock::iterator BBI = UI;
2121 --BBI;
2122 // Do not delete instructions that can have side effects, like calls
2123 // (which may never return) and volatile loads and stores.
2124 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2125
2126 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2127 if (SI->isVolatile())
2128 break;
2129
2130 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2131 if (LI->isVolatile())
2132 break;
2133
2134 // Delete this instruction
Chris Lattner302ba6f2010-12-14 06:17:25 +00002135 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002136 Changed = true;
2137 }
2138
2139 // If the unreachable instruction is the first in the block, take a gander
2140 // at all of the predecessors of this instruction, and simplify them.
2141 if (&BB->front() != UI) return Changed;
2142
2143 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2144 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2145 TerminatorInst *TI = Preds[i]->getTerminator();
2146
2147 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2148 if (BI->isUnconditional()) {
2149 if (BI->getSuccessor(0) == BB) {
2150 new UnreachableInst(TI->getContext(), TI);
2151 TI->eraseFromParent();
2152 Changed = true;
2153 }
2154 } else {
2155 if (BI->getSuccessor(0) == BB) {
2156 BranchInst::Create(BI->getSuccessor(1), BI);
2157 EraseTerminatorInstAndDCECond(BI);
2158 } else if (BI->getSuccessor(1) == BB) {
2159 BranchInst::Create(BI->getSuccessor(0), BI);
2160 EraseTerminatorInstAndDCECond(BI);
2161 Changed = true;
2162 }
2163 }
2164 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2165 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2166 if (SI->getSuccessor(i) == BB) {
2167 BB->removePredecessor(SI->getParent());
2168 SI->removeCase(i);
2169 --i; --e;
2170 Changed = true;
2171 }
2172 // If the default value is unreachable, figure out the most popular
2173 // destination and make it the default.
2174 if (SI->getSuccessor(0) == BB) {
2175 std::map<BasicBlock*, unsigned> Popularity;
2176 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2177 Popularity[SI->getSuccessor(i)]++;
2178
2179 // Find the most popular block.
2180 unsigned MaxPop = 0;
2181 BasicBlock *MaxBlock = 0;
2182 for (std::map<BasicBlock*, unsigned>::iterator
2183 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2184 if (I->second > MaxPop) {
2185 MaxPop = I->second;
2186 MaxBlock = I->first;
2187 }
2188 }
2189 if (MaxBlock) {
2190 // Make this the new default, allowing us to delete any explicit
2191 // edges to it.
2192 SI->setSuccessor(0, MaxBlock);
2193 Changed = true;
2194
2195 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2196 // it.
2197 if (isa<PHINode>(MaxBlock->begin()))
2198 for (unsigned i = 0; i != MaxPop-1; ++i)
2199 MaxBlock->removePredecessor(SI->getParent());
2200
2201 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2202 if (SI->getSuccessor(i) == MaxBlock) {
2203 SI->removeCase(i);
2204 --i; --e;
2205 }
2206 }
2207 }
2208 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2209 if (II->getUnwindDest() == BB) {
2210 // Convert the invoke to a call instruction. This would be a good
2211 // place to note that the call does not throw though.
2212 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2213 II->removeFromParent(); // Take out of symbol table
2214
2215 // Insert the call now...
2216 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2217 CallInst *CI = CallInst::Create(II->getCalledValue(),
2218 Args.begin(), Args.end(),
2219 II->getName(), BI);
2220 CI->setCallingConv(II->getCallingConv());
2221 CI->setAttributes(II->getAttributes());
2222 // If the invoke produced a value, the call does now instead.
2223 II->replaceAllUsesWith(CI);
2224 delete II;
2225 Changed = true;
2226 }
2227 }
2228 }
2229
2230 // If this block is now dead, remove it.
2231 if (pred_begin(BB) == pred_end(BB) &&
2232 BB != &BB->getParent()->getEntryBlock()) {
2233 // We know there are no successors, so just nuke the block.
2234 BB->eraseFromParent();
2235 return true;
2236 }
2237
2238 return Changed;
2239}
2240
2241
2242bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI) {
2243 // If this switch is too complex to want to look at, ignore it.
2244 if (!isValueEqualityComparison(SI))
2245 return false;
2246
2247 BasicBlock *BB = SI->getParent();
2248
2249 // If we only have one predecessor, and if it is a branch on this value,
2250 // see if that predecessor totally determines the outcome of this switch.
2251 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2252 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
Chris Lattner021c9d32010-12-13 06:36:51 +00002253 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002254
2255 // If the block only contains the switch, see if we can fold the block
2256 // away into any preds.
2257 BasicBlock::iterator BBI = BB->begin();
2258 // Ignore dbg intrinsics.
2259 while (isa<DbgInfoIntrinsic>(BBI))
2260 ++BBI;
2261 if (SI == &*BBI)
2262 if (FoldValueComparisonIntoPredecessors(SI))
Chris Lattner021c9d32010-12-13 06:36:51 +00002263 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002264
2265 return false;
2266}
2267
2268bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2269 BasicBlock *BB = IBI->getParent();
2270 bool Changed = false;
2271
2272 // Eliminate redundant destinations.
2273 SmallPtrSet<Value *, 8> Succs;
2274 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2275 BasicBlock *Dest = IBI->getDestination(i);
2276 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2277 Dest->removePredecessor(BB);
2278 IBI->removeDestination(i);
2279 --i; --e;
2280 Changed = true;
2281 }
2282 }
2283
2284 if (IBI->getNumDestinations() == 0) {
2285 // If the indirectbr has no successors, change it to unreachable.
2286 new UnreachableInst(IBI->getContext(), IBI);
2287 EraseTerminatorInstAndDCECond(IBI);
2288 return true;
2289 }
2290
2291 if (IBI->getNumDestinations() == 1) {
2292 // If the indirectbr has one successor, change it to a direct branch.
2293 BranchInst::Create(IBI->getDestination(0), IBI);
2294 EraseTerminatorInstAndDCECond(IBI);
2295 return true;
2296 }
2297
2298 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2299 if (SimplifyIndirectBrOnSelect(IBI, SI))
2300 return SimplifyCFG(BB) | true;
2301 }
2302 return Changed;
2303}
2304
2305bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI) {
2306 BasicBlock *BB = BI->getParent();
2307
2308 // If the Terminator is the only non-phi instruction, simplify the block.
2309 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
2310 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2311 TryToSimplifyUncondBranchFromEmptyBlock(BB))
2312 return true;
2313
2314 // If the only instruction in the block is a seteq/setne comparison
2315 // against a constant, try to simplify the block.
2316 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2317 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2318 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2319 ;
Chris Lattner302ba6f2010-12-14 06:17:25 +00002320 if (I->isTerminator() && TryToSimplifyUncondBranchWithICmpInIt(ICI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002321 return true;
2322 }
2323
2324 return false;
2325}
2326
2327
2328bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI) {
2329 BasicBlock *BB = BI->getParent();
2330
2331 // Conditional branch
2332 if (isValueEqualityComparison(BI)) {
2333 // If we only have one predecessor, and if it is a branch on this value,
2334 // see if that predecessor totally determines the outcome of this
2335 // switch.
2336 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2337 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
2338 return SimplifyCFG(BB) | true;
2339
2340 // This block must be empty, except for the setcond inst, if it exists.
2341 // Ignore dbg intrinsics.
2342 BasicBlock::iterator I = BB->begin();
2343 // Ignore dbg intrinsics.
2344 while (isa<DbgInfoIntrinsic>(I))
2345 ++I;
2346 if (&*I == BI) {
2347 if (FoldValueComparisonIntoPredecessors(BI))
2348 return SimplifyCFG(BB) | true;
2349 } else if (&*I == cast<Instruction>(BI->getCondition())){
2350 ++I;
2351 // Ignore dbg intrinsics.
2352 while (isa<DbgInfoIntrinsic>(I))
2353 ++I;
2354 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI))
2355 return SimplifyCFG(BB) | true;
2356 }
2357 }
2358
2359 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
2360 if (SimplifyBranchOnICmpChain(BI, TD))
2361 return true;
2362
2363 // We have a conditional branch to two blocks that are only reachable
2364 // from BI. We know that the condbr dominates the two blocks, so see if
2365 // there is any identical code in the "then" and "else" blocks. If so, we
2366 // can hoist it up to the branching block.
2367 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2368 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2369 if (HoistThenElseCodeToIf(BI))
2370 return SimplifyCFG(BB) | true;
2371 } else {
2372 // If Successor #1 has multiple preds, we may be able to conditionally
2373 // execute Successor #0 if it branches to successor #1.
2374 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2375 if (Succ0TI->getNumSuccessors() == 1 &&
2376 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
2377 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
2378 return SimplifyCFG(BB) | true;
2379 }
2380 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2381 // If Successor #0 has multiple preds, we may be able to conditionally
2382 // execute Successor #1 if it branches to successor #0.
2383 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2384 if (Succ1TI->getNumSuccessors() == 1 &&
2385 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
2386 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
2387 return SimplifyCFG(BB) | true;
2388 }
2389
2390 // If this is a branch on a phi node in the current block, thread control
2391 // through this block if any PHI node entries are constants.
2392 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2393 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00002394 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002395 return SimplifyCFG(BB) | true;
2396
2397 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2398 // branches to us and one of our successors, fold the setcc into the
2399 // predecessor and use logical operations to pick the right destination.
2400 if (FoldBranchToCommonDest(BI))
Owen Anderson2d9220e2010-12-13 23:49:28 +00002401 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002402
2403 // Scan predecessor blocks for conditional branches.
2404 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2405 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2406 if (PBI != BI && PBI->isConditional())
2407 if (SimplifyCondBranchToCondBranch(PBI, BI))
2408 return SimplifyCFG(BB) | true;
2409
2410 return false;
2411}
2412
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002413bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002414 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002415
Chris Lattner302ba6f2010-12-14 06:17:25 +00002416 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002417 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002418
Dan Gohmane2c6d132010-08-14 00:29:42 +00002419 // Remove basic blocks that have no predecessors (except the entry block)...
2420 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002421 if ((pred_begin(BB) == pred_end(BB) &&
2422 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00002423 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00002424 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00002425 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00002426 return true;
2427 }
2428
Chris Lattner694e37f2003-08-17 19:41:53 +00002429 // Check to see if we can constant propagate this terminator instruction
2430 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002431 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00002432
Dan Gohman2c635662009-10-30 22:39:04 +00002433 // Check for and eliminate duplicate PHI nodes in this block.
2434 Changed |= EliminateDuplicatePHINodes(BB);
2435
Chris Lattnerddb97a22010-12-13 05:10:48 +00002436 // Merge basic blocks into their predecessor if there is only one distinct
2437 // pred, and if there is only one distinct successor of the predecessor, and
2438 // if there are no PHI nodes.
2439 //
2440 if (MergeBlockIntoPredecessor(BB))
2441 return true;
2442
Dan Gohman882d87d2008-03-11 21:53:06 +00002443 // If there is a trivial two-entry PHI node in this basic block, and we can
2444 // eliminate it, do so now.
2445 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
2446 if (PN->getNumIncomingValues() == 2)
Chris Lattner73c50a62010-12-14 07:00:00 +00002447 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00002448
Chris Lattner3d512132010-12-13 06:25:44 +00002449 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00002450 if (BI->isUnconditional()) {
2451 if (SimplifyUncondBranch(BI)) return true;
2452 } else {
Chris Lattner117f8cf2010-12-14 05:57:30 +00002453 if (SimplifyCondBranch(BI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00002454 }
2455 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
2456 if (SimplifyReturn(RI)) return true;
2457 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2458 if (SimplifySwitch(SI)) return true;
2459 } else if (UnreachableInst *UI =
2460 dyn_cast<UnreachableInst>(BB->getTerminator())) {
2461 if (SimplifyUnreachable(UI)) return true;
2462 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
2463 if (SimplifyUnwind(UI)) return true;
2464 } else if (IndirectBrInst *IBI =
2465 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
2466 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00002467 }
2468
Chris Lattner694e37f2003-08-17 19:41:53 +00002469 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002470}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002471
2472/// SimplifyCFG - This function is used to do simplification of a CFG. For
2473/// example, it adjusts branches to branches to eliminate the extra hop, it
2474/// eliminates unreachable basic blocks, and does other "peephole" optimization
2475/// of the CFG. It returns true if a modification was made.
2476///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002477bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2478 return SimplifyCFGOpt(TD).run(BB);
2479}