blob: 4a58eb3d845c9e374c33a2ab25e64b5b1b79945c [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"
Nick Lewycky9d523102011-12-26 20:37:40 +000017#include "llvm/DerivedTypes.h"
18#include "llvm/GlobalVariable.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000019#include "llvm/IRBuilder.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000020#include "llvm/Instructions.h"
Devang Patel383d7ed2009-02-03 22:12:02 +000021#include "llvm/IntrinsicInst.h"
Nick Lewycky06cc66f2011-12-27 04:31:52 +000022#include "llvm/LLVMContext.h"
23#include "llvm/Metadata.h"
Dan Gohman3b205172012-01-05 23:58:56 +000024#include "llvm/Operator.h"
Chris Lattner0d560082004-02-24 05:38:11 +000025#include "llvm/Type.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000032#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramer10fcfb52011-05-14 15:57:25 +000033#include "llvm/Analysis/ValueTracking.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000034#include "llvm/Support/CFG.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000035#include "llvm/Support/CommandLine.h"
Chris Lattnere27db742010-12-17 06:20:15 +000036#include "llvm/Support/ConstantRange.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000037#include "llvm/Support/Debug.h"
Benjamin Kramer937338c2012-05-26 13:59:43 +000038#include "llvm/Support/MDBuilder.h"
Devang Pateld3a17882011-05-19 20:52:46 +000039#include "llvm/Support/NoFolder.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000040#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000043#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000044#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000045#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Peter Collingbourne57808b32011-04-29 18:47:38 +000048static cl::opt<unsigned>
49PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
50 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
51
Evan Chengc3f507f2011-01-29 04:46:23 +000052static cl::opt<bool>
53DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
54 cl::desc("Duplicate return instructions into unconditional branches"));
55
Evan Cheng502a4f52008-06-12 21:15:59 +000056STATISTIC(NumSpeculations, "Number of speculative executed instructions");
57
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000058namespace {
59class SimplifyCFGOpt {
60 const TargetData *const TD;
61
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000062 Value *isValueEqualityComparison(TerminatorInst *TI);
63 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +000064 IntegersSubsetToBB &Mapping);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000065 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +000066 BasicBlock *Pred,
67 IRBuilder<> &Builder);
Devang Patelb55d9242011-05-18 20:53:17 +000068 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
69 IRBuilder<> &Builder);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000070
Devang Patel176ec402011-05-18 21:33:11 +000071 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingaa5abe82012-02-06 21:16:41 +000072 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000073 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patel007349d2011-05-18 20:35:38 +000074 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000075 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patela23812c2011-05-18 18:28:48 +000076 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patel007349d2011-05-18 20:35:38 +000077 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000078
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000079public:
80 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
81 bool run(BasicBlock *BB);
82};
83}
84
Chris Lattner2bdcb562005-08-03 00:19:45 +000085/// SafeToMergeTerminators - Return true if it is safe to merge these two
86/// terminator instructions together.
87///
88static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
89 if (SI1 == SI2) return false; // Can't merge with self!
90
91 // It is not safe to merge these two switch instructions if they have a common
92 // successor, and if that successor has a PHI node, and if *that* PHI node has
93 // conflicting incoming values from the two switch blocks.
94 BasicBlock *SI1BB = SI1->getParent();
95 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000096 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000097
98 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
99 if (SI1Succs.count(*I))
100 for (BasicBlock::iterator BBI = (*I)->begin();
101 isa<PHINode>(BBI); ++BBI) {
102 PHINode *PN = cast<PHINode>(BBI);
103 if (PN->getIncomingValueForBlock(SI1BB) !=
104 PN->getIncomingValueForBlock(SI2BB))
105 return false;
106 }
107
108 return true;
109}
110
Manman Renee28e0f2012-06-13 05:43:29 +0000111/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
112/// to merge these two terminator instructions together, where SI1 is an
113/// unconditional branch. PhiNodes will store all PHI nodes in common
114/// successors.
115///
116static bool isProfitableToFoldUnconditional(BranchInst *SI1,
117 BranchInst *SI2,
Nick Lewyckyedb58422012-06-24 10:15:42 +0000118 Instruction *Cond,
Manman Renee28e0f2012-06-13 05:43:29 +0000119 SmallVectorImpl<PHINode*> &PhiNodes) {
120 if (SI1 == SI2) return false; // Can't merge with self!
121 assert(SI1->isUnconditional() && SI2->isConditional());
122
123 // We fold the unconditional branch if we can easily update all PHI nodes in
124 // common successors:
125 // 1> We have a constant incoming value for the conditional branch;
126 // 2> We have "Cond" as the incoming value for the unconditional branch;
127 // 3> SI2->getCondition() and Cond have same operands.
128 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
129 if (!Ci2) return false;
130 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
131 Cond->getOperand(1) == Ci2->getOperand(1)) &&
132 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
133 Cond->getOperand(1) == Ci2->getOperand(0)))
134 return false;
135
136 BasicBlock *SI1BB = SI1->getParent();
137 BasicBlock *SI2BB = SI2->getParent();
138 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
139 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
140 if (SI1Succs.count(*I))
141 for (BasicBlock::iterator BBI = (*I)->begin();
142 isa<PHINode>(BBI); ++BBI) {
143 PHINode *PN = cast<PHINode>(BBI);
144 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewyckyedb58422012-06-24 10:15:42 +0000145 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Renee28e0f2012-06-13 05:43:29 +0000146 return false;
147 PhiNodes.push_back(PN);
148 }
149 return true;
150}
151
Chris Lattner2bdcb562005-08-03 00:19:45 +0000152/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
153/// now be entries in it from the 'NewPred' block. The values that will be
154/// flowing into the PHI nodes will be the same as those coming in from
155/// ExistPred, an existing predecessor of Succ.
156static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
157 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +0000158 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
159
Chris Lattner093a4382008-07-13 22:23:11 +0000160 PHINode *PN;
161 for (BasicBlock::iterator I = Succ->begin();
162 (PN = dyn_cast<PHINode>(I)); ++I)
163 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000164}
165
Chris Lattner7e663482005-08-03 00:11:16 +0000166
Chris Lattner73c50a62010-12-14 07:00:00 +0000167/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
168/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000169/// to an "if condition". If so, return the boolean condition that determines
170/// which entry into BB will be taken. Also, return by references the block
171/// that will be entered from if the condition is true, and the block that will
172/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000173///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000174/// This does no checking to see if the true/false blocks have large or unsavory
175/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000176static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
177 BasicBlock *&IfFalse) {
178 PHINode *SomePHI = cast<PHINode>(BB->begin());
179 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000180 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000181 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
182 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000183
184 // We can only handle branches. Other control flow will be lowered to
185 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000186 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
187 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
188 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000189 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000190
191 // Eliminate code duplication by ensuring that Pred1Br is conditional if
192 // either are.
193 if (Pred2Br->isConditional()) {
194 // If both branches are conditional, we don't have an "if statement". In
195 // reality, we could transform this case, but since the condition will be
196 // required anyway, we stand no chance of eliminating it, so the xform is
197 // probably not profitable.
198 if (Pred1Br->isConditional())
199 return 0;
200
201 std::swap(Pred1, Pred2);
202 std::swap(Pred1Br, Pred2Br);
203 }
204
205 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000206 // The only thing we have to watch out for here is to make sure that Pred2
207 // doesn't have incoming edges from other blocks. If it does, the condition
208 // doesn't dominate BB.
209 if (Pred2->getSinglePredecessor() == 0)
210 return 0;
211
Chris Lattner723c66d2004-02-11 03:36:04 +0000212 // If we found a conditional branch predecessor, make sure that it branches
213 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
214 if (Pred1Br->getSuccessor(0) == BB &&
215 Pred1Br->getSuccessor(1) == Pred2) {
216 IfTrue = Pred1;
217 IfFalse = Pred2;
218 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
219 Pred1Br->getSuccessor(1) == BB) {
220 IfTrue = Pred2;
221 IfFalse = Pred1;
222 } else {
223 // We know that one arm of the conditional goes to BB, so the other must
224 // go somewhere unrelated, and this must not be an "if statement".
225 return 0;
226 }
227
Chris Lattner723c66d2004-02-11 03:36:04 +0000228 return Pred1Br->getCondition();
229 }
230
231 // Ok, if we got here, both predecessors end with an unconditional branch to
232 // BB. Don't panic! If both blocks only have a single (identical)
233 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000234 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
235 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000236 return 0;
237
238 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000239 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
240 if (BI == 0) return 0;
241
242 assert(BI->isConditional() && "Two successors but not conditional?");
243 if (BI->getSuccessor(0) == Pred1) {
244 IfTrue = Pred1;
245 IfFalse = Pred2;
246 } else {
247 IfTrue = Pred2;
248 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000249 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000250 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000251}
252
Dan Gohman3b205172012-01-05 23:58:56 +0000253/// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
254/// given instruction, which is assumed to be safe to speculate. 1 means
255/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
256static unsigned ComputeSpeculationCost(const User *I) {
257 assert(isSafeToSpeculativelyExecute(I) &&
258 "Instruction is not safe to speculatively execute!");
259 switch (Operator::getOpcode(I)) {
260 default:
261 // In doubt, be conservative.
262 return UINT_MAX;
263 case Instruction::GetElementPtr:
264 // GEPs are cheap if all indices are constant.
265 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
266 return UINT_MAX;
267 return 1;
268 case Instruction::Load:
269 case Instruction::Add:
270 case Instruction::Sub:
271 case Instruction::And:
272 case Instruction::Or:
273 case Instruction::Xor:
274 case Instruction::Shl:
275 case Instruction::LShr:
276 case Instruction::AShr:
277 case Instruction::ICmp:
278 case Instruction::Trunc:
279 case Instruction::ZExt:
280 case Instruction::SExt:
281 return 1; // These are all cheap.
282
283 case Instruction::Call:
284 case Instruction::Select:
285 return 2;
286 }
287}
288
Bill Wendling5049fa62009-01-19 23:43:56 +0000289/// DominatesMergePoint - If we have a merge point of an "if condition" as
290/// accepted above, return true if the specified value dominates the block. We
291/// don't handle the true generality of domination here, just a special case
292/// which works well enough for us.
293///
294/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournef15907f2011-04-29 18:47:31 +0000295/// see if V (which must be an instruction) and its recursive operands
296/// that do not dominate BB have a combined cost lower than CostRemaining and
297/// are non-trapping. If both are true, the instruction is inserted into the
298/// set and true is returned.
299///
300/// The cost for most non-trapping instructions is defined as 1 except for
301/// Select whose cost is 2.
302///
303/// After this function returns, CostRemaining is decreased by the cost of
304/// V plus its non-dominating operands. If that cost is greater than
305/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner9c078662004-10-14 05:13:36 +0000306static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Peter Collingbournef15907f2011-04-29 18:47:31 +0000307 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
308 unsigned &CostRemaining) {
Chris Lattner570751c2004-04-09 22:50:22 +0000309 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000310 if (!I) {
311 // Non-instructions all dominate instructions, but not all constantexprs
312 // can be executed unconditionally.
313 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
314 if (C->canTrap())
315 return false;
316 return true;
317 }
Chris Lattner570751c2004-04-09 22:50:22 +0000318 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000319
Chris Lattnerda895d62005-02-27 06:18:25 +0000320 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000321 // the bottom of this block.
322 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000323
Chris Lattner570751c2004-04-09 22:50:22 +0000324 // If this instruction is defined in a block that contains an unconditional
325 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000326 // statement". If not, it definitely dominates the region.
327 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
328 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
329 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000330
Chris Lattner44da7ca2010-12-14 07:41:39 +0000331 // If we aren't allowing aggressive promotion anymore, then don't consider
332 // instructions in the 'if region'.
333 if (AggressiveInsts == 0) return false;
334
Peter Collingbournef15907f2011-04-29 18:47:31 +0000335 // If we have seen this instruction before, don't count it again.
336 if (AggressiveInsts->count(I)) return true;
337
Chris Lattner44da7ca2010-12-14 07:41:39 +0000338 // Okay, it looks like the instruction IS in the "condition". Check to
339 // see if it's a cheap instruction to unconditionally compute, and if it
340 // only uses stuff defined outside of the condition. If so, hoist it out.
Dan Gohmanf0426602011-12-14 23:49:11 +0000341 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000342 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000343
Dan Gohman3b205172012-01-05 23:58:56 +0000344 unsigned Cost = ComputeSpeculationCost(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000345
Peter Collingbournef15907f2011-04-29 18:47:31 +0000346 if (Cost > CostRemaining)
347 return false;
348
349 CostRemaining -= Cost;
350
351 // Okay, we can only really hoist these out if their operands do
352 // not take us over the cost threshold.
Chris Lattner44da7ca2010-12-14 07:41:39 +0000353 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Peter Collingbournef15907f2011-04-29 18:47:31 +0000354 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000355 return false;
356 // Okay, it's safe to do this! Remember this instruction.
357 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000358 return true;
359}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000360
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000361/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
362/// and PointerNullValue. Return NULL if value is not a constant int.
Chris Lattner28acc132010-12-13 03:30:12 +0000363static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000364 // Normal constant int.
365 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000366 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000367 return CI;
368
369 // This is some kind of pointer constant. Turn it into a pointer-sized
370 // ConstantInt if possible.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000372
373 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
374 if (isa<ConstantPointerNull>(V))
375 return ConstantInt::get(PtrTy, 0);
376
377 // IntToPtr const int.
378 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
379 if (CE->getOpcode() == Instruction::IntToPtr)
380 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
381 // The constant is very likely to have the right type already.
382 if (CI->getType() == PtrTy)
383 return CI;
384 else
385 return cast<ConstantInt>
386 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
387 }
388 return 0;
389}
390
Chris Lattner0aa749b2010-12-13 04:26:26 +0000391/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
392/// collection of icmp eq/ne instructions that compare a value against a
393/// constant, return the value being compared, and stick the constant into the
394/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000395static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000396GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000397 const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000398 Instruction *I = dyn_cast<Instruction>(V);
399 if (I == 0) return 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000400
Chris Lattner7312a222010-12-13 04:50:38 +0000401 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000402 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Chris Lattnere27db742010-12-17 06:20:15 +0000403 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
404 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000405 UsedICmps++;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000406 Vals.push_back(C);
407 return I->getOperand(0);
408 }
Chris Lattnere27db742010-12-17 06:20:15 +0000409
410 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
411 // the set.
412 ConstantRange Span =
Chris Lattnera37029c2010-12-18 20:22:49 +0000413 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Chris Lattnere27db742010-12-17 06:20:15 +0000414
415 // If this is an and/!= check then we want to optimize "x ugt 2" into
416 // x != 0 && x != 1.
417 if (!isEQ)
418 Span = Span.inverse();
419
420 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewyckyf460bf82012-01-19 18:19:42 +0000421 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Chris Lattnere27db742010-12-17 06:20:15 +0000422 return 0;
423
424 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
425 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000426 UsedICmps++;
Chris Lattnere27db742010-12-17 06:20:15 +0000427 return I->getOperand(0);
428 }
Chris Lattner662269d2010-12-13 04:18:32 +0000429 return 0;
430 }
431
Chris Lattner7312a222010-12-13 04:50:38 +0000432 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000433 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000434 return 0;
Chris Lattner662269d2010-12-13 04:18:32 +0000435
Chris Lattner7312a222010-12-13 04:50:38 +0000436 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000437 unsigned UsedICmpsBeforeLHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000438 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000439 isEQ, UsedICmps)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000440 unsigned NumVals = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000441 unsigned UsedICmpsBeforeRHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000442 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000443 isEQ, UsedICmps)) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000444 if (LHS == RHS)
445 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000446 Vals.resize(NumVals);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000447 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000448 }
Chris Lattner7312a222010-12-13 04:50:38 +0000449
450 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
451 // set it and return success.
452 if (Extra == 0 || Extra == I->getOperand(1)) {
453 Extra = I->getOperand(1);
454 return LHS;
455 }
456
457 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000458 UsedICmps = UsedICmpsBeforeLHS;
Chris Lattner7312a222010-12-13 04:50:38 +0000459 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000460 }
Chris Lattner7312a222010-12-13 04:50:38 +0000461
462 // If the LHS can't be folded in, but Extra is available and RHS can, try to
463 // use LHS as Extra.
464 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000465 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000466 Extra = I->getOperand(0);
467 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000468 isEQ, UsedICmps))
Chris Lattner7312a222010-12-13 04:50:38 +0000469 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000470 assert(Vals.size() == NumValsBeforeLHS);
471 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000472 }
473
Chris Lattner0d560082004-02-24 05:38:11 +0000474 return 0;
475}
Nick Lewycky9d523102011-12-26 20:37:40 +0000476
Eli Friedman080efb82008-12-16 20:54:32 +0000477static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Nick Lewycky9d523102011-12-26 20:37:40 +0000478 Instruction *Cond = 0;
Eli Friedman080efb82008-12-16 20:54:32 +0000479 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
480 Cond = dyn_cast<Instruction>(SI->getCondition());
481 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
482 if (BI->isConditional())
483 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000484 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
485 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000486 }
487
488 TI->eraseFromParent();
489 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
490}
491
Chris Lattner9fd49552008-11-27 23:25:44 +0000492/// isValueEqualityComparison - Return true if the specified terminator checks
493/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000494Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
495 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000496 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
497 // Do not permit merging of large switch instructions into their
498 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000499 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
500 pred_end(SI->getParent())) <= 128)
501 CV = SI->getCondition();
502 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000503 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000504 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
505 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
506 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000507 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000508 CV = ICI->getOperand(0);
509
510 // Unwrap any lossless ptrtoint cast.
511 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
512 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
513 CV = PTII->getOperand(0);
514 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000515}
516
Bill Wendling5049fa62009-01-19 23:43:56 +0000517/// GetValueEqualityComparisonCases - Given a value comparison instruction,
518/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000519BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000520GetValueEqualityComparisonCases(TerminatorInst *TI,
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000521 IntegersSubsetToBB &Mapping) {
Chris Lattner542f1492004-02-28 21:28:10 +0000522 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000523 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
524 i != e; ++i)
525 Mapping.add(i.getCaseValueEx(), i.getCaseSuccessor());
Chris Lattner542f1492004-02-28 21:28:10 +0000526 return SI->getDefaultDest();
527 }
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000528
Chris Lattner542f1492004-02-28 21:28:10 +0000529 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000530 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000531 IntegersSubsetToBB Builder;
532
533 Mapping.add(
534 IntItem::fromConstantInt(GetConstantInt(ICI->getOperand(1), TD)),
535 BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE));
536
Reid Spencere4d87aa2006-12-23 06:05:41 +0000537 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000538}
539
Bill Wendling5049fa62009-01-19 23:43:56 +0000540/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
541/// terminator instruction and its block is known to only have a single
542/// predecessor block, check to see if that predecessor is also a value
543/// comparison with the same value, and if that comparison determines the
544/// outcome of this comparison. If so, simplify TI. This does a very limited
545/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000546bool SimplifyCFGOpt::
547SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +0000548 BasicBlock *Pred,
549 IRBuilder<> &Builder) {
Chris Lattner623369a2005-02-24 06:17:52 +0000550 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
551 if (!PredVal) return false; // Not a value comparison in predecessor.
552
553 Value *ThisVal = isValueEqualityComparison(TI);
554 assert(ThisVal && "This isn't a value comparison!!");
555 if (ThisVal != PredVal) return false; // Different predicates.
556
557 // Find out information about when control will move from Pred to TI's block.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000558 IntegersSubsetToBB PredCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000559 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
560 PredCases);
Misha Brukmanfd939082005-04-21 23:48:37 +0000561
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000562 // Remove default from cases.
563 PredCases.removeCase(PredDef);
564
Chris Lattner623369a2005-02-24 06:17:52 +0000565 // Find information about how control leaves this block.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000566 IntegersSubsetToBB ThisCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000567 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Chris Lattner623369a2005-02-24 06:17:52 +0000568
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000569 // Remove default from cases.
570 ThisCases.removeCase(ThisDef);
571
Chris Lattner623369a2005-02-24 06:17:52 +0000572 // If TI's block is the default block from Pred's comparison, potentially
573 // simplify TI based on this knowledge.
574 if (PredDef == TI->getParent()) {
575 // If we are here, we know that the value is none of those cases listed in
576 // PredCases. If there are any cases in ThisCases that are in PredCases, we
577 // can simplify TI.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000578 if (!PredCases.isOverlapped(ThisCases))
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000579 return false;
580
581 if (isa<BranchInst>(TI)) {
582 // Okay, one of the successors of this condbr is dead. Convert it to a
583 // uncond br.
584 assert(ThisCases.size() == 1 && "Branch can only have one case!");
585 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000586 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000587 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000588
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000589 // Remove PHI node entries for the dead edge.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000590 ThisCases.begin()->second->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000591
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000592 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
593 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000594
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000595 EraseTerminatorInstAndDCECond(TI);
596 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000597 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000598
599 SwitchInst *SI = cast<SwitchInst>(TI);
600 // Okay, TI has cases that are statically dead, prune them away.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000601 IRBuilder<> CodeBuilder(SI);
602 CodeBuilder.SetCurrentDebugLocation(SI->getDebugLoc());
Chris Lattner623369a2005-02-24 06:17:52 +0000603
David Greene89d6fd32010-01-05 01:26:52 +0000604 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000605 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000606
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000607 // Okay, TI has cases that are statically dead, prune them away.
608 IntegersSubsetToBB NewThisCases;
609 IntegersSubsetToBB WastedCases;
610 ThisCases.diff(&NewThisCases, &WastedCases, 0, PredCases);
611
612 IntegersSubsetToBB::Cases Cases;
613 NewThisCases.getCases(Cases, true/*temporary prevent complex cases*/);
614
615 SwitchInst *NewSI =
616 CodeBuilder.CreateSwitch(ThisVal, SI->getDefaultDest(), Cases.size());
617
618 for (IntegersSubsetToBB::RangeIterator i = WastedCases.begin(),
619 e = WastedCases.end(); i != e; ++i)
620 i->second->removePredecessor(TI->getParent());
621
622 for (IntegersSubsetToBB::CasesIt i = Cases.begin(), e = Cases.end();
623 i != e; ++i)
624 NewSI->addCase(i->second, i->first);
625
626 EraseTerminatorInstAndDCECond(SI);
627 DEBUG(dbgs() << "Leaving: " << *NewSI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000628 return true;
629 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000630
631 // Otherwise, TI's block must correspond to some matched value. Find out
632 // which value (or set of values) this is.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000633 BasicBlock *TIBB = TI->getParent();
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000634 const IntItem* TIVIntITem = PredCases.getCaseSingleNumber(TIBB);
635 assert(TIVIntITem && "No edge from pred to succ?");
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000636
637 // Okay, we found the one constant that our value can be if we get into TI's
638 // BB. Find out which successor will unconditionally be branched to.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000639 BasicBlock *TheRealDest = ThisCases.findSuccessor(*TIVIntITem);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000640
641 // If not handled by any explicit cases, it is handled by the default case.
642 if (TheRealDest == 0) TheRealDest = ThisDef;
643
644 // Remove PHI node entries for dead edges.
645 BasicBlock *CheckEdge = TheRealDest;
646 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
647 if (*SI != CheckEdge)
648 (*SI)->removePredecessor(TIBB);
649 else
650 CheckEdge = 0;
651
652 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000653 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000654 (void) NI;
655
656 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
657 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
658
659 EraseTerminatorInstAndDCECond(TI);
660 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000661}
662
Dale Johannesenc81f5442009-03-12 21:01:11 +0000663namespace {
664 /// ConstantIntOrdering - This class implements a stable ordering of constant
665 /// integers that does not depend on their address. This is important for
666 /// applications that sort ConstantInt's to ensure uniqueness.
667 struct ConstantIntOrdering {
668 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
669 return LHS->getValue().ult(RHS->getValue());
670 }
671 };
672}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000673
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000674static int ConstantIntSortPredicate(const void *P1, const void *P2) {
675 const ConstantInt *LHS = *(const ConstantInt**)P1;
676 const ConstantInt *RHS = *(const ConstantInt**)P2;
Chris Lattnerba3c8152010-12-15 04:52:41 +0000677 if (LHS->getValue().ult(RHS->getValue()))
678 return 1;
679 if (LHS->getValue() == RHS->getValue())
680 return 0;
681 return -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000682}
683
Bill Wendling5049fa62009-01-19 23:43:56 +0000684/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
685/// equality comparison instruction (either a switch or a branch on "X == c").
686/// See if any of the predecessors of the terminator block are value comparisons
687/// on the same value. If so, and if safe to do so, fold them together.
Devang Patelb55d9242011-05-18 20:53:17 +0000688bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
689 IRBuilder<> &Builder) {
Chris Lattner542f1492004-02-28 21:28:10 +0000690 BasicBlock *BB = TI->getParent();
691 Value *CV = isValueEqualityComparison(TI); // CondVal
692 assert(CV && "Not a comparison?");
693 bool Changed = false;
694
Chris Lattner82442432008-02-18 07:42:56 +0000695 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000696 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000697 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000698
Chris Lattner542f1492004-02-28 21:28:10 +0000699 // See if the predecessor is a comparison with the same value.
700 TerminatorInst *PTI = Pred->getTerminator();
701 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
702
703 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
704 // Figure out which 'cases' to copy from SI to PSI.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000705 IntegersSubsetToBB BBCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000706 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
707
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000708 IntegersSubsetToBB PredCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000709 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
710
711 // Based on whether the default edge from PTI goes to BB or not, fill in
712 // PredCases and PredDefault with the new switch cases we would like to
713 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000714 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000715
716 if (PredDefault == BB) {
717 // If this is the default destination from PTI, only the edges in TI
718 // that don't occur in PTI, or that branch to BB will be activated.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000719
720 PredCases.removeCase(BB);
721 IntegersSubsetToBB NewBBCases;
722 BBCases.diff(&NewBBCases, 0, 0, PredCases);
723 PredCases.add(NewBBCases);
724 for (IntegersSubsetToBB::RangeIterator i = NewBBCases.begin(),
725 e = NewBBCases.end(); i != e; ++i)
726 NewSuccessors.push_back(i->second);
Chris Lattner542f1492004-02-28 21:28:10 +0000727
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000728 // Replace the default if needed.
Chris Lattner542f1492004-02-28 21:28:10 +0000729 if (PredDefault != BBDefault) {
730 PredDefault->removePredecessor(Pred);
731 PredDefault = BBDefault;
732 NewSuccessors.push_back(BBDefault);
733 }
Chris Lattner542f1492004-02-28 21:28:10 +0000734
735 } else {
736 // If this is not the default destination from PSI, only the edges
737 // in SI that occur in PSI with a destination of BB will be
738 // activated.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000739 IntegersSubsetToBB BBPredCase;
740 PredCases.detachCase(BBPredCase, BB);
741 IntegersSubsetToBB CasesWithBBDef;
742 IntegersSubsetToBB InharitedCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000743
744 // Okay, now we know which constants were sent to BB from the
745 // predecessor. Figure out where they will all go now.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000746 if (!BBPredCase.empty()) {
747 BBCases.diff(
748 0, // LHS excl RHS
749 &InharitedCases, // intersection
750 &CasesWithBBDef, // RHS excl LHS
751 BBPredCase); // RHS.
752 }
753 PredCases.add(InharitedCases);
754 for (IntegersSubsetToBB::RangeIterator i = InharitedCases.begin(),
755 e = InharitedCases.end();
756 i != e; ++i)
757 NewSuccessors.push_back(i->second);
758
Chris Lattner542f1492004-02-28 21:28:10 +0000759 // If there are any constants vectored to BB that TI doesn't handle,
760 // they must go to the default destination of TI.
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000761 PredCases.add(CasesWithBBDef, BBDefault);
762 for (unsigned i = 0, e = CasesWithBBDef.size(); i != e; ++i)
Chris Lattner542f1492004-02-28 21:28:10 +0000763 NewSuccessors.push_back(BBDefault);
Chris Lattner542f1492004-02-28 21:28:10 +0000764 }
765
766 // Okay, at this point, we know which new successor Pred will get. Make
767 // sure we update the number of entries in the PHI nodes for these
768 // successors.
769 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
770 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
771
Devang Patelb55d9242011-05-18 20:53:17 +0000772 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000773 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000774 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000775 assert(TD && "Cannot switch on pointer without TargetData");
Devang Patelb55d9242011-05-18 20:53:17 +0000776 CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
777 "magicptr");
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000778 }
779
Chris Lattner542f1492004-02-28 21:28:10 +0000780 // Now that the successors are updated, create the new Switch instruction.
Devang Patelb55d9242011-05-18 20:53:17 +0000781 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
782 PredCases.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +0000783 NewSI->setDebugLoc(PTI->getDebugLoc());
Stepan Dyatkovskiyb2833d92012-07-02 13:02:18 +0000784 IntegersSubsetToBB::Cases Cases;
785 PredCases.getCases(Cases, true/*temporary prevent complex case*/);
786
787 for (IntegersSubsetToBB::CasesIt i = Cases.begin(), e = Cases.end();
788 i != e; ++i)
789 NewSI->addCase(i->second, i->first);
Chris Lattner13b2f762005-01-01 16:02:12 +0000790
Eli Friedman080efb82008-12-16 20:54:32 +0000791 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000792
Chris Lattner542f1492004-02-28 21:28:10 +0000793 // Okay, last check. If BB is still a successor of PSI, then we must
794 // have an infinite loop case. If so, add an infinitely looping block
795 // to handle the case to preserve the behavior of the code.
796 BasicBlock *InfLoopBlock = 0;
797 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
798 if (NewSI->getSuccessor(i) == BB) {
799 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000800 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000801 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +0000802 InfLoopBlock = BasicBlock::Create(BB->getContext(),
803 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +0000804 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000805 }
806 NewSI->setSuccessor(i, InfLoopBlock);
807 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000808
Chris Lattner542f1492004-02-28 21:28:10 +0000809 Changed = true;
810 }
811 }
812 return Changed;
813}
814
Dale Johannesenc1f10402009-06-15 20:59:27 +0000815// isSafeToHoistInvoke - If we would need to insert a select that uses the
816// value of this invoke (comments in HoistThenElseCodeToIf explain why we
817// would need to do this), we can't hoist the invoke, as there is nowhere
818// to put the select in this case.
819static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
820 Instruction *I1, Instruction *I2) {
821 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
822 PHINode *PN;
823 for (BasicBlock::iterator BBI = SI->begin();
824 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
825 Value *BB1V = PN->getIncomingValueForBlock(BB1);
826 Value *BB2V = PN->getIncomingValueForBlock(BB2);
827 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
828 return false;
829 }
830 }
831 }
832 return true;
833}
834
Chris Lattner6306d072005-08-03 17:59:45 +0000835/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000836/// BB2, hoist any common code in the two blocks up into the branch block. The
837/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Rafael Espindola216dde92011-05-19 02:26:30 +0000838static bool HoistThenElseCodeToIf(BranchInst *BI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000839 // This does very trivial matching, with limited scanning, to find identical
840 // instructions in the two blocks. In particular, we don't want to get into
841 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
842 // such, we currently just scan for obviously identical instructions in an
843 // identical order.
844 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
845 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
846
Devang Patel65085cf2009-02-04 00:03:08 +0000847 BasicBlock::iterator BB1_Itr = BB1->begin();
848 BasicBlock::iterator BB2_Itr = BB2->begin();
849
850 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +0000851 // Skip debug info if it is not identical.
852 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
853 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
854 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
855 while (isa<DbgInfoIntrinsic>(I1))
856 I1 = BB1_Itr++;
857 while (isa<DbgInfoIntrinsic>(I2))
858 I2 = BB2_Itr++;
859 }
Devang Patelae6c95b2011-04-07 00:30:15 +0000860 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +0000861 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000862 return false;
863
864 // If we get here, we can hoist at least one instruction.
865 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000866
867 do {
868 // If we are hoisting the terminator instruction, don't move one (making a
869 // broken BB), instead clone it, and remove BI.
870 if (isa<TerminatorInst>(I1))
871 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000872
Chris Lattner37dc9382004-11-30 00:29:14 +0000873 // For a normal instruction, we just move one to right before the branch,
874 // then replace all uses of the other with the first. Finally, we remove
875 // the now redundant second instruction.
876 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
877 if (!I2->use_empty())
878 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000879 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +0000880 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000881
Devang Patel65085cf2009-02-04 00:03:08 +0000882 I1 = BB1_Itr++;
Devang Patel65085cf2009-02-04 00:03:08 +0000883 I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +0000884 // Skip debug info if it is not identical.
885 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
886 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
887 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
888 while (isa<DbgInfoIntrinsic>(I1))
889 I1 = BB1_Itr++;
890 while (isa<DbgInfoIntrinsic>(I2))
891 I2 = BB2_Itr++;
892 }
Devang Patelae6c95b2011-04-07 00:30:15 +0000893 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +0000894
895 return true;
896
897HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000898 // It may not be possible to hoist an invoke.
899 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
900 return true;
901
Chris Lattner37dc9382004-11-30 00:29:14 +0000902 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +0000903 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +0000904 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +0000905 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000906 I1->replaceAllUsesWith(NT);
907 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000908 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000909 }
910
Devang Pateld3a17882011-05-19 20:52:46 +0000911 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner37dc9382004-11-30 00:29:14 +0000912 // Hoisting one of the terminators from our successor is a great thing.
913 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
914 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
915 // nodes, so we insert select instruction to compute the final result.
916 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
917 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
918 PHINode *PN;
919 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000920 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000921 Value *BB1V = PN->getIncomingValueForBlock(BB1);
922 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000923 if (BB1V == BB2V) continue;
924
925 // These values do not agree. Insert a select instruction before NT
926 // that determines the right value.
927 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Devang Pateld3a17882011-05-19 20:52:46 +0000928 if (SI == 0)
929 SI = cast<SelectInst>
930 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
931 BB1V->getName()+"."+BB2V->getName()));
932
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000933 // Make the PHI node use the select for all incoming values for BB1/BB2
934 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
935 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
936 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000937 }
938 }
939
940 // Update any PHI nodes in our new successors.
941 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
942 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000943
Eli Friedman080efb82008-12-16 20:54:32 +0000944 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000945 return true;
946}
947
Evan Cheng4d09efd2008-06-07 08:52:29 +0000948/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
949/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
950/// (for now, restricted to a single instruction that's side effect free) from
951/// the BB1 into the branch block to speculatively execute it.
Dan Gohman3b205172012-01-05 23:58:56 +0000952///
953/// Turn
954/// BB:
955/// %t1 = icmp
956/// br i1 %t1, label %BB1, label %BB2
957/// BB1:
958/// %t3 = add %t2, c
959/// br label BB2
960/// BB2:
961/// =>
962/// BB:
963/// %t1 = icmp
964/// %t4 = add %t2, c
965/// %t3 = select i1 %t1, %t2, %t3
Rafael Espindola216dde92011-05-19 02:26:30 +0000966static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
Evan Cheng4d09efd2008-06-07 08:52:29 +0000967 // Only speculatively execution a single instruction (not counting the
968 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000969 Instruction *HInst = NULL;
970 Instruction *Term = BB1->getTerminator();
971 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
972 BBI != BBE; ++BBI) {
973 Instruction *I = BBI;
974 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000975 if (isa<DbgInfoIntrinsic>(I)) continue;
976 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +0000977
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000978 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +0000979 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000980 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +0000981 }
Dan Gohman3b205172012-01-05 23:58:56 +0000982
983 BasicBlock *BIParent = BI->getParent();
984
985 // Check the instruction to be hoisted, if there is one.
986 if (HInst) {
987 // Don't hoist the instruction if it's unsafe or expensive.
988 if (!isSafeToSpeculativelyExecute(HInst))
989 return false;
990 if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
991 return false;
992
993 // Do not hoist the instruction if any of its operands are defined but not
994 // used in this BB. The transformation will prevent the operand from
995 // being sunk into the use block.
996 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
997 i != e; ++i) {
998 Instruction *OpI = dyn_cast<Instruction>(*i);
999 if (OpI && OpI->getParent() == BIParent &&
1000 !OpI->mayHaveSideEffects() &&
1001 !OpI->isUsedInBasicBlock(BIParent))
1002 return false;
1003 }
1004 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001005
Evan Cheng797d9512008-06-11 19:18:20 +00001006 // Be conservative for now. FP select instruction can often be expensive.
1007 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001008 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +00001009 return false;
1010
Evan Cheng4d09efd2008-06-07 08:52:29 +00001011 // If BB1 is actually on the false edge of the conditional branch, remember
1012 // to swap the select operands later.
1013 bool Invert = false;
1014 if (BB1 != BI->getSuccessor(0)) {
1015 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1016 Invert = true;
1017 }
1018
Dan Gohman3b205172012-01-05 23:58:56 +00001019 // Collect interesting PHIs, and scan for hazards.
1020 SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001021 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Dan Gohman3b205172012-01-05 23:58:56 +00001022 for (BasicBlock::iterator I = BB2->begin();
1023 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1024 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1025 Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
1026
1027 // Skip PHIs which are trivial.
1028 if (BB1V == BIParentV)
1029 continue;
1030
1031 // Check for saftey.
1032 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
1033 // An unfolded ConstantExpr could end up getting expanded into
1034 // Instructions. Don't speculate this and another instruction at
1035 // the same time.
1036 if (HInst)
1037 return false;
1038 if (!isSafeToSpeculativelyExecute(CE))
1039 return false;
1040 if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
1041 return false;
1042 }
1043
1044 // Ok, we may insert a select for this PHI.
1045 PHIs.insert(std::make_pair(BB1V, BIParentV));
Evan Cheng4d09efd2008-06-07 08:52:29 +00001046 }
Dan Gohman3b205172012-01-05 23:58:56 +00001047
1048 // If there are no PHIs to process, bail early. This helps ensure idempotence
1049 // as well.
1050 if (PHIs.empty())
1051 return false;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001052
Dan Gohman3b205172012-01-05 23:58:56 +00001053 // If we get here, we can hoist the instruction and if-convert.
1054 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001055
Dan Gohman3b205172012-01-05 23:58:56 +00001056 // Hoist the instruction.
1057 if (HInst)
1058 BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
Evan Cheng502a4f52008-06-12 21:15:59 +00001059
Dan Gohman3b205172012-01-05 23:58:56 +00001060 // Insert selects and rewrite the PHI operands.
Devang Pateld3a17882011-05-19 20:52:46 +00001061 IRBuilder<true, NoFolder> Builder(BI);
Dan Gohman3b205172012-01-05 23:58:56 +00001062 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
1063 Value *TrueV = PHIs[i].first;
1064 Value *FalseV = PHIs[i].second;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001065
Dan Gohman3b205172012-01-05 23:58:56 +00001066 // Create a select whose true value is the speculatively executed value and
1067 // false value is the previously determined FalseV.
1068 SelectInst *SI;
1069 if (Invert)
1070 SI = cast<SelectInst>
1071 (Builder.CreateSelect(BrCond, FalseV, TrueV,
1072 FalseV->getName() + "." + TrueV->getName()));
1073 else
1074 SI = cast<SelectInst>
1075 (Builder.CreateSelect(BrCond, TrueV, FalseV,
1076 TrueV->getName() + "." + FalseV->getName()));
1077
1078 // Make the PHI node use the select for all incoming values for "then" and
1079 // "if" blocks.
1080 for (BasicBlock::iterator I = BB2->begin();
1081 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1082 unsigned BB1I = PN->getBasicBlockIndex(BB1);
1083 unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
1084 Value *BB1V = PN->getIncomingValue(BB1I);
1085 Value *BIParentV = PN->getIncomingValue(BIParentI);
1086 if (TrueV == BB1V && FalseV == BIParentV) {
1087 PN->setIncomingValue(BB1I, SI);
1088 PN->setIncomingValue(BIParentI, SI);
1089 }
1090 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001091 }
1092
Evan Cheng502a4f52008-06-12 21:15:59 +00001093 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001094 return true;
1095}
1096
Chris Lattner2e42e362005-09-20 00:43:16 +00001097/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1098/// across this block.
1099static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1100 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001101 unsigned Size = 0;
1102
Devang Patel9200c892009-03-10 18:00:05 +00001103 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001104 if (isa<DbgInfoIntrinsic>(BBI))
1105 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001106 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001107 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001108
Dale Johannesen8483e542009-03-12 23:18:09 +00001109 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001110 // live outside of the current basic block.
1111 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1112 UI != E; ++UI) {
1113 Instruction *U = cast<Instruction>(*UI);
1114 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1115 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001116
1117 // Looks ok, continue checking.
1118 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001119
Chris Lattner2e42e362005-09-20 00:43:16 +00001120 return true;
1121}
1122
Chris Lattnereaba3a12005-09-19 23:49:37 +00001123/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1124/// that is defined in the same block as the branch and if any PHI entries are
1125/// constants, thread edges corresponding to that entry to be branches to their
1126/// ultimate destination.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001127static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001128 BasicBlock *BB = BI->getParent();
1129 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001130 // NOTE: we currently cannot transform this case if the PHI node is used
1131 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001132 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1133 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001134
1135 // Degenerate case of a single entry PHI.
1136 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001137 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001138 return true;
1139 }
1140
1141 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001142 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001143
1144 // Okay, this is a simple enough basic block. See if any phi values are
1145 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001146 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001147 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1148 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1149
1150 // Okay, we now know that all edges from PredBB should be revectored to
1151 // branch to RealDest.
1152 BasicBlock *PredBB = PN->getIncomingBlock(i);
1153 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1154
1155 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling6a648b82011-06-04 09:42:04 +00001156 // Skip if the predecessor's terminator is an indirect branch.
1157 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001158
1159 // The dest block might have PHI nodes, other predecessors and other
1160 // difficult cases. Instead of being smart about this, just insert a new
1161 // block that jumps to the destination block, effectively splitting
1162 // the edge we are about to create.
1163 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1164 RealDest->getName()+".critedge",
1165 RealDest->getParent(), RealDest);
1166 BranchInst::Create(RealDest, EdgeBB);
Chris Lattner6de0a282010-12-14 07:09:42 +00001167
1168 // Update PHI nodes.
1169 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001170
1171 // BB may have instructions that are being threaded over. Clone these
1172 // instructions into EdgeBB. We know that there will be no uses of the
1173 // cloned instructions outside of EdgeBB.
1174 BasicBlock::iterator InsertPt = EdgeBB->begin();
1175 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1176 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1177 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1178 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1179 continue;
1180 }
1181 // Clone the instruction.
1182 Instruction *N = BBI->clone();
1183 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1184
1185 // Update operands due to translation.
1186 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1187 i != e; ++i) {
1188 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1189 if (PI != TranslateMap.end())
1190 *i = PI->second;
1191 }
1192
1193 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001194 if (Value *V = SimplifyInstruction(N, TD)) {
1195 TranslateMap[BBI] = V;
1196 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001197 } else {
1198 // Insert the new instruction into its new home.
1199 EdgeBB->getInstList().insert(InsertPt, N);
1200 if (!BBI->use_empty())
1201 TranslateMap[BBI] = N;
1202 }
1203 }
1204
1205 // Loop over all of the edges from PredBB to BB, changing them to branch
1206 // to EdgeBB instead.
1207 TerminatorInst *PredBBTI = PredBB->getTerminator();
1208 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1209 if (PredBBTI->getSuccessor(i) == BB) {
1210 BB->removePredecessor(PredBB);
1211 PredBBTI->setSuccessor(i, EdgeBB);
1212 }
Bill Wendling6a648b82011-06-04 09:42:04 +00001213
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001214 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001215 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001216 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001217
1218 return false;
1219}
1220
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001221/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1222/// PHI node, see if we can eliminate it.
Devang Pateld3a17882011-05-19 20:52:46 +00001223static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001224 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1225 // statement", which has a very simple dominance structure. Basically, we
1226 // are trying to find the condition that is being branched on, which
1227 // subsequently causes this merge to happen. We really want control
1228 // dependence information for this check, but simplifycfg can't keep it up
1229 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001230 BasicBlock *BB = PN->getParent();
1231 BasicBlock *IfTrue, *IfFalse;
1232 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001233 if (!IfCond ||
1234 // Don't bother if the branch will be constant folded trivially.
1235 isa<ConstantInt>(IfCond))
1236 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001237
Chris Lattner822a8792006-11-18 19:19:36 +00001238 // Okay, we found that we can merge this two-entry phi node into a select.
1239 // Doing so would require us to fold *all* two entry phi nodes in this block.
1240 // At some point this becomes non-profitable (particularly if the target
1241 // doesn't support cmov's). Only do this transformation if there are two or
1242 // fewer PHI nodes in this block.
1243 unsigned NumPhis = 0;
1244 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1245 if (NumPhis > 2)
1246 return false;
1247
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001248 // Loop over the PHI's seeing if we can promote them all to select
1249 // instructions. While we are at it, keep track of the instructions
1250 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001251 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne57808b32011-04-29 18:47:38 +00001252 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1253 MaxCostVal1 = PHINodeFoldingThreshold;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001254
Chris Lattner3aff13b2010-12-14 08:46:09 +00001255 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1256 PHINode *PN = cast<PHINode>(II++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001257 if (Value *V = SimplifyInstruction(PN, TD)) {
1258 PN->replaceAllUsesWith(V);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001259 PN->eraseFromParent();
Chris Lattner07ff3532010-12-14 07:20:29 +00001260 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001261 }
Chris Lattner07ff3532010-12-14 07:20:29 +00001262
Peter Collingbournef15907f2011-04-29 18:47:31 +00001263 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1264 MaxCostVal0) ||
1265 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1266 MaxCostVal1))
Chris Lattner07ff3532010-12-14 07:20:29 +00001267 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001268 }
1269
Chris Lattner44da7ca2010-12-14 07:41:39 +00001270 // If we folded the the first phi, PN dangles at this point. Refresh it. If
1271 // we ran out of PHIs then we simplified them all.
1272 PN = dyn_cast<PHINode>(BB->begin());
1273 if (PN == 0) return true;
1274
Chris Lattner3aff13b2010-12-14 08:46:09 +00001275 // Don't fold i1 branches on PHIs which contain binary operators. These can
1276 // often be turned into switches and other things.
1277 if (PN->getType()->isIntegerTy(1) &&
1278 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1279 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1280 isa<BinaryOperator>(IfCond)))
1281 return false;
1282
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001283 // If we all PHI nodes are promotable, check to make sure that all
1284 // instructions in the predecessor blocks can be promoted as well. If
1285 // not, we won't be able to get rid of the control flow, so it's not
1286 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001287 BasicBlock *DomBlock = 0;
1288 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1289 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1290 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1291 IfBlock1 = 0;
1292 } else {
1293 DomBlock = *pred_begin(IfBlock1);
1294 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001295 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001296 // This is not an aggressive instruction that we can promote.
1297 // Because of this, we won't be able to get rid of the control
1298 // flow, so the xform is not worth it.
1299 return false;
1300 }
1301 }
1302
Chris Lattner44da7ca2010-12-14 07:41:39 +00001303 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1304 IfBlock2 = 0;
1305 } else {
1306 DomBlock = *pred_begin(IfBlock2);
1307 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001308 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001309 // This is not an aggressive instruction that we can promote.
1310 // Because of this, we won't be able to get rid of the control
1311 // flow, so the xform is not worth it.
1312 return false;
1313 }
1314 }
Chris Lattnere0b18e52010-12-14 07:23:10 +00001315
1316 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001317 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001318
1319 // If we can still promote the PHI nodes after this gauntlet of tests,
1320 // do all of the PHI's now.
Chris Lattner3aff13b2010-12-14 08:46:09 +00001321 Instruction *InsertPt = DomBlock->getTerminator();
Devang Pateld3a17882011-05-19 20:52:46 +00001322 IRBuilder<true, NoFolder> Builder(InsertPt);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001323
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001324 // Move all 'aggressive' instructions, which are defined in the
1325 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001326 if (IfBlock1)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001327 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001328 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001329 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001330 if (IfBlock2)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001331 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001332 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001333 IfBlock2->getTerminator());
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001334
1335 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1336 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001337 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1338 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001339
Devang Patelf60364d2011-05-18 18:16:44 +00001340 SelectInst *NV =
1341 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner86cc4232007-02-11 01:37:51 +00001342 PN->replaceAllUsesWith(NV);
1343 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001344 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001345 }
Chris Lattner60d410d2010-12-14 08:01:53 +00001346
1347 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1348 // has been flattened. Change DomBlock to jump directly to our new block to
1349 // avoid other simplifycfg's kicking in on the diamond.
1350 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patelf60364d2011-05-18 18:16:44 +00001351 Builder.SetInsertPoint(OldTI);
1352 Builder.CreateBr(BB);
Chris Lattner60d410d2010-12-14 08:01:53 +00001353 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001354 return true;
1355}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001356
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001357/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1358/// to two returning blocks, try to merge them together into one return,
1359/// introducing a select if the return values disagree.
Devang Patel176ec402011-05-18 21:33:11 +00001360static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1361 IRBuilder<> &Builder) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001362 assert(BI->isConditional() && "Must be a conditional branch");
1363 BasicBlock *TrueSucc = BI->getSuccessor(0);
1364 BasicBlock *FalseSucc = BI->getSuccessor(1);
1365 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1366 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1367
1368 // Check to ensure both blocks are empty (just a return) or optionally empty
1369 // with PHI nodes. If there are other instructions, merging would cause extra
1370 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001371 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001372 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001373 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001374 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001375
Devang Patel176ec402011-05-18 21:33:11 +00001376 Builder.SetInsertPoint(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001377 // Okay, we found a branch that is going to two return nodes. If
1378 // there is no return value for this function, just change the
1379 // branch into a return.
1380 if (FalseRet->getNumOperands() == 0) {
1381 TrueSucc->removePredecessor(BI->getParent());
1382 FalseSucc->removePredecessor(BI->getParent());
Devang Patel176ec402011-05-18 21:33:11 +00001383 Builder.CreateRetVoid();
Eli Friedman080efb82008-12-16 20:54:32 +00001384 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001385 return true;
1386 }
1387
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001388 // Otherwise, figure out what the true and false return values are
1389 // so we can insert a new select instruction.
1390 Value *TrueValue = TrueRet->getReturnValue();
1391 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001392
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001393 // Unwrap any PHI nodes in the return blocks.
1394 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1395 if (TVPN->getParent() == TrueSucc)
1396 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1397 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1398 if (FVPN->getParent() == FalseSucc)
1399 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1400
1401 // In order for this transformation to be safe, we must be able to
1402 // unconditionally execute both operands to the return. This is
1403 // normally the case, but we could have a potentially-trapping
1404 // constant expression that prevents this transformation from being
1405 // safe.
1406 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1407 if (TCV->canTrap())
1408 return false;
1409 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1410 if (FCV->canTrap())
1411 return false;
1412
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001413 // Okay, we collected all the mapped values and checked them for sanity, and
1414 // defined to really do this transformation. First, update the CFG.
1415 TrueSucc->removePredecessor(BI->getParent());
1416 FalseSucc->removePredecessor(BI->getParent());
1417
1418 // Insert select instructions where needed.
1419 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001420 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001421 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001422 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1423 } else if (isa<UndefValue>(TrueValue)) {
1424 TrueValue = FalseValue;
1425 } else {
Devang Patel176ec402011-05-18 21:33:11 +00001426 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1427 FalseValue, "retval");
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001428 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001429 }
1430
Devang Patel176ec402011-05-18 21:33:11 +00001431 Value *RI = !TrueValue ?
1432 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1433
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001434 (void) RI;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001435
David Greene89d6fd32010-01-05 01:26:52 +00001436 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001437 << "\n " << *BI << "NewRet = " << *RI
1438 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001439
Eli Friedman080efb82008-12-16 20:54:32 +00001440 EraseTerminatorInstAndDCECond(BI);
1441
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001442 return true;
1443}
1444
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001445/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1446/// probabilities of the branch taking each edge. Fills in the two APInt
1447/// parameters and return true, or returns false if no or invalid metadata was
1448/// found.
1449static bool ExtractBranchMetadata(BranchInst *BI,
1450 APInt &ProbTrue, APInt &ProbFalse) {
1451 assert(BI->isConditional() &&
1452 "Looking for probabilities on unconditional branch?");
1453 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky91968482011-12-27 18:27:22 +00001454 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001455 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1456 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky91968482011-12-27 18:27:22 +00001457 if (!CITrue || !CIFalse) return false;
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001458 ProbTrue = CITrue->getValue();
1459 ProbFalse = CIFalse->getValue();
1460 assert(ProbTrue.getBitWidth() == 32 && ProbFalse.getBitWidth() == 32 &&
1461 "Branch probability metadata must be 32-bit integers");
1462 return true;
1463}
1464
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001465/// MultiplyAndLosePrecision - Multiplies A and B, then returns the result. In
1466/// the event of overflow, logically-shifts all four inputs right until the
1467/// multiply fits.
1468static APInt MultiplyAndLosePrecision(APInt &A, APInt &B, APInt &C, APInt &D,
1469 unsigned &BitsLost) {
1470 BitsLost = 0;
1471 bool Overflow = false;
1472 APInt Result = A.umul_ov(B, Overflow);
1473 if (Overflow) {
1474 APInt MaxB = APInt::getMaxValue(A.getBitWidth()).udiv(A);
1475 do {
1476 B = B.lshr(1);
1477 ++BitsLost;
1478 } while (B.ugt(MaxB));
1479 A = A.lshr(BitsLost);
1480 C = C.lshr(BitsLost);
1481 D = D.lshr(BitsLost);
1482 Result = A * B;
1483 }
1484 return Result;
1485}
1486
Manman Renee28e0f2012-06-13 05:43:29 +00001487/// checkCSEInPredecessor - Return true if the given instruction is available
1488/// in its predecessor block. If yes, the instruction will be removed.
1489///
1490bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1491 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1492 return false;
1493 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1494 Instruction *PBI = &*I;
1495 // Check whether Inst and PBI generate the same value.
1496 if (Inst->isIdenticalTo(PBI)) {
1497 Inst->replaceAllUsesWith(PBI);
1498 Inst->eraseFromParent();
1499 return true;
1500 }
1501 }
1502 return false;
1503}
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001504
Chris Lattnerc8fbc342011-04-11 23:24:57 +00001505/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1506/// predecessor branches to us and one of our successors, fold the block into
1507/// the predecessor and use logical operations to pick the right destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001508bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001509 BasicBlock *BB = BI->getParent();
Devang Pateld3a17882011-05-19 20:52:46 +00001510
Manman Renee28e0f2012-06-13 05:43:29 +00001511 Instruction *Cond = 0;
1512 if (BI->isConditional())
1513 Cond = dyn_cast<Instruction>(BI->getCondition());
1514 else {
1515 // For unconditional branch, check for a simple CFG pattern, where
1516 // BB has a single predecessor and BB's successor is also its predecessor's
1517 // successor. If such pattern exisits, check for CSE between BB and its
1518 // predecessor.
1519 if (BasicBlock *PB = BB->getSinglePredecessor())
1520 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1521 if (PBI->isConditional() &&
1522 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1523 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1524 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1525 I != E; ) {
1526 Instruction *Curr = I++;
1527 if (isa<CmpInst>(Curr)) {
1528 Cond = Curr;
1529 break;
1530 }
1531 // Quit if we can't remove this instruction.
1532 if (!checkCSEInPredecessor(Curr, PB))
1533 return false;
1534 }
1535 }
1536
1537 if (Cond == 0)
1538 return false;
1539 }
1540
Owen Andersone84178a2010-07-14 19:52:16 +00001541 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1542 Cond->getParent() != BB || !Cond->hasOneUse())
1543 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001544
Chris Lattner1347e872008-07-13 21:12:01 +00001545 // Only allow this if the condition is a simple instruction that can be
1546 // executed unconditionally. It must be in the same block as the branch, and
1547 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001548 BasicBlock::iterator FrontIt = BB->front();
Chris Lattner3c6e7462011-04-14 02:44:53 +00001549
Devang Pateld0a203d2009-02-04 21:39:48 +00001550 // Ignore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001551 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Nick Lewycky9d523102011-12-26 20:37:40 +00001552
Owen Andersone84178a2010-07-14 19:52:16 +00001553 // Allow a single instruction to be hoisted in addition to the compare
1554 // that feeds the branch. We later ensure that any values that _it_ uses
1555 // were also live in the predecessor, so that we don't unnecessarily create
1556 // register pressure or inhibit out-of-order execution.
1557 Instruction *BonusInst = 0;
1558 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001559 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
Dan Gohmanf0426602011-12-14 23:49:11 +00001560 isSafeToSpeculativelyExecute(FrontIt)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001561 BonusInst = &*FrontIt;
1562 ++FrontIt;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001563
1564 // Ignore dbg intrinsics.
1565 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Devang Patel60d490c2011-04-07 23:11:25 +00001566 }
1567
Owen Andersone84178a2010-07-14 19:52:16 +00001568 // Only a single bonus inst is allowed.
1569 if (&*FrontIt != Cond)
1570 return false;
1571
Chris Lattner1347e872008-07-13 21:12:01 +00001572 // Make sure the instruction after the condition is the cond branch.
1573 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001574
Devang Pateld0a203d2009-02-04 21:39:48 +00001575 // Ingore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001576 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
1577
1578 if (&*CondIt != BI)
Chris Lattner1347e872008-07-13 21:12:01 +00001579 return false;
Chris Lattner6ff645b2009-01-19 23:03:13 +00001580
1581 // Cond is known to be a compare or binary operator. Check to make sure that
1582 // neither operand is a potentially-trapping constant expression.
1583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1584 if (CE->canTrap())
1585 return false;
1586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1587 if (CE->canTrap())
1588 return false;
1589
Chris Lattner1347e872008-07-13 21:12:01 +00001590 // Finally, don't infinitely unroll conditional loops.
1591 BasicBlock *TrueDest = BI->getSuccessor(0);
Manman Renee28e0f2012-06-13 05:43:29 +00001592 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0;
Chris Lattner1347e872008-07-13 21:12:01 +00001593 if (TrueDest == BB || FalseDest == BB)
1594 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001595
Chris Lattner1347e872008-07-13 21:12:01 +00001596 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1597 BasicBlock *PredBlock = *PI;
1598 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001599
Chris Lattner093a4382008-07-13 22:23:11 +00001600 // Check that we have two conditional branches. If there is a PHI node in
1601 // the common successor, verify that the same value flows in from both
1602 // blocks.
Manman Renee28e0f2012-06-13 05:43:29 +00001603 SmallVector<PHINode*, 4> PHIs;
1604 if (PBI == 0 || PBI->isUnconditional() ||
1605 (BI->isConditional() &&
1606 !SafeToMergeTerminators(BI, PBI)) ||
1607 (!BI->isConditional() &&
1608 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner1347e872008-07-13 21:12:01 +00001609 continue;
1610
Chris Lattner3c6e7462011-04-14 02:44:53 +00001611 // Determine if the two branches share a common destination.
1612 Instruction::BinaryOps Opc;
1613 bool InvertPredCond = false;
1614
Manman Renee28e0f2012-06-13 05:43:29 +00001615 if (BI->isConditional()) {
1616 if (PBI->getSuccessor(0) == TrueDest)
1617 Opc = Instruction::Or;
1618 else if (PBI->getSuccessor(1) == FalseDest)
1619 Opc = Instruction::And;
1620 else if (PBI->getSuccessor(0) == FalseDest)
1621 Opc = Instruction::And, InvertPredCond = true;
1622 else if (PBI->getSuccessor(1) == TrueDest)
1623 Opc = Instruction::Or, InvertPredCond = true;
1624 else
1625 continue;
1626 } else {
1627 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
1628 continue;
1629 }
Chris Lattner3c6e7462011-04-14 02:44:53 +00001630
Owen Andersone84178a2010-07-14 19:52:16 +00001631 // Ensure that any values used in the bonus instruction are also used
1632 // by the terminator of the predecessor. This means that those values
1633 // must already have been resolved, so we won't be inhibiting the
1634 // out-of-order core by speculating them earlier.
1635 if (BonusInst) {
1636 // Collect the values used by the bonus inst
1637 SmallPtrSet<Value*, 4> UsedValues;
1638 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1639 OE = BonusInst->op_end(); OI != OE; ++OI) {
Nick Lewycky9d523102011-12-26 20:37:40 +00001640 Value *V = *OI;
Owen Andersone84178a2010-07-14 19:52:16 +00001641 if (!isa<Constant>(V))
1642 UsedValues.insert(V);
1643 }
1644
1645 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1646 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1647
1648 // Walk up to four levels back up the use-def chain of the predecessor's
1649 // terminator to see if all those values were used. The choice of four
1650 // levels is arbitrary, to provide a compile-time-cost bound.
1651 while (!Worklist.empty()) {
1652 std::pair<Value*, unsigned> Pair = Worklist.back();
1653 Worklist.pop_back();
1654
1655 if (Pair.second >= 4) continue;
1656 UsedValues.erase(Pair.first);
1657 if (UsedValues.empty()) break;
1658
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001659 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001660 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1661 OI != OE; ++OI)
1662 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1663 }
1664 }
1665
1666 if (!UsedValues.empty()) return false;
1667 }
Chris Lattner36989092008-07-13 21:20:19 +00001668
David Greene89d6fd32010-01-05 01:26:52 +00001669 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Devang Pateld3a17882011-05-19 20:52:46 +00001670 IRBuilder<> Builder(PBI);
1671
Chris Lattner36989092008-07-13 21:20:19 +00001672 // If we need to invert the condition in the pred block to match, do so now.
1673 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001674 Value *NewCond = PBI->getCondition();
1675
1676 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1677 CmpInst *CI = cast<CmpInst>(NewCond);
1678 CI->setPredicate(CI->getInversePredicate());
1679 } else {
Devang Pateld3a17882011-05-19 20:52:46 +00001680 NewCond = Builder.CreateNot(NewCond,
1681 PBI->getCondition()->getName()+".not");
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001682 }
1683
Chris Lattner1347e872008-07-13 21:12:01 +00001684 PBI->setCondition(NewCond);
Nick Lewyckyc9a1aed2011-12-26 20:54:14 +00001685 PBI->swapSuccessors();
Chris Lattner1347e872008-07-13 21:12:01 +00001686 }
Chris Lattner70087f32008-07-13 21:15:11 +00001687
Owen Andersone84178a2010-07-14 19:52:16 +00001688 // If we have a bonus inst, clone it into the predecessor block.
1689 Instruction *NewBonus = 0;
1690 if (BonusInst) {
1691 NewBonus = BonusInst->clone();
1692 PredBlock->getInstList().insert(PBI, NewBonus);
1693 NewBonus->takeName(BonusInst);
1694 BonusInst->setName(BonusInst->getName()+".old");
1695 }
1696
Chris Lattner36989092008-07-13 21:20:19 +00001697 // Clone Cond into the predecessor basic block, and or/and the
1698 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00001699 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00001700 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00001701 PredBlock->getInstList().insert(PBI, New);
1702 New->takeName(Cond);
1703 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001704
Manman Renee28e0f2012-06-13 05:43:29 +00001705 if (BI->isConditional()) {
1706 Instruction *NewCond =
1707 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Pateld3a17882011-05-19 20:52:46 +00001708 New, "or.cond"));
Manman Renee28e0f2012-06-13 05:43:29 +00001709 PBI->setCondition(NewCond);
1710
1711 if (PBI->getSuccessor(0) == BB) {
1712 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1713 PBI->setSuccessor(0, TrueDest);
1714 }
1715 if (PBI->getSuccessor(1) == BB) {
1716 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1717 PBI->setSuccessor(1, FalseDest);
1718 }
1719 } else {
1720 // Update PHI nodes in the common successors.
1721 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewyckyedb58422012-06-24 10:15:42 +00001722 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Renee28e0f2012-06-13 05:43:29 +00001723 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
1724 assert(PBI_C->getType()->isIntegerTy(1));
1725 Instruction *MergedCond = 0;
1726 if (PBI->getSuccessor(0) == TrueDest) {
1727 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
1728 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
1729 // is false: !PBI_Cond and BI_Value
1730 Instruction *NotCond =
1731 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
1732 "not.cond"));
1733 MergedCond =
1734 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
1735 NotCond, New,
1736 "and.cond"));
1737 if (PBI_C->isOne())
1738 MergedCond =
1739 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
1740 PBI->getCondition(), MergedCond,
1741 "or.cond"));
1742 } else {
1743 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
1744 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
1745 // is false: PBI_Cond and BI_Value
1746 MergedCond =
1747 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
1748 PBI->getCondition(), New,
1749 "and.cond"));
1750 if (PBI_C->isOne()) {
1751 Instruction *NotCond =
1752 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
1753 "not.cond"));
1754 MergedCond =
1755 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
1756 NotCond, MergedCond,
1757 "or.cond"));
1758 }
1759 }
1760 // Update PHI Node.
1761 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
1762 MergedCond);
1763 }
1764 // Change PBI from Conditional to Unconditional.
1765 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
1766 EraseTerminatorInstAndDCECond(PBI);
1767 PBI = New_PBI;
Chris Lattner36989092008-07-13 21:20:19 +00001768 }
Devang Pateld4181942011-04-06 22:37:20 +00001769
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001770 // TODO: If BB is reachable from all paths through PredBlock, then we
1771 // could replace PBI's branch probabilities with BI's.
1772
1773 // Merge probability data into PredBlock's branch.
1774 APInt A, B, C, D;
Manman Renee28e0f2012-06-13 05:43:29 +00001775 if (PBI->isConditional() && BI->isConditional() &&
1776 ExtractBranchMetadata(PBI, C, D) && ExtractBranchMetadata(BI, A, B)) {
Nick Lewycky8da7ddf2011-12-28 06:57:32 +00001777 // Given IR which does:
1778 // bbA:
1779 // br i1 %x, label %bbB, label %bbC
1780 // bbB:
1781 // br i1 %y, label %bbD, label %bbC
1782 // Let's call the probability that we take the edge from %bbA to %bbB
1783 // 'a', from %bbA to %bbC, 'b', from %bbB to %bbD 'c' and from %bbB to
1784 // %bbC probability 'd'.
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001785 //
Nick Lewycky8da7ddf2011-12-28 06:57:32 +00001786 // We transform the IR into:
1787 // bbA:
1788 // br i1 %z, label %bbD, label %bbC
1789 // where the probability of going to %bbD is (a*c) and going to bbC is
1790 // (b+a*d).
1791 //
1792 // Probabilities aren't stored as ratios directly. Using branch weights,
1793 // we get:
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001794 // (a*c)% = A*C, (b+(a*d))% = A*D+B*C+B*D.
1795
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001796 // In the event of overflow, we want to drop the LSB of the input
1797 // probabilities.
1798 unsigned BitsLost;
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001799
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001800 // Ignore overflow result on ProbTrue.
1801 APInt ProbTrue = MultiplyAndLosePrecision(A, C, B, D, BitsLost);
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001802
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001803 APInt Tmp1 = MultiplyAndLosePrecision(B, D, A, C, BitsLost);
1804 if (BitsLost) {
1805 ProbTrue = ProbTrue.lshr(BitsLost*2);
1806 }
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001807
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001808 APInt Tmp2 = MultiplyAndLosePrecision(A, D, C, B, BitsLost);
1809 if (BitsLost) {
1810 ProbTrue = ProbTrue.lshr(BitsLost*2);
1811 Tmp1 = Tmp1.lshr(BitsLost*2);
1812 }
1813
1814 APInt Tmp3 = MultiplyAndLosePrecision(B, C, A, D, BitsLost);
1815 if (BitsLost) {
1816 ProbTrue = ProbTrue.lshr(BitsLost*2);
1817 Tmp1 = Tmp1.lshr(BitsLost*2);
1818 Tmp2 = Tmp2.lshr(BitsLost*2);
1819 }
1820
1821 bool Overflow1 = false, Overflow2 = false;
1822 APInt Tmp4 = Tmp2.uadd_ov(Tmp3, Overflow1);
1823 APInt ProbFalse = Tmp4.uadd_ov(Tmp1, Overflow2);
1824
1825 if (Overflow1 || Overflow2) {
1826 ProbTrue = ProbTrue.lshr(1);
1827 Tmp1 = Tmp1.lshr(1);
1828 Tmp2 = Tmp2.lshr(1);
1829 Tmp3 = Tmp3.lshr(1);
1830 Tmp4 = Tmp2 + Tmp3;
1831 ProbFalse = Tmp4 + Tmp1;
1832 }
1833
1834 // The sum of branch weights must fit in 32-bits.
1835 if (ProbTrue.isNegative() && ProbFalse.isNegative()) {
1836 ProbTrue = ProbTrue.lshr(1);
1837 ProbFalse = ProbFalse.lshr(1);
1838 }
1839
1840 if (ProbTrue != ProbFalse) {
1841 // Normalize the result.
1842 APInt GCD = APIntOps::GreatestCommonDivisor(ProbTrue, ProbFalse);
1843 ProbTrue = ProbTrue.udiv(GCD);
1844 ProbFalse = ProbFalse.udiv(GCD);
1845
Benjamin Kramer937338c2012-05-26 13:59:43 +00001846 MDBuilder MDB(BI->getContext());
1847 MDNode *N = MDB.createBranchWeights(ProbTrue.getZExtValue(),
1848 ProbFalse.getZExtValue());
1849 PBI->setMetadata(LLVMContext::MD_prof, N);
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001850 } else {
1851 PBI->setMetadata(LLVMContext::MD_prof, NULL);
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001852 }
1853 } else {
1854 PBI->setMetadata(LLVMContext::MD_prof, NULL);
1855 }
1856
Chris Lattner3c6e7462011-04-14 02:44:53 +00001857 // Copy any debug value intrinsics into the end of PredBlock.
1858 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1859 if (isa<DbgInfoIntrinsic>(*I))
1860 I->clone()->insertBefore(PBI);
1861
Chris Lattner117f8cf2010-12-14 05:57:30 +00001862 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001863 }
1864 return false;
1865}
1866
Chris Lattner867661a2008-07-13 21:53:26 +00001867/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1868/// predecessor of another block, this function tries to simplify it. We know
1869/// that PBI and BI are both conditional branches, and BI is in one of the
1870/// successor blocks of PBI - PBI branches to BI.
1871static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1872 assert(PBI->isConditional() && BI->isConditional());
1873 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00001874
Chris Lattner867661a2008-07-13 21:53:26 +00001875 // If this block ends with a branch instruction, and if there is a
1876 // predecessor that ends on a branch of the same condition, make
1877 // this conditional branch redundant.
1878 if (PBI->getCondition() == BI->getCondition() &&
1879 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1880 // Okay, the outcome of this conditional branch is statically
1881 // knowable. If this block had a single pred, handle specially.
1882 if (BB->getSinglePredecessor()) {
1883 // Turn this into a branch on constant.
1884 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001885 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1886 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001887 return true; // Nuke the branch on constant.
1888 }
1889
1890 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1891 // in the constant and simplify the block result. Subsequent passes of
1892 // simplifycfg will thread the block.
1893 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foadd8b4fb42011-03-30 11:19:20 +00001894 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson1d0be152009-08-13 21:58:54 +00001895 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad3ecfc862011-03-30 11:28:46 +00001896 std::distance(PB, PE),
Chris Lattner867661a2008-07-13 21:53:26 +00001897 BI->getCondition()->getName() + ".pr",
1898 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001899 // Okay, we're going to insert the PHI node. Since PBI is not the only
1900 // predecessor, compute the PHI'd conditional value for all of the preds.
1901 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001902 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif62539832010-07-12 10:59:23 +00001903 BasicBlock *P = *PI;
1904 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00001905 PBI != BI && PBI->isConditional() &&
1906 PBI->getCondition() == BI->getCondition() &&
1907 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1908 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001909 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00001910 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001911 } else {
Gabor Greif62539832010-07-12 10:59:23 +00001912 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001913 }
Gabor Greif62539832010-07-12 10:59:23 +00001914 }
Chris Lattner867661a2008-07-13 21:53:26 +00001915
1916 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001917 return true;
1918 }
1919 }
1920
1921 // If this is a conditional branch in an empty block, and if any
1922 // predecessors is a conditional branch to one of our destinations,
1923 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001924 BasicBlock::iterator BBI = BB->begin();
1925 // Ignore dbg intrinsics.
1926 while (isa<DbgInfoIntrinsic>(BBI))
1927 ++BBI;
1928 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001929 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001930
1931
1932 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1933 if (CE->canTrap())
1934 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001935
1936 int PBIOp, BIOp;
1937 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1938 PBIOp = BIOp = 0;
1939 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1940 PBIOp = 0, BIOp = 1;
1941 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1942 PBIOp = 1, BIOp = 0;
1943 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1944 PBIOp = BIOp = 1;
1945 else
1946 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001947
Chris Lattnerb8245122008-07-13 22:04:41 +00001948 // Check to make sure that the other destination of this branch
1949 // isn't BB itself. If so, this is an infinite loop that will
1950 // keep getting unwound.
1951 if (PBI->getSuccessor(PBIOp) == BB)
1952 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001953
Chris Lattnerb8245122008-07-13 22:04:41 +00001954 // Do not perform this transformation if it would require
1955 // insertion of a large number of select instructions. For targets
1956 // without predication/cmovs, this is a big pessimization.
1957 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001958
Chris Lattnerb8245122008-07-13 22:04:41 +00001959 unsigned NumPhis = 0;
1960 for (BasicBlock::iterator II = CommonDest->begin();
1961 isa<PHINode>(II); ++II, ++NumPhis)
1962 if (NumPhis > 2) // Disable this xform.
1963 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001964
Chris Lattnerb8245122008-07-13 22:04:41 +00001965 // Finally, if everything is ok, fold the branches to logical ops.
1966 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1967
David Greene89d6fd32010-01-05 01:26:52 +00001968 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00001969 << "AND: " << *BI->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001970
Chris Lattner093a4382008-07-13 22:23:11 +00001971
1972 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1973 // branch in it, where one edge (OtherDest) goes back to itself but the other
1974 // exits. We don't *know* that the program avoids the infinite loop
1975 // (even though that seems likely). If we do this xform naively, we'll end up
1976 // recursively unpeeling the loop. Since we know that (after the xform is
1977 // done) that the block *is* infinite if reached, we just make it an obviously
1978 // infinite loop with no cond branch.
1979 if (OtherDest == BB) {
1980 // Insert it at the end of the function, because it's either code,
1981 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001982 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1983 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00001984 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1985 OtherDest = InfLoopBlock;
1986 }
1987
David Greene89d6fd32010-01-05 01:26:52 +00001988 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Pateld3a17882011-05-19 20:52:46 +00001989
Chris Lattnerb8245122008-07-13 22:04:41 +00001990 // BI may have other predecessors. Because of this, we leave
1991 // it alone, but modify PBI.
1992
1993 // Make sure we get to CommonDest on True&True directions.
1994 Value *PBICond = PBI->getCondition();
Devang Pateld3a17882011-05-19 20:52:46 +00001995 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattnerb8245122008-07-13 22:04:41 +00001996 if (PBIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00001997 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
1998
Chris Lattnerb8245122008-07-13 22:04:41 +00001999 Value *BICond = BI->getCondition();
2000 if (BIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00002001 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2002
Chris Lattnerb8245122008-07-13 22:04:41 +00002003 // Merge the conditions.
Devang Pateld3a17882011-05-19 20:52:46 +00002004 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Chris Lattnerb8245122008-07-13 22:04:41 +00002005
2006 // Modify PBI to branch on the new condition to the new dests.
2007 PBI->setCondition(Cond);
2008 PBI->setSuccessor(0, CommonDest);
2009 PBI->setSuccessor(1, OtherDest);
2010
2011 // OtherDest may have phi nodes. If so, add an entry from PBI's
2012 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00002013 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Chris Lattnerb8245122008-07-13 22:04:41 +00002014
2015 // We know that the CommonDest already had an edge from PBI to
2016 // it. If it has PHIs though, the PHIs may have different
2017 // entries for BB and PBI's BB. If so, insert a select to make
2018 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00002019 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00002020 for (BasicBlock::iterator II = CommonDest->begin();
2021 (PN = dyn_cast<PHINode>(II)); ++II) {
2022 Value *BIV = PN->getIncomingValueForBlock(BB);
2023 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2024 Value *PBIV = PN->getIncomingValue(PBBIdx);
2025 if (BIV != PBIV) {
2026 // Insert a select in PBI to pick the right value.
Devang Pateld3a17882011-05-19 20:52:46 +00002027 Value *NV = cast<SelectInst>
2028 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattnerb8245122008-07-13 22:04:41 +00002029 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00002030 }
2031 }
Chris Lattnerb8245122008-07-13 22:04:41 +00002032
David Greene89d6fd32010-01-05 01:26:52 +00002033 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2034 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00002035
2036 // This basic block is probably dead. We know it has at least
2037 // one fewer predecessor.
2038 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00002039}
2040
Frits van Bommel65fdded2011-01-11 12:52:11 +00002041// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2042// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2043// Takes care of updating the successors and removing the old terminator.
2044// Also makes sure not to introduce new successors by assuming that edges to
2045// non-successor TrueBBs and FalseBBs aren't reachable.
2046static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2047 BasicBlock *TrueBB, BasicBlock *FalseBB){
2048 // Remove any superfluous successor edges from the CFG.
2049 // First, figure out which successors to preserve.
2050 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2051 // successor.
2052 BasicBlock *KeepEdge1 = TrueBB;
2053 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
2054
2055 // Then remove the rest.
2056 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2057 BasicBlock *Succ = OldTerm->getSuccessor(I);
2058 // Make sure only to keep exactly one copy of each edge.
2059 if (Succ == KeepEdge1)
2060 KeepEdge1 = 0;
2061 else if (Succ == KeepEdge2)
2062 KeepEdge2 = 0;
2063 else
2064 Succ->removePredecessor(OldTerm->getParent());
2065 }
2066
Devang Pateld3372b82011-05-18 18:43:31 +00002067 IRBuilder<> Builder(OldTerm);
2068 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2069
Frits van Bommel65fdded2011-01-11 12:52:11 +00002070 // Insert an appropriate new terminator.
2071 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
2072 if (TrueBB == FalseBB)
2073 // We were only looking for one successor, and it was present.
2074 // Create an unconditional branch to it.
Devang Pateld3372b82011-05-18 18:43:31 +00002075 Builder.CreateBr(TrueBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002076 else
2077 // We found both of the successors we were looking for.
2078 // Create a conditional branch sharing the condition of the select.
Devang Pateld3372b82011-05-18 18:43:31 +00002079 Builder.CreateCondBr(Cond, TrueBB, FalseBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002080 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2081 // Neither of the selected blocks were successors, so this
2082 // terminator must be unreachable.
2083 new UnreachableInst(OldTerm->getContext(), OldTerm);
2084 } else {
2085 // One of the selected values was a successor, but the other wasn't.
2086 // Insert an unconditional branch to the one that was found;
2087 // the edge to the one that wasn't must be unreachable.
2088 if (KeepEdge1 == 0)
2089 // Only TrueBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002090 Builder.CreateBr(TrueBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002091 else
2092 // Only FalseBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002093 Builder.CreateBr(FalseBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002094 }
2095
2096 EraseTerminatorInstAndDCECond(OldTerm);
2097 return true;
2098}
2099
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002100// SimplifySwitchOnSelect - Replaces
2101// (switch (select cond, X, Y)) on constant X, Y
2102// with a branch - conditional if X and Y lead to distinct BBs,
2103// unconditional otherwise.
2104static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2105 // Check for constant integer values in the select.
2106 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2107 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2108 if (!TrueVal || !FalseVal)
2109 return false;
2110
2111 // Find the relevant condition and destinations.
2112 Value *Condition = Select->getCondition();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002113 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2114 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002115
2116 // Perform the actual simplification.
2117 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
2118}
2119
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002120// SimplifyIndirectBrOnSelect - Replaces
2121// (indirectbr (select cond, blockaddress(@fn, BlockA),
2122// blockaddress(@fn, BlockB)))
2123// with
2124// (br cond, BlockA, BlockB).
2125static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2126 // Check that both operands of the select are block addresses.
2127 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2128 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2129 if (!TBA || !FBA)
2130 return false;
2131
2132 // Extract the actual blocks.
2133 BasicBlock *TrueBB = TBA->getBasicBlock();
2134 BasicBlock *FalseBB = FBA->getBasicBlock();
2135
Frits van Bommel65fdded2011-01-11 12:52:11 +00002136 // Perform the actual simplification.
2137 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002138}
2139
Chris Lattner61c77442010-12-13 03:18:54 +00002140/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2141/// instruction (a seteq/setne with a constant) as the only instruction in a
2142/// block that ends with an uncond branch. We are looking for a very specific
2143/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2144/// this case, we merge the first two "or's of icmp" into a switch, but then the
2145/// default value goes to an uncond block with a seteq in it, we get something
2146/// like:
2147///
2148/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2149/// DEFAULT:
2150/// %tmp = icmp eq i8 %A, 92
2151/// br label %end
2152/// end:
2153/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2154///
2155/// We prefer to split the edge to 'end' so that there is a true/false entry to
2156/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002157static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
Devang Patela23812c2011-05-18 18:28:48 +00002158 const TargetData *TD,
2159 IRBuilder<> &Builder) {
Chris Lattner61c77442010-12-13 03:18:54 +00002160 BasicBlock *BB = ICI->getParent();
Devang Patela23812c2011-05-18 18:28:48 +00002161
Chris Lattner61c77442010-12-13 03:18:54 +00002162 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2163 // complex.
2164 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2165
2166 Value *V = ICI->getOperand(0);
2167 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2168
2169 // The pattern we're looking for is where our only predecessor is a switch on
2170 // 'V' and this block is the default case for the switch. In this case we can
2171 // fold the compared value into the switch to simplify things.
2172 BasicBlock *Pred = BB->getSinglePredecessor();
2173 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
2174
2175 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2176 if (SI->getCondition() != V)
2177 return false;
2178
2179 // If BB is reachable on a non-default case, then we simply know the value of
2180 // V in this block. Substitute it and constant fold the icmp instruction
2181 // away.
2182 if (SI->getDefaultDest() != BB) {
2183 ConstantInt *VVal = SI->findCaseDest(BB);
2184 assert(VVal && "Should have a unique destination value");
2185 ICI->setOperand(0, VVal);
2186
Chris Lattner302ba6f2010-12-14 06:17:25 +00002187 if (Value *V = SimplifyInstruction(ICI, TD)) {
2188 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00002189 ICI->eraseFromParent();
2190 }
2191 // BB is now empty, so it is likely to simplify away.
2192 return SimplifyCFG(BB) | true;
2193 }
2194
Chris Lattnerabf70672010-12-13 03:43:57 +00002195 // Ok, the block is reachable from the default dest. If the constant we're
2196 // comparing exists in one of the other edges, then we can constant fold ICI
2197 // and zap it.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002198 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattnerabf70672010-12-13 03:43:57 +00002199 Value *V;
2200 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2201 V = ConstantInt::getFalse(BB->getContext());
2202 else
2203 V = ConstantInt::getTrue(BB->getContext());
2204
2205 ICI->replaceAllUsesWith(V);
2206 ICI->eraseFromParent();
2207 // BB is now empty, so it is likely to simplify away.
2208 return SimplifyCFG(BB) | true;
2209 }
2210
Chris Lattner61c77442010-12-13 03:18:54 +00002211 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2212 // the block.
2213 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2214 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
2215 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
2216 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2217 return false;
2218
2219 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2220 // true in the PHI.
2221 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2222 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2223
2224 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2225 std::swap(DefaultCst, NewCst);
2226
2227 // Replace ICI (which is used by the PHI for the default value) with true or
2228 // false depending on if it is EQ or NE.
2229 ICI->replaceAllUsesWith(DefaultCst);
2230 ICI->eraseFromParent();
2231
2232 // Okay, the switch goes to this block on a default value. Add an edge from
2233 // the switch to the merge point on the compared value.
2234 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2235 BB->getParent(), BB);
2236 SI->addCase(Cst, NewBB);
2237
2238 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patela23812c2011-05-18 18:28:48 +00002239 Builder.SetInsertPoint(NewBB);
2240 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2241 Builder.CreateBr(SuccBlock);
Chris Lattner61c77442010-12-13 03:18:54 +00002242 PHIUse->addIncoming(NewCst, NewBB);
2243 return true;
2244}
2245
Chris Lattner97fdb892010-12-13 05:03:41 +00002246/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2247/// Check to see if it is branching on an or/and chain of icmp instructions, and
2248/// fold it into a switch instruction if so.
Devang Patel02dd5412011-05-18 23:18:47 +00002249static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
2250 IRBuilder<> &Builder) {
Chris Lattner97fdb892010-12-13 05:03:41 +00002251 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2252 if (Cond == 0) return false;
2253
2254
2255 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2256 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2257 // 'setne's and'ed together, collect them.
2258 Value *CompVal = 0;
2259 std::vector<ConstantInt*> Values;
2260 bool TrueWhenEqual = true;
2261 Value *ExtraCase = 0;
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002262 unsigned UsedICmps = 0;
Chris Lattner97fdb892010-12-13 05:03:41 +00002263
2264 if (Cond->getOpcode() == Instruction::Or) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002265 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
2266 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002267 } else if (Cond->getOpcode() == Instruction::And) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002268 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
2269 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002270 TrueWhenEqual = false;
2271 }
2272
2273 // If we didn't have a multiply compared value, fail.
2274 if (CompVal == 0) return false;
2275
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002276 // Avoid turning single icmps into a switch.
2277 if (UsedICmps <= 1)
2278 return false;
2279
Chris Lattner97fdb892010-12-13 05:03:41 +00002280 // There might be duplicate constants in the list, which the switch
2281 // instruction can't handle, remove them now.
2282 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2283 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2284
2285 // If Extra was used, we require at least two switch values to do the
2286 // transformation. A switch with one value is just an cond branch.
2287 if (ExtraCase && Values.size() < 2) return false;
2288
2289 // Figure out which block is which destination.
2290 BasicBlock *DefaultBB = BI->getSuccessor(1);
2291 BasicBlock *EdgeBB = BI->getSuccessor(0);
2292 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2293
2294 BasicBlock *BB = BI->getParent();
2295
Chris Lattner302ba6f2010-12-14 06:17:25 +00002296 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00002297 << " cases into SWITCH. BB is:\n" << *BB);
2298
Chris Lattner97fdb892010-12-13 05:03:41 +00002299 // If there are any extra values that couldn't be folded into the switch
2300 // then we evaluate them with an explicit branch first. Split the block
2301 // right before the condbr to handle it.
2302 if (ExtraCase) {
2303 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2304 // Remove the uncond branch added to the old block.
2305 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel02dd5412011-05-18 23:18:47 +00002306 Builder.SetInsertPoint(OldTI);
2307
Chris Lattner117f8cf2010-12-14 05:57:30 +00002308 if (TrueWhenEqual)
Devang Patel02dd5412011-05-18 23:18:47 +00002309 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002310 else
Devang Patel02dd5412011-05-18 23:18:47 +00002311 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002312
Chris Lattner97fdb892010-12-13 05:03:41 +00002313 OldTI->eraseFromParent();
Chris Lattner97bd89e2010-12-13 05:34:18 +00002314
2315 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2316 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00002317 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Chris Lattner302ba6f2010-12-14 06:17:25 +00002318
2319 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2320 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00002321 BB = NewBB;
2322 }
Devang Patel02dd5412011-05-18 23:18:47 +00002323
2324 Builder.SetInsertPoint(BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00002325 // Convert pointer to int before we switch.
2326 if (CompVal->getType()->isPointerTy()) {
2327 assert(TD && "Cannot switch on pointer without TargetData");
Devang Patel02dd5412011-05-18 23:18:47 +00002328 CompVal = Builder.CreatePtrToInt(CompVal,
2329 TD->getIntPtrType(CompVal->getContext()),
2330 "magicptr");
Chris Lattner97fdb892010-12-13 05:03:41 +00002331 }
2332
2333 // Create the new switch instruction now.
Devang Patel02dd5412011-05-18 23:18:47 +00002334 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +00002335
Chris Lattner97fdb892010-12-13 05:03:41 +00002336 // Add all of the 'cases' to the switch instruction.
2337 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2338 New->addCase(Values[i], EdgeBB);
2339
2340 // We added edges from PI to the EdgeBB. As such, if there were any
2341 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2342 // the number of edges added.
2343 for (BasicBlock::iterator BBI = EdgeBB->begin();
2344 isa<PHINode>(BBI); ++BBI) {
2345 PHINode *PN = cast<PHINode>(BBI);
2346 Value *InVal = PN->getIncomingValueForBlock(BB);
2347 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2348 PN->addIncoming(InVal, BB);
2349 }
2350
2351 // Erase the old branch instruction.
2352 EraseTerminatorInstAndDCECond(BI);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002353
Chris Lattner302ba6f2010-12-14 06:17:25 +00002354 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00002355 return true;
2356}
2357
Duncan Sandsad99ef82011-09-05 12:57:57 +00002358bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2359 // If this is a trivial landing pad that just continues unwinding the caught
2360 // exception then zap the landing pad, turning its invokes into calls.
2361 BasicBlock *BB = RI->getParent();
2362 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2363 if (RI->getValue() != LPInst)
2364 // Not a landing pad, or the resume is not unwinding the exception that
2365 // caused control to branch here.
2366 return false;
2367
2368 // Check that there are no other instructions except for debug intrinsics.
2369 BasicBlock::iterator I = LPInst, E = RI;
2370 while (++I != E)
2371 if (!isa<DbgInfoIntrinsic>(I))
2372 return false;
2373
2374 // Turn all invokes that unwind here into calls and delete the basic block.
2375 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2376 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2377 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2378 // Insert a call instruction before the invoke.
2379 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2380 Call->takeName(II);
2381 Call->setCallingConv(II->getCallingConv());
2382 Call->setAttributes(II->getAttributes());
2383 Call->setDebugLoc(II->getDebugLoc());
2384
2385 // Anything that used the value produced by the invoke instruction now uses
2386 // the value produced by the call instruction. Note that we do this even
2387 // for void functions and calls with no uses so that the callgraph edge is
2388 // updated.
2389 II->replaceAllUsesWith(Call);
2390 BB->removePredecessor(II->getParent());
2391
2392 // Insert a branch to the normal destination right before the invoke.
2393 BranchInst::Create(II->getNormalDest(), II);
2394
2395 // Finally, delete the invoke instruction!
2396 II->eraseFromParent();
2397 }
2398
2399 // The landingpad is now unreachable. Zap it.
2400 BB->eraseFromParent();
2401 return true;
2402}
2403
Devang Patel176ec402011-05-18 21:33:11 +00002404bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00002405 BasicBlock *BB = RI->getParent();
2406 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2407
2408 // Find predecessors that end with branches.
2409 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2410 SmallVector<BranchInst*, 8> CondBranchPreds;
2411 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2412 BasicBlock *P = *PI;
2413 TerminatorInst *PTI = P->getTerminator();
2414 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2415 if (BI->isUnconditional())
2416 UncondBranchPreds.push_back(P);
2417 else
2418 CondBranchPreds.push_back(BI);
2419 }
2420 }
2421
2422 // If we found some, do the transformation!
Evan Chengc3f507f2011-01-29 04:46:23 +00002423 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner3d512132010-12-13 06:25:44 +00002424 while (!UncondBranchPreds.empty()) {
2425 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2426 DEBUG(dbgs() << "FOLDING: " << *BB
2427 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengc3f507f2011-01-29 04:46:23 +00002428 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner3d512132010-12-13 06:25:44 +00002429 }
2430
2431 // If we eliminated all predecessors of the block, delete the block now.
2432 if (pred_begin(BB) == pred_end(BB))
2433 // We know there are no successors, so just nuke the block.
2434 BB->eraseFromParent();
2435
2436 return true;
2437 }
2438
2439 // Check out all of the conditional branches going to this return
2440 // instruction. If any of them just select between returns, change the
2441 // branch itself into a select/return pair.
2442 while (!CondBranchPreds.empty()) {
2443 BranchInst *BI = CondBranchPreds.pop_back_val();
2444
2445 // Check to see if the non-BB successor is also a return block.
2446 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2447 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Patel176ec402011-05-18 21:33:11 +00002448 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002449 return true;
2450 }
2451 return false;
2452}
2453
Chris Lattner3d512132010-12-13 06:25:44 +00002454bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2455 BasicBlock *BB = UI->getParent();
2456
2457 bool Changed = false;
2458
2459 // If there are any instructions immediately before the unreachable that can
2460 // be removed, do so.
2461 while (UI != BB->begin()) {
2462 BasicBlock::iterator BBI = UI;
2463 --BBI;
Eli Friedman81763882011-08-15 23:59:28 +00002464 // Do not delete instructions that can have side effects which might cause
2465 // the unreachable to not be reachable; specifically, calls and volatile
2466 // operations may have this effect.
Chris Lattner3d512132010-12-13 06:25:44 +00002467 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman81763882011-08-15 23:59:28 +00002468
2469 if (BBI->mayHaveSideEffects()) {
2470 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2471 if (SI->isVolatile())
2472 break;
2473 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2474 if (LI->isVolatile())
2475 break;
2476 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2477 if (RMWI->isVolatile())
2478 break;
2479 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2480 if (CXI->isVolatile())
2481 break;
2482 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2483 !isa<LandingPadInst>(BBI)) {
Chris Lattner3d512132010-12-13 06:25:44 +00002484 break;
Eli Friedman81763882011-08-15 23:59:28 +00002485 }
Bill Wendling23b49ba2011-08-16 20:41:17 +00002486 // Note that deleting LandingPad's here is in fact okay, although it
2487 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2488 // all the predecessors of this block will be the unwind edges of Invokes,
2489 // and we can therefore guarantee this block will be erased.
Eli Friedman81763882011-08-15 23:59:28 +00002490 }
2491
Eli Friedman2adc5b62011-03-09 00:48:33 +00002492 // Delete this instruction (any uses are guaranteed to be dead)
2493 if (!BBI->use_empty())
2494 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattner302ba6f2010-12-14 06:17:25 +00002495 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002496 Changed = true;
2497 }
2498
2499 // If the unreachable instruction is the first in the block, take a gander
2500 // at all of the predecessors of this instruction, and simplify them.
2501 if (&BB->front() != UI) return Changed;
2502
2503 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2504 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2505 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel1aa89a22011-05-19 00:09:21 +00002506 IRBuilder<> Builder(TI);
Chris Lattner3d512132010-12-13 06:25:44 +00002507 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2508 if (BI->isUnconditional()) {
2509 if (BI->getSuccessor(0) == BB) {
2510 new UnreachableInst(TI->getContext(), TI);
2511 TI->eraseFromParent();
2512 Changed = true;
2513 }
2514 } else {
2515 if (BI->getSuccessor(0) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002516 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner3d512132010-12-13 06:25:44 +00002517 EraseTerminatorInstAndDCECond(BI);
2518 } else if (BI->getSuccessor(1) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002519 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner3d512132010-12-13 06:25:44 +00002520 EraseTerminatorInstAndDCECond(BI);
2521 Changed = true;
2522 }
2523 }
2524 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002525 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002526 i != e; ++i)
2527 if (i.getCaseSuccessor() == BB) {
Chris Lattner3d512132010-12-13 06:25:44 +00002528 BB->removePredecessor(SI->getParent());
2529 SI->removeCase(i);
2530 --i; --e;
2531 Changed = true;
2532 }
2533 // If the default value is unreachable, figure out the most popular
2534 // destination and make it the default.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002535 if (SI->getDefaultDest() == BB) {
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002536 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002537 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002538 i != e; ++i) {
Nick Lewycky9d523102011-12-26 20:37:40 +00002539 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002540 Popularity[i.getCaseSuccessor()];
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002541 if (entry.first == 0) {
2542 entry.first = 1;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002543 entry.second = i.getCaseIndex();
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002544 } else {
2545 entry.first++;
2546 }
2547 }
2548
Chris Lattner3d512132010-12-13 06:25:44 +00002549 // Find the most popular block.
2550 unsigned MaxPop = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002551 unsigned MaxIndex = 0;
Chris Lattner3d512132010-12-13 06:25:44 +00002552 BasicBlock *MaxBlock = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002553 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner3d512132010-12-13 06:25:44 +00002554 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002555 if (I->second.first > MaxPop ||
2556 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
2557 MaxPop = I->second.first;
2558 MaxIndex = I->second.second;
Chris Lattner3d512132010-12-13 06:25:44 +00002559 MaxBlock = I->first;
2560 }
2561 }
2562 if (MaxBlock) {
2563 // Make this the new default, allowing us to delete any explicit
2564 // edges to it.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002565 SI->setDefaultDest(MaxBlock);
Chris Lattner3d512132010-12-13 06:25:44 +00002566 Changed = true;
2567
2568 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2569 // it.
2570 if (isa<PHINode>(MaxBlock->begin()))
2571 for (unsigned i = 0; i != MaxPop-1; ++i)
2572 MaxBlock->removePredecessor(SI->getParent());
2573
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002574 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002575 i != e; ++i)
2576 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner3d512132010-12-13 06:25:44 +00002577 SI->removeCase(i);
2578 --i; --e;
2579 }
2580 }
2581 }
2582 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2583 if (II->getUnwindDest() == BB) {
2584 // Convert the invoke to a call instruction. This would be a good
2585 // place to note that the call does not throw though.
Devang Patel1aa89a22011-05-19 00:09:21 +00002586 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner3d512132010-12-13 06:25:44 +00002587 II->removeFromParent(); // Take out of symbol table
2588
2589 // Insert the call now...
2590 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel1aa89a22011-05-19 00:09:21 +00002591 Builder.SetInsertPoint(BI);
2592 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foada3efbb12011-07-15 08:37:34 +00002593 Args, II->getName());
Chris Lattner3d512132010-12-13 06:25:44 +00002594 CI->setCallingConv(II->getCallingConv());
2595 CI->setAttributes(II->getAttributes());
2596 // If the invoke produced a value, the call does now instead.
2597 II->replaceAllUsesWith(CI);
2598 delete II;
2599 Changed = true;
2600 }
2601 }
2602 }
2603
2604 // If this block is now dead, remove it.
2605 if (pred_begin(BB) == pred_end(BB) &&
2606 BB != &BB->getParent()->getEntryBlock()) {
2607 // We know there are no successors, so just nuke the block.
2608 BB->eraseFromParent();
2609 return true;
2610 }
2611
2612 return Changed;
2613}
2614
Benjamin Kramer56442df2011-02-02 15:56:22 +00002615/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
2616/// integer range comparison into a sub, an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00002617static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002618 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramer56442df2011-02-02 15:56:22 +00002619
Benjamin Kramer042b27f2011-02-03 22:51:41 +00002620 // Make sure all cases point to the same destination and gather the values.
2621 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002622 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002623 Cases.push_back(I.getCaseValue());
2624 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002625 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002626 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer042b27f2011-02-03 22:51:41 +00002627 return false;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002628 Cases.push_back(I.getCaseValue());
Benjamin Kramer042b27f2011-02-03 22:51:41 +00002629 }
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002630 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer042b27f2011-02-03 22:51:41 +00002631
2632 // Sort the case values, then check if they form a range we can transform.
2633 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
2634 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
2635 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
2636 return false;
2637 }
2638
2639 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002640 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramer56442df2011-02-02 15:56:22 +00002641
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002642 Value *Sub = SI->getCondition();
2643 if (!Offset->isNullValue())
Devang Patel1f5812b2011-05-19 00:13:33 +00002644 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
2645 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002646 Builder.CreateCondBr(
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002647 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramer56442df2011-02-02 15:56:22 +00002648
2649 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002650 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramer56442df2011-02-02 15:56:22 +00002651 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002652 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramer56442df2011-02-02 15:56:22 +00002653 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
2654 }
2655 SI->eraseFromParent();
2656
2657 return true;
2658}
Chris Lattner3d512132010-12-13 06:25:44 +00002659
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002660/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
2661/// and use it to remove dead cases.
2662static bool EliminateDeadSwitchCases(SwitchInst *SI) {
2663 Value *Cond = SI->getCondition();
2664 unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
2665 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00002666 ComputeMaskedBits(Cond, KnownZero, KnownOne);
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002667
2668 // Gather dead cases.
2669 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002670 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002671 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
2672 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
2673 DeadCases.push_back(I.getCaseValue());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002674 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002675 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002676 }
2677 }
2678
2679 // Remove dead cases from the switch.
2680 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002681 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002682 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002683 "Case was not found. Probably mistake in DeadCases forming.");
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002684 // Prune unused values from PHI nodes.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002685 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002686 SI->removeCase(Case);
2687 }
2688
2689 return !DeadCases.empty();
2690}
2691
Hans Wennborg448da512011-06-18 10:28:47 +00002692/// FindPHIForConditionForwarding - If BB would be eligible for simplification
2693/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
2694/// by an unconditional branch), look at the phi node for BB in the successor
2695/// block and see if the incoming value is equal to CaseValue. If so, return
2696/// the phi node, and set PhiIndex to BB's index in the phi node.
2697static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
2698 BasicBlock *BB,
2699 int *PhiIndex) {
2700 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
2701 return NULL; // BB must be empty to be a candidate for simplification.
2702 if (!BB->getSinglePredecessor())
2703 return NULL; // BB must be dominated by the switch.
2704
2705 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
2706 if (!Branch || !Branch->isUnconditional())
2707 return NULL; // Terminator must be unconditional branch.
2708
2709 BasicBlock *Succ = Branch->getSuccessor(0);
2710
2711 BasicBlock::iterator I = Succ->begin();
2712 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
2713 int Idx = PHI->getBasicBlockIndex(BB);
2714 assert(Idx >= 0 && "PHI has no entry for predecessor?");
2715
2716 Value *InValue = PHI->getIncomingValue(Idx);
2717 if (InValue != CaseValue) continue;
2718
2719 *PhiIndex = Idx;
2720 return PHI;
2721 }
2722
2723 return NULL;
2724}
2725
2726/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
2727/// instruction to a phi node dominated by the switch, if that would mean that
2728/// some of the destination blocks of the switch can be folded away.
2729/// Returns true if a change is made.
2730static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
2731 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
2732 ForwardingNodesMap ForwardingNodes;
2733
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002734 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002735 ConstantInt *CaseValue = I.getCaseValue();
2736 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg448da512011-06-18 10:28:47 +00002737
2738 int PhiIndex;
2739 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
2740 &PhiIndex);
2741 if (!PHI) continue;
2742
2743 ForwardingNodes[PHI].push_back(PhiIndex);
2744 }
2745
2746 bool Changed = false;
2747
2748 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
2749 E = ForwardingNodes.end(); I != E; ++I) {
2750 PHINode *Phi = I->first;
2751 SmallVector<int,4> &Indexes = I->second;
2752
2753 if (Indexes.size() < 2) continue;
2754
2755 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
2756 Phi->setIncomingValue(Indexes[I], SI->getCondition());
2757 Changed = true;
2758 }
2759
2760 return Changed;
2761}
2762
Devang Patel007349d2011-05-18 20:35:38 +00002763bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00002764 // If this switch is too complex to want to look at, ignore it.
2765 if (!isValueEqualityComparison(SI))
2766 return false;
2767
2768 BasicBlock *BB = SI->getParent();
2769
2770 // If we only have one predecessor, and if it is a branch on this value,
2771 // see if that predecessor totally determines the outcome of this switch.
2772 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patel007349d2011-05-18 20:35:38 +00002773 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Chris Lattner021c9d32010-12-13 06:36:51 +00002774 return SimplifyCFG(BB) | true;
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002775
2776 Value *Cond = SI->getCondition();
2777 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
2778 if (SimplifySwitchOnSelect(SI, Select))
2779 return SimplifyCFG(BB) | true;
2780
Chris Lattner3d512132010-12-13 06:25:44 +00002781 // If the block only contains the switch, see if we can fold the block
2782 // away into any preds.
2783 BasicBlock::iterator BBI = BB->begin();
2784 // Ignore dbg intrinsics.
2785 while (isa<DbgInfoIntrinsic>(BBI))
2786 ++BBI;
2787 if (SI == &*BBI)
Devang Patelb55d9242011-05-18 20:53:17 +00002788 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Chris Lattner021c9d32010-12-13 06:36:51 +00002789 return SimplifyCFG(BB) | true;
Benjamin Kramer56442df2011-02-02 15:56:22 +00002790
2791 // Try to transform the switch into an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00002792 if (TurnSwitchRangeIntoICmp(SI, Builder))
Benjamin Kramer56442df2011-02-02 15:56:22 +00002793 return SimplifyCFG(BB) | true;
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00002794
2795 // Remove unreachable cases.
2796 if (EliminateDeadSwitchCases(SI))
2797 return SimplifyCFG(BB) | true;
2798
Hans Wennborg448da512011-06-18 10:28:47 +00002799 if (ForwardSwitchConditionToPHI(SI))
2800 return SimplifyCFG(BB) | true;
2801
Chris Lattner3d512132010-12-13 06:25:44 +00002802 return false;
2803}
2804
2805bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2806 BasicBlock *BB = IBI->getParent();
2807 bool Changed = false;
2808
2809 // Eliminate redundant destinations.
2810 SmallPtrSet<Value *, 8> Succs;
2811 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2812 BasicBlock *Dest = IBI->getDestination(i);
2813 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2814 Dest->removePredecessor(BB);
2815 IBI->removeDestination(i);
2816 --i; --e;
2817 Changed = true;
2818 }
2819 }
2820
2821 if (IBI->getNumDestinations() == 0) {
2822 // If the indirectbr has no successors, change it to unreachable.
2823 new UnreachableInst(IBI->getContext(), IBI);
2824 EraseTerminatorInstAndDCECond(IBI);
2825 return true;
2826 }
2827
2828 if (IBI->getNumDestinations() == 1) {
2829 // If the indirectbr has one successor, change it to a direct branch.
2830 BranchInst::Create(IBI->getDestination(0), IBI);
2831 EraseTerminatorInstAndDCECond(IBI);
2832 return true;
2833 }
2834
2835 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2836 if (SimplifyIndirectBrOnSelect(IBI, SI))
2837 return SimplifyCFG(BB) | true;
2838 }
2839 return Changed;
2840}
2841
Devang Patela23812c2011-05-18 18:28:48 +00002842bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner3d512132010-12-13 06:25:44 +00002843 BasicBlock *BB = BI->getParent();
2844
2845 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindola77a2c372011-06-30 20:14:24 +00002846 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
Chris Lattner3d512132010-12-13 06:25:44 +00002847 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2848 TryToSimplifyUncondBranchFromEmptyBlock(BB))
2849 return true;
2850
2851 // If the only instruction in the block is a seteq/setne comparison
2852 // against a constant, try to simplify the block.
2853 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2854 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2855 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2856 ;
Nick Lewycky9d523102011-12-26 20:37:40 +00002857 if (I->isTerminator() &&
2858 TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002859 return true;
2860 }
2861
Manman Renee28e0f2012-06-13 05:43:29 +00002862 // If this basic block is ONLY a compare and a branch, and if a predecessor
2863 // branches to us and our successor, fold the comparison into the
2864 // predecessor and use logical operations to update the incoming value
2865 // for PHI nodes in common successor.
2866 if (FoldBranchToCommonDest(BI))
2867 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002868 return false;
2869}
2870
2871
Devang Patel007349d2011-05-18 20:35:38 +00002872bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00002873 BasicBlock *BB = BI->getParent();
2874
2875 // Conditional branch
2876 if (isValueEqualityComparison(BI)) {
2877 // If we only have one predecessor, and if it is a branch on this value,
2878 // see if that predecessor totally determines the outcome of this
2879 // switch.
2880 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patel007349d2011-05-18 20:35:38 +00002881 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002882 return SimplifyCFG(BB) | true;
2883
2884 // This block must be empty, except for the setcond inst, if it exists.
2885 // Ignore dbg intrinsics.
2886 BasicBlock::iterator I = BB->begin();
2887 // Ignore dbg intrinsics.
2888 while (isa<DbgInfoIntrinsic>(I))
2889 ++I;
2890 if (&*I == BI) {
Devang Patelb55d9242011-05-18 20:53:17 +00002891 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002892 return SimplifyCFG(BB) | true;
2893 } else if (&*I == cast<Instruction>(BI->getCondition())){
2894 ++I;
2895 // Ignore dbg intrinsics.
2896 while (isa<DbgInfoIntrinsic>(I))
2897 ++I;
Devang Patelb55d9242011-05-18 20:53:17 +00002898 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002899 return SimplifyCFG(BB) | true;
2900 }
2901 }
2902
2903 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Devang Patel02dd5412011-05-18 23:18:47 +00002904 if (SimplifyBranchOnICmpChain(BI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002905 return true;
2906
Dan Gohman3b205172012-01-05 23:58:56 +00002907 // If this basic block is ONLY a compare and a branch, and if a predecessor
2908 // branches to us and one of our successors, fold the comparison into the
2909 // predecessor and use logical operations to pick the right destination.
2910 if (FoldBranchToCommonDest(BI))
2911 return SimplifyCFG(BB) | true;
2912
Chris Lattner3d512132010-12-13 06:25:44 +00002913 // We have a conditional branch to two blocks that are only reachable
2914 // from BI. We know that the condbr dominates the two blocks, so see if
2915 // there is any identical code in the "then" and "else" blocks. If so, we
2916 // can hoist it up to the branching block.
2917 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2918 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
Rafael Espindola216dde92011-05-19 02:26:30 +00002919 if (HoistThenElseCodeToIf(BI))
Chris Lattner3d512132010-12-13 06:25:44 +00002920 return SimplifyCFG(BB) | true;
2921 } else {
2922 // If Successor #1 has multiple preds, we may be able to conditionally
2923 // execute Successor #0 if it branches to successor #1.
2924 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2925 if (Succ0TI->getNumSuccessors() == 1 &&
2926 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Rafael Espindola216dde92011-05-19 02:26:30 +00002927 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
Chris Lattner3d512132010-12-13 06:25:44 +00002928 return SimplifyCFG(BB) | true;
2929 }
2930 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2931 // If Successor #0 has multiple preds, we may be able to conditionally
2932 // execute Successor #1 if it branches to successor #0.
2933 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2934 if (Succ1TI->getNumSuccessors() == 1 &&
2935 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Rafael Espindola216dde92011-05-19 02:26:30 +00002936 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
Chris Lattner3d512132010-12-13 06:25:44 +00002937 return SimplifyCFG(BB) | true;
2938 }
2939
2940 // If this is a branch on a phi node in the current block, thread control
2941 // through this block if any PHI node entries are constants.
2942 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2943 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00002944 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002945 return SimplifyCFG(BB) | true;
2946
Chris Lattner3d512132010-12-13 06:25:44 +00002947 // Scan predecessor blocks for conditional branches.
2948 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2949 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2950 if (PBI != BI && PBI->isConditional())
2951 if (SimplifyCondBranchToCondBranch(PBI, BI))
2952 return SimplifyCFG(BB) | true;
2953
2954 return false;
2955}
2956
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002957/// Check if passing a value to an instruction will cause undefined behavior.
2958static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
2959 Constant *C = dyn_cast<Constant>(V);
2960 if (!C)
2961 return false;
2962
Benjamin Kramer9bb54882011-08-26 02:25:55 +00002963 if (!I->hasOneUse()) // Only look at single-use instructions, for compile time
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002964 return false;
2965
2966 if (C->isNullValue()) {
2967 Instruction *Use = I->use_back();
2968
2969 // Now make sure that there are no instructions in between that can alter
2970 // control flow (eg. calls)
2971 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer9bb54882011-08-26 02:25:55 +00002972 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002973 return false;
2974
2975 // Look through GEPs. A load from a GEP derived from NULL is still undefined
2976 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
2977 if (GEP->getPointerOperand() == I)
2978 return passingValueIsAlwaysUndefined(V, GEP);
2979
2980 // Look through bitcasts.
2981 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
2982 return passingValueIsAlwaysUndefined(V, BC);
2983
Benjamin Kramer9bb54882011-08-26 02:25:55 +00002984 // Load from null is undefined.
2985 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
2986 return LI->getPointerAddressSpace() == 0;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002987
Benjamin Kramer9bb54882011-08-26 02:25:55 +00002988 // Store to null is undefined.
2989 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
2990 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002991 }
2992 return false;
2993}
2994
2995/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewycky9d523102011-12-26 20:37:40 +00002996/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramer98d6d232011-08-26 01:22:29 +00002997static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
2998 for (BasicBlock::iterator i = BB->begin();
2999 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
3000 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
3001 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
3002 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
3003 IRBuilder<> Builder(T);
3004 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
3005 BB->removePredecessor(PHI->getIncomingBlock(i));
3006 // Turn uncoditional branches into unreachables and remove the dead
3007 // destination from conditional branches.
3008 if (BI->isUnconditional())
3009 Builder.CreateUnreachable();
3010 else
3011 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
3012 BI->getSuccessor(0));
3013 BI->eraseFromParent();
3014 return true;
3015 }
3016 // TODO: SwitchInst.
3017 }
3018
3019 return false;
3020}
3021
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003022bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00003023 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003024
Chris Lattner302ba6f2010-12-14 06:17:25 +00003025 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003026 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003027
Dan Gohmane2c6d132010-08-14 00:29:42 +00003028 // Remove basic blocks that have no predecessors (except the entry block)...
3029 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00003030 if ((pred_begin(BB) == pred_end(BB) &&
3031 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00003032 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00003033 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00003034 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00003035 return true;
3036 }
3037
Chris Lattner694e37f2003-08-17 19:41:53 +00003038 // Check to see if we can constant propagate this terminator instruction
3039 // away...
Frits van Bommel5649ba72011-05-22 16:24:18 +00003040 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner694e37f2003-08-17 19:41:53 +00003041
Dan Gohman2c635662009-10-30 22:39:04 +00003042 // Check for and eliminate duplicate PHI nodes in this block.
3043 Changed |= EliminateDuplicatePHINodes(BB);
3044
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003045 // Check for and remove branches that will always cause undefined behavior.
3046 Changed |= removeUndefIntroducingPredecessor(BB);
3047
Chris Lattnerddb97a22010-12-13 05:10:48 +00003048 // Merge basic blocks into their predecessor if there is only one distinct
3049 // pred, and if there is only one distinct successor of the predecessor, and
3050 // if there are no PHI nodes.
3051 //
3052 if (MergeBlockIntoPredecessor(BB))
3053 return true;
3054
Devang Patel3e410c62011-05-18 18:01:27 +00003055 IRBuilder<> Builder(BB);
3056
Dan Gohman882d87d2008-03-11 21:53:06 +00003057 // If there is a trivial two-entry PHI node in this basic block, and we can
3058 // eliminate it, do so now.
3059 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
3060 if (PN->getNumIncomingValues() == 2)
Devang Pateld3a17882011-05-19 20:52:46 +00003061 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00003062
Devang Patel007349d2011-05-18 20:35:38 +00003063 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner3d512132010-12-13 06:25:44 +00003064 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00003065 if (BI->isUnconditional()) {
Devang Patela23812c2011-05-18 18:28:48 +00003066 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003067 } else {
Devang Patel007349d2011-05-18 20:35:38 +00003068 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003069 }
3070 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel176ec402011-05-18 21:33:11 +00003071 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingaa5abe82012-02-06 21:16:41 +00003072 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
3073 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003074 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patel007349d2011-05-18 20:35:38 +00003075 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003076 } else if (UnreachableInst *UI =
3077 dyn_cast<UnreachableInst>(BB->getTerminator())) {
3078 if (SimplifyUnreachable(UI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003079 } else if (IndirectBrInst *IBI =
3080 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
3081 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00003082 }
3083
Chris Lattner694e37f2003-08-17 19:41:53 +00003084 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003085}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003086
3087/// SimplifyCFG - This function is used to do simplification of a CFG. For
3088/// example, it adjusts branches to branches to eliminate the extra hop, it
3089/// eliminates unreachable basic blocks, and does other "peephole" optimization
3090/// of the CFG. It returns true if a modification was made.
3091///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003092bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
3093 return SimplifyCFGOpt(TD).run(BB);
3094}