blob: 427ac4ed143a1c7c56a32e2a54cf567aa5880bd0 [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"
Chandler Carruth0baa4802012-07-15 23:26:50 +000023#include "llvm/MDBuilder.h"
Nick Lewycky06cc66f2011-12-27 04:31:52 +000024#include "llvm/Metadata.h"
Hans Wennborg486270a2012-09-06 09:43:28 +000025#include "llvm/Module.h"
Dan Gohman3b205172012-01-05 23:58:56 +000026#include "llvm/Operator.h"
Chris Lattner0d560082004-02-24 05:38:11 +000027#include "llvm/Type.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000034#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramer10fcfb52011-05-14 15:57:25 +000035#include "llvm/Analysis/ValueTracking.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000036#include "llvm/Support/CFG.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000037#include "llvm/Support/CommandLine.h"
Chris Lattnere27db742010-12-17 06:20:15 +000038#include "llvm/Support/ConstantRange.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000039#include "llvm/Support/Debug.h"
Devang Pateld3a17882011-05-19 20:52:46 +000040#include "llvm/Support/NoFolder.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000041#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000042#include "llvm/DataLayout.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000044#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000045#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000046#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Peter Collingbourne57808b32011-04-29 18:47:38 +000049static cl::opt<unsigned>
50PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
51 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
52
Evan Chengc3f507f2011-01-29 04:46:23 +000053static cl::opt<bool>
54DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
55 cl::desc("Duplicate return instructions into unconditional branches"));
56
Manman Ren554da1a2012-09-20 22:37:36 +000057static cl::opt<bool>
58SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
59 cl::desc("Sink common instructions down to the end block"));
60
Hans Wennborgd72271c2012-09-26 09:44:49 +000061STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Hans Wennborg50b7d702012-09-26 14:01:53 +000062STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Manman Ren554da1a2012-09-20 22:37:36 +000063STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborg50b7d702012-09-26 14:01:53 +000064STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng502a4f52008-06-12 21:15:59 +000065
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000066namespace {
Eric Christopherc723eb12012-07-02 23:22:21 +000067 /// ValueEqualityComparisonCase - Represents a case of a switch.
68 struct ValueEqualityComparisonCase {
69 ConstantInt *Value;
70 BasicBlock *Dest;
71
72 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
73 : Value(Value), Dest(Dest) {}
74
75 bool operator<(ValueEqualityComparisonCase RHS) const {
76 // Comparing pointers is ok as we only rely on the order for uniquing.
77 return Value < RHS.Value;
78 }
Benjamin Kramer8e13ded2012-10-14 11:15:42 +000079
80 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherc723eb12012-07-02 23:22:21 +000081 };
82
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000083class SimplifyCFGOpt {
Micah Villmow3574eca2012-10-08 16:38:25 +000084 const DataLayout *const TD;
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000085
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000086 Value *isValueEqualityComparison(TerminatorInst *TI);
87 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherc723eb12012-07-02 23:22:21 +000088 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000089 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +000090 BasicBlock *Pred,
91 IRBuilder<> &Builder);
Devang Patelb55d9242011-05-18 20:53:17 +000092 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
93 IRBuilder<> &Builder);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000094
Devang Patel176ec402011-05-18 21:33:11 +000095 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingaa5abe82012-02-06 21:16:41 +000096 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000097 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patel007349d2011-05-18 20:35:38 +000098 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner3d512132010-12-13 06:25:44 +000099 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patela23812c2011-05-18 18:28:48 +0000100 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patel007349d2011-05-18 20:35:38 +0000101 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner3d512132010-12-13 06:25:44 +0000102
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000103public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000104 explicit SimplifyCFGOpt(const DataLayout *td) : TD(td) {}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000105 bool run(BasicBlock *BB);
106};
107}
108
Chris Lattner2bdcb562005-08-03 00:19:45 +0000109/// SafeToMergeTerminators - Return true if it is safe to merge these two
110/// terminator instructions together.
111///
112static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
113 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trick6b014382012-08-29 21:46:36 +0000114
Chris Lattner2bdcb562005-08-03 00:19:45 +0000115 // It is not safe to merge these two switch instructions if they have a common
116 // successor, and if that successor has a PHI node, and if *that* PHI node has
117 // conflicting incoming values from the two switch blocks.
118 BasicBlock *SI1BB = SI1->getParent();
119 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +0000120 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trick6b014382012-08-29 21:46:36 +0000121
Chris Lattner2bdcb562005-08-03 00:19:45 +0000122 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
123 if (SI1Succs.count(*I))
124 for (BasicBlock::iterator BBI = (*I)->begin();
125 isa<PHINode>(BBI); ++BBI) {
126 PHINode *PN = cast<PHINode>(BBI);
127 if (PN->getIncomingValueForBlock(SI1BB) !=
128 PN->getIncomingValueForBlock(SI2BB))
129 return false;
130 }
Andrew Trick6b014382012-08-29 21:46:36 +0000131
Chris Lattner2bdcb562005-08-03 00:19:45 +0000132 return true;
133}
134
Manman Renee28e0f2012-06-13 05:43:29 +0000135/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
136/// to merge these two terminator instructions together, where SI1 is an
137/// unconditional branch. PhiNodes will store all PHI nodes in common
138/// successors.
139///
140static bool isProfitableToFoldUnconditional(BranchInst *SI1,
141 BranchInst *SI2,
Nick Lewyckyedb58422012-06-24 10:15:42 +0000142 Instruction *Cond,
Manman Renee28e0f2012-06-13 05:43:29 +0000143 SmallVectorImpl<PHINode*> &PhiNodes) {
144 if (SI1 == SI2) return false; // Can't merge with self!
145 assert(SI1->isUnconditional() && SI2->isConditional());
146
147 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trick6b014382012-08-29 21:46:36 +0000148 // common successors:
Manman Renee28e0f2012-06-13 05:43:29 +0000149 // 1> We have a constant incoming value for the conditional branch;
150 // 2> We have "Cond" as the incoming value for the unconditional branch;
151 // 3> SI2->getCondition() and Cond have same operands.
152 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
153 if (!Ci2) return false;
154 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
155 Cond->getOperand(1) == Ci2->getOperand(1)) &&
156 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
157 Cond->getOperand(1) == Ci2->getOperand(0)))
158 return false;
159
160 BasicBlock *SI1BB = SI1->getParent();
161 BasicBlock *SI2BB = SI2->getParent();
162 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
163 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
164 if (SI1Succs.count(*I))
165 for (BasicBlock::iterator BBI = (*I)->begin();
166 isa<PHINode>(BBI); ++BBI) {
167 PHINode *PN = cast<PHINode>(BBI);
168 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewyckyedb58422012-06-24 10:15:42 +0000169 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Renee28e0f2012-06-13 05:43:29 +0000170 return false;
171 PhiNodes.push_back(PN);
172 }
173 return true;
174}
175
Chris Lattner2bdcb562005-08-03 00:19:45 +0000176/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
177/// now be entries in it from the 'NewPred' block. The values that will be
178/// flowing into the PHI nodes will be the same as those coming in from
179/// ExistPred, an existing predecessor of Succ.
180static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
181 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +0000182 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trick6b014382012-08-29 21:46:36 +0000183
Chris Lattner093a4382008-07-13 22:23:11 +0000184 PHINode *PN;
185 for (BasicBlock::iterator I = Succ->begin();
186 (PN = dyn_cast<PHINode>(I)); ++I)
187 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000188}
189
Chris Lattner7e663482005-08-03 00:11:16 +0000190
Chris Lattner73c50a62010-12-14 07:00:00 +0000191/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
192/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000193/// to an "if condition". If so, return the boolean condition that determines
194/// which entry into BB will be taken. Also, return by references the block
195/// that will be entered from if the condition is true, and the block that will
196/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000197///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000198/// This does no checking to see if the true/false blocks have large or unsavory
199/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000200static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
201 BasicBlock *&IfFalse) {
202 PHINode *SomePHI = cast<PHINode>(BB->begin());
203 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000204 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000205 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
206 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000207
208 // We can only handle branches. Other control flow will be lowered to
209 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000210 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
211 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
212 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000213 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000214
215 // Eliminate code duplication by ensuring that Pred1Br is conditional if
216 // either are.
217 if (Pred2Br->isConditional()) {
218 // If both branches are conditional, we don't have an "if statement". In
219 // reality, we could transform this case, but since the condition will be
220 // required anyway, we stand no chance of eliminating it, so the xform is
221 // probably not profitable.
222 if (Pred1Br->isConditional())
223 return 0;
224
225 std::swap(Pred1, Pred2);
226 std::swap(Pred1Br, Pred2Br);
227 }
228
229 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000230 // The only thing we have to watch out for here is to make sure that Pred2
231 // doesn't have incoming edges from other blocks. If it does, the condition
232 // doesn't dominate BB.
233 if (Pred2->getSinglePredecessor() == 0)
234 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000235
Chris Lattner723c66d2004-02-11 03:36:04 +0000236 // If we found a conditional branch predecessor, make sure that it branches
237 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
238 if (Pred1Br->getSuccessor(0) == BB &&
239 Pred1Br->getSuccessor(1) == Pred2) {
240 IfTrue = Pred1;
241 IfFalse = Pred2;
242 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
243 Pred1Br->getSuccessor(1) == BB) {
244 IfTrue = Pred2;
245 IfFalse = Pred1;
246 } else {
247 // We know that one arm of the conditional goes to BB, so the other must
248 // go somewhere unrelated, and this must not be an "if statement".
249 return 0;
250 }
251
Chris Lattner723c66d2004-02-11 03:36:04 +0000252 return Pred1Br->getCondition();
253 }
254
255 // Ok, if we got here, both predecessors end with an unconditional branch to
256 // BB. Don't panic! If both blocks only have a single (identical)
257 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000258 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
259 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000260 return 0;
261
262 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000263 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
264 if (BI == 0) return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000265
Chris Lattner995ba1b2010-12-14 07:15:21 +0000266 assert(BI->isConditional() && "Two successors but not conditional?");
267 if (BI->getSuccessor(0) == Pred1) {
268 IfTrue = Pred1;
269 IfFalse = Pred2;
270 } else {
271 IfTrue = Pred2;
272 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000273 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000274 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000275}
276
Dan Gohman3b205172012-01-05 23:58:56 +0000277/// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
278/// given instruction, which is assumed to be safe to speculate. 1 means
279/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
280static unsigned ComputeSpeculationCost(const User *I) {
281 assert(isSafeToSpeculativelyExecute(I) &&
282 "Instruction is not safe to speculatively execute!");
283 switch (Operator::getOpcode(I)) {
284 default:
285 // In doubt, be conservative.
286 return UINT_MAX;
287 case Instruction::GetElementPtr:
288 // GEPs are cheap if all indices are constant.
289 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
290 return UINT_MAX;
291 return 1;
292 case Instruction::Load:
293 case Instruction::Add:
294 case Instruction::Sub:
295 case Instruction::And:
296 case Instruction::Or:
297 case Instruction::Xor:
298 case Instruction::Shl:
299 case Instruction::LShr:
300 case Instruction::AShr:
301 case Instruction::ICmp:
302 case Instruction::Trunc:
303 case Instruction::ZExt:
304 case Instruction::SExt:
305 return 1; // These are all cheap.
306
307 case Instruction::Call:
308 case Instruction::Select:
309 return 2;
310 }
311}
312
Bill Wendling5049fa62009-01-19 23:43:56 +0000313/// DominatesMergePoint - If we have a merge point of an "if condition" as
314/// accepted above, return true if the specified value dominates the block. We
315/// don't handle the true generality of domination here, just a special case
316/// which works well enough for us.
317///
318/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournef15907f2011-04-29 18:47:31 +0000319/// see if V (which must be an instruction) and its recursive operands
320/// that do not dominate BB have a combined cost lower than CostRemaining and
321/// are non-trapping. If both are true, the instruction is inserted into the
322/// set and true is returned.
323///
324/// The cost for most non-trapping instructions is defined as 1 except for
325/// Select whose cost is 2.
326///
327/// After this function returns, CostRemaining is decreased by the cost of
328/// V plus its non-dominating operands. If that cost is greater than
329/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner9c078662004-10-14 05:13:36 +0000330static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Peter Collingbournef15907f2011-04-29 18:47:31 +0000331 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
332 unsigned &CostRemaining) {
Chris Lattner570751c2004-04-09 22:50:22 +0000333 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000334 if (!I) {
335 // Non-instructions all dominate instructions, but not all constantexprs
336 // can be executed unconditionally.
337 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
338 if (C->canTrap())
339 return false;
340 return true;
341 }
Chris Lattner570751c2004-04-09 22:50:22 +0000342 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000343
Chris Lattnerda895d62005-02-27 06:18:25 +0000344 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000345 // the bottom of this block.
346 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000347
Chris Lattner570751c2004-04-09 22:50:22 +0000348 // If this instruction is defined in a block that contains an unconditional
349 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000350 // statement". If not, it definitely dominates the region.
351 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
352 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
353 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000354
Chris Lattner44da7ca2010-12-14 07:41:39 +0000355 // If we aren't allowing aggressive promotion anymore, then don't consider
356 // instructions in the 'if region'.
357 if (AggressiveInsts == 0) return false;
Andrew Trick6b014382012-08-29 21:46:36 +0000358
Peter Collingbournef15907f2011-04-29 18:47:31 +0000359 // If we have seen this instruction before, don't count it again.
360 if (AggressiveInsts->count(I)) return true;
361
Chris Lattner44da7ca2010-12-14 07:41:39 +0000362 // Okay, it looks like the instruction IS in the "condition". Check to
363 // see if it's a cheap instruction to unconditionally compute, and if it
364 // only uses stuff defined outside of the condition. If so, hoist it out.
Dan Gohmanf0426602011-12-14 23:49:11 +0000365 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000366 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000367
Dan Gohman3b205172012-01-05 23:58:56 +0000368 unsigned Cost = ComputeSpeculationCost(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000369
Peter Collingbournef15907f2011-04-29 18:47:31 +0000370 if (Cost > CostRemaining)
371 return false;
372
373 CostRemaining -= Cost;
374
375 // Okay, we can only really hoist these out if their operands do
376 // not take us over the cost threshold.
Chris Lattner44da7ca2010-12-14 07:41:39 +0000377 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Peter Collingbournef15907f2011-04-29 18:47:31 +0000378 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
Chris Lattner44da7ca2010-12-14 07:41:39 +0000379 return false;
380 // Okay, it's safe to do this! Remember this instruction.
381 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000382 return true;
383}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000384
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000385/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
386/// and PointerNullValue. Return NULL if value is not a constant int.
Micah Villmow3574eca2012-10-08 16:38:25 +0000387static ConstantInt *GetConstantInt(Value *V, const DataLayout *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000388 // Normal constant int.
389 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000390 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000391 return CI;
392
393 // This is some kind of pointer constant. Turn it into a pointer-sized
394 // ConstantInt if possible.
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000395 IntegerType *PtrTy = TD->getIntPtrType(V->getType());
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000396
397 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
398 if (isa<ConstantPointerNull>(V))
399 return ConstantInt::get(PtrTy, 0);
400
401 // IntToPtr const int.
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
403 if (CE->getOpcode() == Instruction::IntToPtr)
404 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
405 // The constant is very likely to have the right type already.
406 if (CI->getType() == PtrTy)
407 return CI;
408 else
409 return cast<ConstantInt>
410 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
411 }
412 return 0;
413}
414
Chris Lattner0aa749b2010-12-13 04:26:26 +0000415/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
416/// collection of icmp eq/ne instructions that compare a value against a
417/// constant, return the value being compared, and stick the constant into the
418/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000419static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000420GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Micah Villmow3574eca2012-10-08 16:38:25 +0000421 const DataLayout *TD, bool isEQ, unsigned &UsedICmps) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000422 Instruction *I = dyn_cast<Instruction>(V);
423 if (I == 0) return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000424
Chris Lattner7312a222010-12-13 04:50:38 +0000425 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000426 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Chris Lattnere27db742010-12-17 06:20:15 +0000427 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
428 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000429 UsedICmps++;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000430 Vals.push_back(C);
431 return I->getOperand(0);
432 }
Andrew Trick6b014382012-08-29 21:46:36 +0000433
Chris Lattnere27db742010-12-17 06:20:15 +0000434 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
435 // the set.
436 ConstantRange Span =
Chris Lattnera37029c2010-12-18 20:22:49 +0000437 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Andrew Trick6b014382012-08-29 21:46:36 +0000438
Chris Lattnere27db742010-12-17 06:20:15 +0000439 // If this is an and/!= check then we want to optimize "x ugt 2" into
440 // x != 0 && x != 1.
441 if (!isEQ)
442 Span = Span.inverse();
Andrew Trick6b014382012-08-29 21:46:36 +0000443
Chris Lattnere27db742010-12-17 06:20:15 +0000444 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewyckyf460bf82012-01-19 18:19:42 +0000445 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Chris Lattnere27db742010-12-17 06:20:15 +0000446 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000447
Chris Lattnere27db742010-12-17 06:20:15 +0000448 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
449 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000450 UsedICmps++;
Chris Lattnere27db742010-12-17 06:20:15 +0000451 return I->getOperand(0);
452 }
Chris Lattner662269d2010-12-13 04:18:32 +0000453 return 0;
454 }
Andrew Trick6b014382012-08-29 21:46:36 +0000455
Chris Lattner7312a222010-12-13 04:50:38 +0000456 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000457 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000458 return 0;
Andrew Trick6b014382012-08-29 21:46:36 +0000459
Chris Lattner7312a222010-12-13 04:50:38 +0000460 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000461 unsigned UsedICmpsBeforeLHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000462 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000463 isEQ, UsedICmps)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000464 unsigned NumVals = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000465 unsigned UsedICmpsBeforeRHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000466 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000467 isEQ, UsedICmps)) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000468 if (LHS == RHS)
469 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000470 Vals.resize(NumVals);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000471 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000472 }
Chris Lattner7312a222010-12-13 04:50:38 +0000473
474 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
475 // set it and return success.
476 if (Extra == 0 || Extra == I->getOperand(1)) {
477 Extra = I->getOperand(1);
478 return LHS;
479 }
Andrew Trick6b014382012-08-29 21:46:36 +0000480
Chris Lattner7312a222010-12-13 04:50:38 +0000481 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000482 UsedICmps = UsedICmpsBeforeLHS;
Chris Lattner7312a222010-12-13 04:50:38 +0000483 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000484 }
Andrew Trick6b014382012-08-29 21:46:36 +0000485
Chris Lattner7312a222010-12-13 04:50:38 +0000486 // If the LHS can't be folded in, but Extra is available and RHS can, try to
487 // use LHS as Extra.
488 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000489 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000490 Extra = I->getOperand(0);
491 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000492 isEQ, UsedICmps))
Chris Lattner7312a222010-12-13 04:50:38 +0000493 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000494 assert(Vals.size() == NumValsBeforeLHS);
495 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000496 }
Andrew Trick6b014382012-08-29 21:46:36 +0000497
Chris Lattner0d560082004-02-24 05:38:11 +0000498 return 0;
499}
Nick Lewycky9d523102011-12-26 20:37:40 +0000500
Eli Friedman080efb82008-12-16 20:54:32 +0000501static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Nick Lewycky9d523102011-12-26 20:37:40 +0000502 Instruction *Cond = 0;
Eli Friedman080efb82008-12-16 20:54:32 +0000503 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
504 Cond = dyn_cast<Instruction>(SI->getCondition());
505 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
506 if (BI->isConditional())
507 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000508 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
509 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000510 }
511
512 TI->eraseFromParent();
513 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
514}
515
Chris Lattner9fd49552008-11-27 23:25:44 +0000516/// isValueEqualityComparison - Return true if the specified terminator checks
517/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000518Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
519 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000520 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
521 // Do not permit merging of large switch instructions into their
522 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000523 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
524 pred_end(SI->getParent())) <= 128)
525 CV = SI->getCondition();
526 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000527 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
529 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
530 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000531 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000532 CV = ICI->getOperand(0);
533
534 // Unwrap any lossless ptrtoint cast.
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000535 if (TD && CV) {
536 PtrToIntInst *PTII = NULL;
537 if ((PTII = dyn_cast<PtrToIntInst>(CV)) &&
538 CV->getType() == TD->getIntPtrType(CV->getContext(),
539 PTII->getPointerAddressSpace()))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000540 CV = PTII->getOperand(0);
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000541 }
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000542 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000543}
544
Bill Wendling5049fa62009-01-19 23:43:56 +0000545/// GetValueEqualityComparisonCases - Given a value comparison instruction,
546/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000547BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000548GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherc723eb12012-07-02 23:22:21 +0000549 std::vector<ValueEqualityComparisonCase>
550 &Cases) {
Chris Lattner542f1492004-02-28 21:28:10 +0000551 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherc723eb12012-07-02 23:22:21 +0000552 Cases.reserve(SI->getNumCases());
553 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
554 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
555 i.getCaseSuccessor()));
Chris Lattner542f1492004-02-28 21:28:10 +0000556 return SI->getDefaultDest();
557 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000558
Chris Lattner542f1492004-02-28 21:28:10 +0000559 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000560 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherc723eb12012-07-02 23:22:21 +0000561 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
562 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
563 TD),
564 Succ));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000566}
567
Eric Christopherc723eb12012-07-02 23:22:21 +0000568
569/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
570/// in the list that match the specified block.
571static void EliminateBlockCases(BasicBlock *BB,
572 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramer8e13ded2012-10-14 11:15:42 +0000573 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherc723eb12012-07-02 23:22:21 +0000574}
575
576/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
577/// well.
578static bool
579ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
580 std::vector<ValueEqualityComparisonCase > &C2) {
581 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
582
583 // Make V1 be smaller than V2.
584 if (V1->size() > V2->size())
585 std::swap(V1, V2);
586
587 if (V1->size() == 0) return false;
588 if (V1->size() == 1) {
589 // Just scan V2.
590 ConstantInt *TheVal = (*V1)[0].Value;
591 for (unsigned i = 0, e = V2->size(); i != e; ++i)
592 if (TheVal == (*V2)[i].Value)
593 return true;
594 }
595
596 // Otherwise, just sort both lists and compare element by element.
597 array_pod_sort(V1->begin(), V1->end());
598 array_pod_sort(V2->begin(), V2->end());
599 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
600 while (i1 != e1 && i2 != e2) {
601 if ((*V1)[i1].Value == (*V2)[i2].Value)
602 return true;
603 if ((*V1)[i1].Value < (*V2)[i2].Value)
604 ++i1;
605 else
606 ++i2;
607 }
608 return false;
609}
610
Bill Wendling5049fa62009-01-19 23:43:56 +0000611/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
612/// terminator instruction and its block is known to only have a single
613/// predecessor block, check to see if that predecessor is also a value
614/// comparison with the same value, and if that comparison determines the
615/// outcome of this comparison. If so, simplify TI. This does a very limited
616/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000617bool SimplifyCFGOpt::
618SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patel007349d2011-05-18 20:35:38 +0000619 BasicBlock *Pred,
620 IRBuilder<> &Builder) {
Chris Lattner623369a2005-02-24 06:17:52 +0000621 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
622 if (!PredVal) return false; // Not a value comparison in predecessor.
623
624 Value *ThisVal = isValueEqualityComparison(TI);
625 assert(ThisVal && "This isn't a value comparison!!");
626 if (ThisVal != PredVal) return false; // Different predicates.
627
Andrew Trickb1b97832012-08-29 21:46:38 +0000628 // TODO: Preserve branch weight metadata, similarly to how
629 // FoldValueComparisonIntoPredecessors preserves it.
630
Chris Lattner623369a2005-02-24 06:17:52 +0000631 // Find out information about when control will move from Pred to TI's block.
Eric Christopherc723eb12012-07-02 23:22:21 +0000632 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000633 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
634 PredCases);
Eric Christopherc723eb12012-07-02 23:22:21 +0000635 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000636
Chris Lattner623369a2005-02-24 06:17:52 +0000637 // Find information about how control leaves this block.
Eric Christopherc723eb12012-07-02 23:22:21 +0000638 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000639 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherc723eb12012-07-02 23:22:21 +0000640 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner623369a2005-02-24 06:17:52 +0000641
642 // If TI's block is the default block from Pred's comparison, potentially
643 // simplify TI based on this knowledge.
644 if (PredDef == TI->getParent()) {
645 // If we are here, we know that the value is none of those cases listed in
646 // PredCases. If there are any cases in ThisCases that are in PredCases, we
647 // can simplify TI.
Eric Christopherc723eb12012-07-02 23:22:21 +0000648 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000649 return false;
Andrew Trick6b014382012-08-29 21:46:36 +0000650
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000651 if (isa<BranchInst>(TI)) {
652 // Okay, one of the successors of this condbr is dead. Convert it to a
653 // uncond br.
654 assert(ThisCases.size() == 1 && "Branch can only have one case!");
655 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000656 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000657 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000658
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000659 // Remove PHI node entries for the dead edge.
Eric Christopherc723eb12012-07-02 23:22:21 +0000660 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000661
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000662 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
663 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000664
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000665 EraseTerminatorInstAndDCECond(TI);
666 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000667 }
Andrew Trick6b014382012-08-29 21:46:36 +0000668
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000669 SwitchInst *SI = cast<SwitchInst>(TI);
670 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherc723eb12012-07-02 23:22:21 +0000671 SmallPtrSet<Constant*, 16> DeadCases;
672 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
673 DeadCases.insert(PredCases[i].Value);
Chris Lattner623369a2005-02-24 06:17:52 +0000674
David Greene89d6fd32010-01-05 01:26:52 +0000675 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000676 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000677
Manman Renad289072012-09-14 21:53:06 +0000678 // Collect branch weights into a vector.
679 SmallVector<uint32_t, 8> Weights;
680 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
681 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
682 if (HasWeight)
683 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
684 ++MD_i) {
685 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
686 assert(CI);
687 Weights.push_back(CI->getValue().getZExtValue());
688 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000689 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
690 --i;
691 if (DeadCases.count(i.getCaseValue())) {
Manman Renad289072012-09-14 21:53:06 +0000692 if (HasWeight) {
693 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
694 Weights.pop_back();
695 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000696 i.getCaseSuccessor()->removePredecessor(TI->getParent());
697 SI->removeCase(i);
698 }
699 }
Manman Rend61d1eb2012-10-11 22:28:34 +0000700 if (HasWeight && Weights.size() >= 2)
Manman Renad289072012-09-14 21:53:06 +0000701 SI->setMetadata(LLVMContext::MD_prof,
702 MDBuilder(SI->getParent()->getContext()).
703 createBranchWeights(Weights));
Eric Christopherc723eb12012-07-02 23:22:21 +0000704
705 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000706 return true;
707 }
Andrew Trick6b014382012-08-29 21:46:36 +0000708
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000709 // Otherwise, TI's block must correspond to some matched value. Find out
710 // which value (or set of values) this is.
Eric Christopherc723eb12012-07-02 23:22:21 +0000711 ConstantInt *TIV = 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000712 BasicBlock *TIBB = TI->getParent();
Eric Christopherc723eb12012-07-02 23:22:21 +0000713 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
714 if (PredCases[i].Dest == TIBB) {
715 if (TIV != 0)
716 return false; // Cannot handle multiple values coming to this block.
717 TIV = PredCases[i].Value;
718 }
719 assert(TIV && "No edge from pred to succ?");
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000720
721 // Okay, we found the one constant that our value can be if we get into TI's
722 // BB. Find out which successor will unconditionally be branched to.
Eric Christopherc723eb12012-07-02 23:22:21 +0000723 BasicBlock *TheRealDest = 0;
724 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
725 if (ThisCases[i].Value == TIV) {
726 TheRealDest = ThisCases[i].Dest;
727 break;
728 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000729
730 // If not handled by any explicit cases, it is handled by the default case.
731 if (TheRealDest == 0) TheRealDest = ThisDef;
732
733 // Remove PHI node entries for dead edges.
734 BasicBlock *CheckEdge = TheRealDest;
735 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
736 if (*SI != CheckEdge)
737 (*SI)->removePredecessor(TIBB);
738 else
739 CheckEdge = 0;
740
741 // Insert the new branch.
Devang Patel007349d2011-05-18 20:35:38 +0000742 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000743 (void) NI;
744
745 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
746 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
747
748 EraseTerminatorInstAndDCECond(TI);
749 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000750}
751
Dale Johannesenc81f5442009-03-12 21:01:11 +0000752namespace {
753 /// ConstantIntOrdering - This class implements a stable ordering of constant
754 /// integers that does not depend on their address. This is important for
755 /// applications that sort ConstantInt's to ensure uniqueness.
756 struct ConstantIntOrdering {
757 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
758 return LHS->getValue().ult(RHS->getValue());
759 }
760 };
761}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000762
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000763static int ConstantIntSortPredicate(const void *P1, const void *P2) {
Roman Divacky59324292012-09-05 22:26:57 +0000764 const ConstantInt *LHS = *(const ConstantInt*const*)P1;
765 const ConstantInt *RHS = *(const ConstantInt*const*)P2;
Chris Lattnerba3c8152010-12-15 04:52:41 +0000766 if (LHS->getValue().ult(RHS->getValue()))
767 return 1;
768 if (LHS->getValue() == RHS->getValue())
769 return 0;
770 return -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000771}
772
Andrew Trickb1b97832012-08-29 21:46:38 +0000773static inline bool HasBranchWeights(const Instruction* I) {
774 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
775 if (ProfMD && ProfMD->getOperand(0))
776 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
777 return MDS->getString().equals("branch_weights");
778
779 return false;
780}
781
Manman Ren020aba02012-09-11 17:43:35 +0000782/// Get Weights of a given TerminatorInst, the default weight is at the front
783/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
784/// metadata.
785static void GetBranchWeights(TerminatorInst *TI,
786 SmallVectorImpl<uint64_t> &Weights) {
787 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
788 assert(MD);
789 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
790 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(i));
Andrew Trickb1b97832012-08-29 21:46:38 +0000791 assert(CI);
Manman Ren020aba02012-09-11 17:43:35 +0000792 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trickb1b97832012-08-29 21:46:38 +0000793 }
794
Manman Ren020aba02012-09-11 17:43:35 +0000795 // If TI is a conditional eq, the default case is the false case,
796 // and the corresponding branch-weight data is at index 2. We swap the
797 // default weight to be the first entry.
798 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
799 assert(Weights.size() == 2);
800 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
801 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
802 std::swap(Weights.front(), Weights.back());
Andrew Trickb1b97832012-08-29 21:46:38 +0000803 }
804}
805
806/// Sees if any of the weights are too big for a uint32_t, and halves all the
807/// weights if any are.
808static void FitWeights(MutableArrayRef<uint64_t> Weights) {
809 bool Halve = false;
810 for (unsigned i = 0; i < Weights.size(); ++i)
811 if (Weights[i] > UINT_MAX) {
812 Halve = true;
813 break;
814 }
815
816 if (! Halve)
817 return;
818
819 for (unsigned i = 0; i < Weights.size(); ++i)
820 Weights[i] /= 2;
821}
822
Bill Wendling5049fa62009-01-19 23:43:56 +0000823/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
824/// equality comparison instruction (either a switch or a branch on "X == c").
825/// See if any of the predecessors of the terminator block are value comparisons
826/// on the same value. If so, and if safe to do so, fold them together.
Devang Patelb55d9242011-05-18 20:53:17 +0000827bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
828 IRBuilder<> &Builder) {
Chris Lattner542f1492004-02-28 21:28:10 +0000829 BasicBlock *BB = TI->getParent();
830 Value *CV = isValueEqualityComparison(TI); // CondVal
831 assert(CV && "Not a comparison?");
832 bool Changed = false;
833
Chris Lattner82442432008-02-18 07:42:56 +0000834 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000835 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000836 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000837
Chris Lattner542f1492004-02-28 21:28:10 +0000838 // See if the predecessor is a comparison with the same value.
839 TerminatorInst *PTI = Pred->getTerminator();
840 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
841
842 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
843 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherc723eb12012-07-02 23:22:21 +0000844 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000845 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
846
Eric Christopherc723eb12012-07-02 23:22:21 +0000847 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner542f1492004-02-28 21:28:10 +0000848 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
849
850 // Based on whether the default edge from PTI goes to BB or not, fill in
851 // PredCases and PredDefault with the new switch cases we would like to
852 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000853 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000854
Andrew Trickb1b97832012-08-29 21:46:38 +0000855 // Update the branch weight metadata along the way
856 SmallVector<uint64_t, 8> Weights;
Andrew Trickb1b97832012-08-29 21:46:38 +0000857 bool PredHasWeights = HasBranchWeights(PTI);
858 bool SuccHasWeights = HasBranchWeights(TI);
859
Manman Ren796d9452012-09-14 19:05:19 +0000860 if (PredHasWeights) {
Manman Ren020aba02012-09-11 17:43:35 +0000861 GetBranchWeights(PTI, Weights);
Manman Ren796d9452012-09-14 19:05:19 +0000862 // branch-weight metadata is inconsistant here.
863 if (Weights.size() != 1 + PredCases.size())
864 PredHasWeights = SuccHasWeights = false;
865 } else if (SuccHasWeights)
Andrew Trickb1b97832012-08-29 21:46:38 +0000866 // If there are no predecessor weights but there are successor weights,
867 // populate Weights with 1, which will later be scaled to the sum of
868 // successor's weights
869 Weights.assign(1 + PredCases.size(), 1);
Andrew Trickb1b97832012-08-29 21:46:38 +0000870
Manman Ren020aba02012-09-11 17:43:35 +0000871 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren796d9452012-09-14 19:05:19 +0000872 if (SuccHasWeights) {
Manman Ren020aba02012-09-11 17:43:35 +0000873 GetBranchWeights(TI, SuccWeights);
Manman Ren796d9452012-09-14 19:05:19 +0000874 // branch-weight metadata is inconsistant here.
875 if (SuccWeights.size() != 1 + BBCases.size())
876 PredHasWeights = SuccHasWeights = false;
877 } else if (PredHasWeights)
Manman Ren020aba02012-09-11 17:43:35 +0000878 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trickb1b97832012-08-29 21:46:38 +0000879
Chris Lattner542f1492004-02-28 21:28:10 +0000880 if (PredDefault == BB) {
881 // If this is the default destination from PTI, only the edges in TI
882 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherc723eb12012-07-02 23:22:21 +0000883 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
884 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
885 if (PredCases[i].Dest != BB)
886 PTIHandled.insert(PredCases[i].Value);
887 else {
888 // The default destination is BB, we don't need explicit targets.
889 std::swap(PredCases[i], PredCases.back());
Andrew Trickb1b97832012-08-29 21:46:38 +0000890
Manman Ren020aba02012-09-11 17:43:35 +0000891 if (PredHasWeights || SuccHasWeights) {
892 // Increase weight for the default case.
893 Weights[0] += Weights[i+1];
Andrew Trickb1b97832012-08-29 21:46:38 +0000894 std::swap(Weights[i+1], Weights.back());
895 Weights.pop_back();
896 }
897
Eric Christopherc723eb12012-07-02 23:22:21 +0000898 PredCases.pop_back();
899 --i; --e;
900 }
Chris Lattner542f1492004-02-28 21:28:10 +0000901
Eric Christopherc723eb12012-07-02 23:22:21 +0000902 // Reconstruct the new switch statement we will be building.
Chris Lattner542f1492004-02-28 21:28:10 +0000903 if (PredDefault != BBDefault) {
904 PredDefault->removePredecessor(Pred);
905 PredDefault = BBDefault;
906 NewSuccessors.push_back(BBDefault);
907 }
Andrew Trickb1b97832012-08-29 21:46:38 +0000908
Manman Ren020aba02012-09-11 17:43:35 +0000909 unsigned CasesFromPred = Weights.size();
910 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherc723eb12012-07-02 23:22:21 +0000911 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
912 if (!PTIHandled.count(BBCases[i].Value) &&
913 BBCases[i].Dest != BBDefault) {
914 PredCases.push_back(BBCases[i]);
915 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren020aba02012-09-11 17:43:35 +0000916 if (SuccHasWeights || PredHasWeights) {
917 // The default weight is at index 0, so weight for the ith case
918 // should be at index i+1. Scale the cases from successor by
919 // PredDefaultWeight (Weights[0]).
920 Weights.push_back(Weights[0] * SuccWeights[i+1]);
921 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trickb1b97832012-08-29 21:46:38 +0000922 }
Eric Christopherc723eb12012-07-02 23:22:21 +0000923 }
Chris Lattner542f1492004-02-28 21:28:10 +0000924
Manman Ren020aba02012-09-11 17:43:35 +0000925 if (SuccHasWeights || PredHasWeights) {
926 ValidTotalSuccWeight += SuccWeights[0];
927 // Scale the cases from predecessor by ValidTotalSuccWeight.
928 for (unsigned i = 1; i < CasesFromPred; ++i)
929 Weights[i] *= ValidTotalSuccWeight;
930 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
931 Weights[0] *= SuccWeights[0];
932 }
Chris Lattner542f1492004-02-28 21:28:10 +0000933 } else {
934 // If this is not the default destination from PSI, only the edges
935 // in SI that occur in PSI with a destination of BB will be
936 // activated.
Eric Christopherc723eb12012-07-02 23:22:21 +0000937 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rena8a2b992012-09-14 17:29:56 +0000938 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherc723eb12012-07-02 23:22:21 +0000939 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
940 if (PredCases[i].Dest == BB) {
941 PTIHandled.insert(PredCases[i].Value);
Manman Rena8a2b992012-09-14 17:29:56 +0000942
943 if (PredHasWeights || SuccHasWeights) {
944 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
945 std::swap(Weights[i+1], Weights.back());
946 Weights.pop_back();
947 }
948
Eric Christopherc723eb12012-07-02 23:22:21 +0000949 std::swap(PredCases[i], PredCases.back());
950 PredCases.pop_back();
951 --i; --e;
952 }
Chris Lattner542f1492004-02-28 21:28:10 +0000953
954 // Okay, now we know which constants were sent to BB from the
955 // predecessor. Figure out where they will all go now.
Eric Christopherc723eb12012-07-02 23:22:21 +0000956 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
957 if (PTIHandled.count(BBCases[i].Value)) {
958 // If this is one we are capable of getting...
Manman Rena8a2b992012-09-14 17:29:56 +0000959 if (PredHasWeights || SuccHasWeights)
960 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherc723eb12012-07-02 23:22:21 +0000961 PredCases.push_back(BBCases[i]);
962 NewSuccessors.push_back(BBCases[i].Dest);
963 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
964 }
965
Chris Lattner542f1492004-02-28 21:28:10 +0000966 // If there are any constants vectored to BB that TI doesn't handle,
967 // they must go to the default destination of TI.
Andrew Trick6b014382012-08-29 21:46:36 +0000968 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherc723eb12012-07-02 23:22:21 +0000969 PTIHandled.begin(),
970 E = PTIHandled.end(); I != E; ++I) {
Manman Rena8a2b992012-09-14 17:29:56 +0000971 if (PredHasWeights || SuccHasWeights)
972 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherc723eb12012-07-02 23:22:21 +0000973 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattner542f1492004-02-28 21:28:10 +0000974 NewSuccessors.push_back(BBDefault);
Eric Christopherc723eb12012-07-02 23:22:21 +0000975 }
Chris Lattner542f1492004-02-28 21:28:10 +0000976 }
977
978 // Okay, at this point, we know which new successor Pred will get. Make
979 // sure we update the number of entries in the PHI nodes for these
980 // successors.
981 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
982 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
983
Devang Patelb55d9242011-05-18 20:53:17 +0000984 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000985 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000986 if (CV->getType()->isPointerTy()) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000987 assert(TD && "Cannot switch on pointer without DataLayout");
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000988 CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getType()),
Devang Patelb55d9242011-05-18 20:53:17 +0000989 "magicptr");
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000990 }
991
Chris Lattner542f1492004-02-28 21:28:10 +0000992 // Now that the successors are updated, create the new Switch instruction.
Devang Patelb55d9242011-05-18 20:53:17 +0000993 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
994 PredCases.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +0000995 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherc723eb12012-07-02 23:22:21 +0000996 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
997 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner13b2f762005-01-01 16:02:12 +0000998
Andrew Trickb1b97832012-08-29 21:46:38 +0000999 if (PredHasWeights || SuccHasWeights) {
1000 // Halve the weights if any of them cannot fit in an uint32_t
1001 FitWeights(Weights);
1002
1003 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1004
1005 NewSI->setMetadata(LLVMContext::MD_prof,
1006 MDBuilder(BB->getContext()).
1007 createBranchWeights(MDWeights));
1008 }
1009
Eli Friedman080efb82008-12-16 20:54:32 +00001010 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +00001011
Chris Lattner542f1492004-02-28 21:28:10 +00001012 // Okay, last check. If BB is still a successor of PSI, then we must
1013 // have an infinite loop case. If so, add an infinitely looping block
1014 // to handle the case to preserve the behavior of the code.
1015 BasicBlock *InfLoopBlock = 0;
1016 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1017 if (NewSI->getSuccessor(i) == BB) {
1018 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +00001019 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +00001020 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001021 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1022 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +00001023 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +00001024 }
1025 NewSI->setSuccessor(i, InfLoopBlock);
1026 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001027
Chris Lattner542f1492004-02-28 21:28:10 +00001028 Changed = true;
1029 }
1030 }
1031 return Changed;
1032}
1033
Dale Johannesenc1f10402009-06-15 20:59:27 +00001034// isSafeToHoistInvoke - If we would need to insert a select that uses the
1035// value of this invoke (comments in HoistThenElseCodeToIf explain why we
1036// would need to do this), we can't hoist the invoke, as there is nowhere
1037// to put the select in this case.
1038static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1039 Instruction *I1, Instruction *I2) {
1040 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1041 PHINode *PN;
1042 for (BasicBlock::iterator BBI = SI->begin();
1043 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1044 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1045 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1046 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1047 return false;
1048 }
1049 }
1050 }
1051 return true;
1052}
1053
Chris Lattner6306d072005-08-03 17:59:45 +00001054/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +00001055/// BB2, hoist any common code in the two blocks up into the branch block. The
1056/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Rafael Espindola216dde92011-05-19 02:26:30 +00001057static bool HoistThenElseCodeToIf(BranchInst *BI) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001058 // This does very trivial matching, with limited scanning, to find identical
1059 // instructions in the two blocks. In particular, we don't want to get into
1060 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1061 // such, we currently just scan for obviously identical instructions in an
1062 // identical order.
1063 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1064 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1065
Devang Patel65085cf2009-02-04 00:03:08 +00001066 BasicBlock::iterator BB1_Itr = BB1->begin();
1067 BasicBlock::iterator BB2_Itr = BB2->begin();
1068
1069 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +00001070 // Skip debug info if it is not identical.
1071 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1072 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1073 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1074 while (isa<DbgInfoIntrinsic>(I1))
1075 I1 = BB1_Itr++;
1076 while (isa<DbgInfoIntrinsic>(I2))
1077 I2 = BB2_Itr++;
1078 }
Devang Patelae6c95b2011-04-07 00:30:15 +00001079 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +00001080 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +00001081 return false;
1082
1083 // If we get here, we can hoist at least one instruction.
1084 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +00001085
1086 do {
1087 // If we are hoisting the terminator instruction, don't move one (making a
1088 // broken BB), instead clone it, and remove BI.
1089 if (isa<TerminatorInst>(I1))
1090 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +00001091
Chris Lattner37dc9382004-11-30 00:29:14 +00001092 // For a normal instruction, we just move one to right before the branch,
1093 // then replace all uses of the other with the first. Finally, we remove
1094 // the now redundant second instruction.
1095 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1096 if (!I2->use_empty())
1097 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +00001098 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001099 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001100
Devang Patel65085cf2009-02-04 00:03:08 +00001101 I1 = BB1_Itr++;
Devang Patel65085cf2009-02-04 00:03:08 +00001102 I2 = BB2_Itr++;
Devang Patel949666e2011-04-07 17:27:36 +00001103 // Skip debug info if it is not identical.
1104 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1105 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1106 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1107 while (isa<DbgInfoIntrinsic>(I1))
1108 I1 = BB1_Itr++;
1109 while (isa<DbgInfoIntrinsic>(I2))
1110 I2 = BB2_Itr++;
1111 }
Devang Patelae6c95b2011-04-07 00:30:15 +00001112 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +00001113
1114 return true;
1115
1116HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +00001117 // It may not be possible to hoist an invoke.
1118 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1119 return true;
1120
Chris Lattner37dc9382004-11-30 00:29:14 +00001121 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +00001122 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +00001123 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +00001124 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001125 I1->replaceAllUsesWith(NT);
1126 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +00001127 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +00001128 }
1129
Devang Pateld3a17882011-05-19 20:52:46 +00001130 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner37dc9382004-11-30 00:29:14 +00001131 // Hoisting one of the terminators from our successor is a great thing.
1132 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1133 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1134 // nodes, so we insert select instruction to compute the final result.
1135 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1136 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1137 PHINode *PN;
1138 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +00001139 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +00001140 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1141 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001142 if (BB1V == BB2V) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001143
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001144 // These values do not agree. Insert a select instruction before NT
1145 // that determines the right value.
1146 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Andrew Trick6b014382012-08-29 21:46:36 +00001147 if (SI == 0)
Devang Pateld3a17882011-05-19 20:52:46 +00001148 SI = cast<SelectInst>
1149 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1150 BB1V->getName()+"."+BB2V->getName()));
1151
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001152 // Make the PHI node use the select for all incoming values for BB1/BB2
1153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1154 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1155 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +00001156 }
1157 }
1158
1159 // Update any PHI nodes in our new successors.
1160 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1161 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +00001162
Eli Friedman080efb82008-12-16 20:54:32 +00001163 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +00001164 return true;
1165}
1166
Manman Ren554da1a2012-09-20 22:37:36 +00001167/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1168/// check whether BBEnd has only two predecessors and the other predecessor
1169/// ends with an unconditional branch. If it is true, sink any common code
1170/// in the two predecessors to BBEnd.
1171static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1172 assert(BI1->isUnconditional());
1173 BasicBlock *BB1 = BI1->getParent();
1174 BasicBlock *BBEnd = BI1->getSuccessor(0);
1175
1176 // Check that BBEnd has two predecessors and the other predecessor ends with
1177 // an unconditional branch.
Benjamin Kramerfdb96062012-09-30 21:03:56 +00001178 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1179 BasicBlock *Pred0 = *PI++;
1180 if (PI == PE) // Only one predecessor.
Manman Ren554da1a2012-09-20 22:37:36 +00001181 return false;
Benjamin Kramerfdb96062012-09-30 21:03:56 +00001182 BasicBlock *Pred1 = *PI++;
1183 if (PI != PE) // More than two predecessors.
1184 return false;
1185 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren554da1a2012-09-20 22:37:36 +00001186 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1187 if (!BI2 || !BI2->isUnconditional())
1188 return false;
1189
1190 // Gather the PHI nodes in BBEnd.
1191 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1192 Instruction *FirstNonPhiInBBEnd = 0;
1193 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1194 I != E; ++I) {
1195 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1196 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1197 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1198 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1199 } else {
1200 FirstNonPhiInBBEnd = &*I;
1201 break;
1202 }
1203 }
1204 if (!FirstNonPhiInBBEnd)
1205 return false;
1206
1207
1208 // This does very trivial matching, with limited scanning, to find identical
1209 // instructions in the two blocks. We scan backward for obviously identical
1210 // instructions in an identical order.
1211 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1212 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1213 RE2 = BB2->getInstList().rend();
1214 // Skip debug info.
1215 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1216 if (RI1 == RE1)
1217 return false;
1218 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1219 if (RI2 == RE2)
1220 return false;
1221 // Skip the unconditional branches.
1222 ++RI1;
1223 ++RI2;
1224
1225 bool Changed = false;
1226 while (RI1 != RE1 && RI2 != RE2) {
1227 // Skip debug info.
1228 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1229 if (RI1 == RE1)
1230 return Changed;
1231 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1232 if (RI2 == RE2)
1233 return Changed;
1234
1235 Instruction *I1 = &*RI1, *I2 = &*RI2;
1236 // I1 and I2 should have a single use in the same PHI node, and they
1237 // perform the same operation.
1238 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1239 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1240 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1241 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1242 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1243 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1244 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1245 !I1->hasOneUse() || !I2->hasOneUse() ||
1246 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1247 MapValueFromBB1ToBB2[I1].first != I2)
1248 return Changed;
1249
1250 // Check whether we should swap the operands of ICmpInst.
1251 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1252 bool SwapOpnds = false;
1253 if (ICmp1 && ICmp2 &&
1254 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1255 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1256 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1257 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1258 ICmp2->swapOperands();
1259 SwapOpnds = true;
1260 }
1261 if (!I1->isSameOperationAs(I2)) {
1262 if (SwapOpnds)
1263 ICmp2->swapOperands();
1264 return Changed;
1265 }
1266
1267 // The operands should be either the same or they need to be generated
1268 // with a PHI node after sinking. We only handle the case where there is
1269 // a single pair of different operands.
1270 Value *DifferentOp1 = 0, *DifferentOp2 = 0;
1271 unsigned Op1Idx = 0;
1272 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1273 if (I1->getOperand(I) == I2->getOperand(I))
1274 continue;
1275 // Early exit if we have more-than one pair of different operands or
1276 // the different operand is already in MapValueFromBB1ToBB2.
1277 // Early exit if we need a PHI node to replace a constant.
1278 if (DifferentOp1 ||
1279 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1280 MapValueFromBB1ToBB2.end() ||
1281 isa<Constant>(I1->getOperand(I)) ||
1282 isa<Constant>(I2->getOperand(I))) {
1283 // If we can't sink the instructions, undo the swapping.
1284 if (SwapOpnds)
1285 ICmp2->swapOperands();
1286 return Changed;
1287 }
1288 DifferentOp1 = I1->getOperand(I);
1289 Op1Idx = I;
1290 DifferentOp2 = I2->getOperand(I);
1291 }
1292
1293 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1294 // remove (I1, I2) from MapValueFromBB1ToBB2.
1295 if (DifferentOp1) {
1296 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1297 DifferentOp1->getName() + ".sink",
1298 BBEnd->begin());
1299 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1300 // I1 should use NewPN instead of DifferentOp1.
1301 I1->setOperand(Op1Idx, NewPN);
1302 NewPN->addIncoming(DifferentOp1, BB1);
1303 NewPN->addIncoming(DifferentOp2, BB2);
1304 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1305 }
1306 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1307 MapValueFromBB1ToBB2.erase(I1);
1308
1309 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1310 DEBUG(dbgs() << " " << *I2 << "\n";);
1311 // We need to update RE1 and RE2 if we are going to sink the first
1312 // instruction in the basic block down.
1313 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1314 // Sink the instruction.
1315 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1316 if (!OldPN->use_empty())
1317 OldPN->replaceAllUsesWith(I1);
1318 OldPN->eraseFromParent();
1319
1320 if (!I2->use_empty())
1321 I2->replaceAllUsesWith(I1);
1322 I1->intersectOptionalDataWith(I2);
1323 I2->eraseFromParent();
1324
1325 if (UpdateRE1)
1326 RE1 = BB1->getInstList().rend();
1327 if (UpdateRE2)
1328 RE2 = BB2->getInstList().rend();
1329 FirstNonPhiInBBEnd = I1;
1330 NumSinkCommons++;
1331 Changed = true;
1332 }
1333 return Changed;
1334}
1335
Evan Cheng4d09efd2008-06-07 08:52:29 +00001336/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
1337/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
1338/// (for now, restricted to a single instruction that's side effect free) from
1339/// the BB1 into the branch block to speculatively execute it.
Dan Gohman3b205172012-01-05 23:58:56 +00001340///
1341/// Turn
1342/// BB:
1343/// %t1 = icmp
1344/// br i1 %t1, label %BB1, label %BB2
1345/// BB1:
1346/// %t3 = add %t2, c
1347/// br label BB2
1348/// BB2:
1349/// =>
1350/// BB:
1351/// %t1 = icmp
1352/// %t4 = add %t2, c
1353/// %t3 = select i1 %t1, %t2, %t3
Rafael Espindola216dde92011-05-19 02:26:30 +00001354static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
Evan Cheng4d09efd2008-06-07 08:52:29 +00001355 // Only speculatively execution a single instruction (not counting the
1356 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +00001357 Instruction *HInst = NULL;
1358 Instruction *Term = BB1->getTerminator();
1359 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
1360 BBI != BBE; ++BBI) {
1361 Instruction *I = BBI;
1362 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001363 if (isa<DbgInfoIntrinsic>(I)) continue;
1364 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +00001365
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001366 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +00001367 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001368 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +00001369 }
Dan Gohman3b205172012-01-05 23:58:56 +00001370
1371 BasicBlock *BIParent = BI->getParent();
1372
1373 // Check the instruction to be hoisted, if there is one.
1374 if (HInst) {
1375 // Don't hoist the instruction if it's unsafe or expensive.
1376 if (!isSafeToSpeculativelyExecute(HInst))
1377 return false;
1378 if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
1379 return false;
1380
1381 // Do not hoist the instruction if any of its operands are defined but not
1382 // used in this BB. The transformation will prevent the operand from
1383 // being sunk into the use block.
Andrew Trick6b014382012-08-29 21:46:36 +00001384 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
Dan Gohman3b205172012-01-05 23:58:56 +00001385 i != e; ++i) {
1386 Instruction *OpI = dyn_cast<Instruction>(*i);
1387 if (OpI && OpI->getParent() == BIParent &&
1388 !OpI->mayHaveSideEffects() &&
1389 !OpI->isUsedInBasicBlock(BIParent))
1390 return false;
1391 }
1392 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001393
Evan Cheng797d9512008-06-11 19:18:20 +00001394 // Be conservative for now. FP select instruction can often be expensive.
1395 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001396 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +00001397 return false;
1398
Evan Cheng4d09efd2008-06-07 08:52:29 +00001399 // If BB1 is actually on the false edge of the conditional branch, remember
1400 // to swap the select operands later.
1401 bool Invert = false;
1402 if (BB1 != BI->getSuccessor(0)) {
1403 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1404 Invert = true;
1405 }
1406
Dan Gohman3b205172012-01-05 23:58:56 +00001407 // Collect interesting PHIs, and scan for hazards.
1408 SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001409 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Dan Gohman3b205172012-01-05 23:58:56 +00001410 for (BasicBlock::iterator I = BB2->begin();
1411 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1412 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1413 Value *BIParentV = PN->getIncomingValueForBlock(BIParent);
1414
1415 // Skip PHIs which are trivial.
1416 if (BB1V == BIParentV)
1417 continue;
1418
1419 // Check for saftey.
1420 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BB1V)) {
1421 // An unfolded ConstantExpr could end up getting expanded into
1422 // Instructions. Don't speculate this and another instruction at
1423 // the same time.
1424 if (HInst)
1425 return false;
1426 if (!isSafeToSpeculativelyExecute(CE))
1427 return false;
1428 if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
1429 return false;
1430 }
1431
1432 // Ok, we may insert a select for this PHI.
1433 PHIs.insert(std::make_pair(BB1V, BIParentV));
Evan Cheng4d09efd2008-06-07 08:52:29 +00001434 }
Dan Gohman3b205172012-01-05 23:58:56 +00001435
1436 // If there are no PHIs to process, bail early. This helps ensure idempotence
1437 // as well.
1438 if (PHIs.empty())
1439 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001440
Dan Gohman3b205172012-01-05 23:58:56 +00001441 // If we get here, we can hoist the instruction and if-convert.
1442 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001443
Dan Gohman3b205172012-01-05 23:58:56 +00001444 // Hoist the instruction.
1445 if (HInst)
1446 BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
Evan Cheng502a4f52008-06-12 21:15:59 +00001447
Dan Gohman3b205172012-01-05 23:58:56 +00001448 // Insert selects and rewrite the PHI operands.
Devang Pateld3a17882011-05-19 20:52:46 +00001449 IRBuilder<true, NoFolder> Builder(BI);
Dan Gohman3b205172012-01-05 23:58:56 +00001450 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
1451 Value *TrueV = PHIs[i].first;
1452 Value *FalseV = PHIs[i].second;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001453
Dan Gohman3b205172012-01-05 23:58:56 +00001454 // Create a select whose true value is the speculatively executed value and
1455 // false value is the previously determined FalseV.
1456 SelectInst *SI;
1457 if (Invert)
1458 SI = cast<SelectInst>
1459 (Builder.CreateSelect(BrCond, FalseV, TrueV,
1460 FalseV->getName() + "." + TrueV->getName()));
1461 else
1462 SI = cast<SelectInst>
1463 (Builder.CreateSelect(BrCond, TrueV, FalseV,
1464 TrueV->getName() + "." + FalseV->getName()));
1465
1466 // Make the PHI node use the select for all incoming values for "then" and
1467 // "if" blocks.
1468 for (BasicBlock::iterator I = BB2->begin();
1469 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1470 unsigned BB1I = PN->getBasicBlockIndex(BB1);
1471 unsigned BIParentI = PN->getBasicBlockIndex(BIParent);
1472 Value *BB1V = PN->getIncomingValue(BB1I);
1473 Value *BIParentV = PN->getIncomingValue(BIParentI);
1474 if (TrueV == BB1V && FalseV == BIParentV) {
1475 PN->setIncomingValue(BB1I, SI);
1476 PN->setIncomingValue(BIParentI, SI);
1477 }
1478 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001479 }
1480
Evan Cheng502a4f52008-06-12 21:15:59 +00001481 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001482 return true;
1483}
1484
Chris Lattner2e42e362005-09-20 00:43:16 +00001485/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1486/// across this block.
1487static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1488 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001489 unsigned Size = 0;
Andrew Trick6b014382012-08-29 21:46:36 +00001490
Devang Patel9200c892009-03-10 18:00:05 +00001491 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001492 if (isa<DbgInfoIntrinsic>(BBI))
1493 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001494 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001495 ++Size;
Andrew Trick6b014382012-08-29 21:46:36 +00001496
Dale Johannesen8483e542009-03-12 23:18:09 +00001497 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001498 // live outside of the current basic block.
1499 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1500 UI != E; ++UI) {
1501 Instruction *U = cast<Instruction>(*UI);
1502 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1503 }
Andrew Trick6b014382012-08-29 21:46:36 +00001504
Chris Lattner2e42e362005-09-20 00:43:16 +00001505 // Looks ok, continue checking.
1506 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001507
Chris Lattner2e42e362005-09-20 00:43:16 +00001508 return true;
1509}
1510
Chris Lattnereaba3a12005-09-19 23:49:37 +00001511/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1512/// that is defined in the same block as the branch and if any PHI entries are
1513/// constants, thread edges corresponding to that entry to be branches to their
1514/// ultimate destination.
Micah Villmow3574eca2012-10-08 16:38:25 +00001515static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001516 BasicBlock *BB = BI->getParent();
1517 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001518 // NOTE: we currently cannot transform this case if the PHI node is used
1519 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001520 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1521 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001522
Chris Lattnereaba3a12005-09-19 23:49:37 +00001523 // Degenerate case of a single entry PHI.
1524 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001525 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001526 return true;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001527 }
1528
1529 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001530 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001531
Chris Lattnereaba3a12005-09-19 23:49:37 +00001532 // Okay, this is a simple enough basic block. See if any phi values are
1533 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001534 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001535 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1536 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001537
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001538 // Okay, we now know that all edges from PredBB should be revectored to
1539 // branch to RealDest.
1540 BasicBlock *PredBB = PN->getIncomingBlock(i);
1541 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trick6b014382012-08-29 21:46:36 +00001542
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001543 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling6a648b82011-06-04 09:42:04 +00001544 // Skip if the predecessor's terminator is an indirect branch.
1545 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001546
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001547 // The dest block might have PHI nodes, other predecessors and other
1548 // difficult cases. Instead of being smart about this, just insert a new
1549 // block that jumps to the destination block, effectively splitting
1550 // the edge we are about to create.
1551 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1552 RealDest->getName()+".critedge",
1553 RealDest->getParent(), RealDest);
1554 BranchInst::Create(RealDest, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00001555
Chris Lattner6de0a282010-12-14 07:09:42 +00001556 // Update PHI nodes.
1557 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001558
1559 // BB may have instructions that are being threaded over. Clone these
1560 // instructions into EdgeBB. We know that there will be no uses of the
1561 // cloned instructions outside of EdgeBB.
1562 BasicBlock::iterator InsertPt = EdgeBB->begin();
1563 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1564 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1565 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1566 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1567 continue;
1568 }
1569 // Clone the instruction.
1570 Instruction *N = BBI->clone();
1571 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trick6b014382012-08-29 21:46:36 +00001572
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001573 // Update operands due to translation.
1574 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1575 i != e; ++i) {
1576 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1577 if (PI != TranslateMap.end())
1578 *i = PI->second;
1579 }
Andrew Trick6b014382012-08-29 21:46:36 +00001580
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001581 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001582 if (Value *V = SimplifyInstruction(N, TD)) {
1583 TranslateMap[BBI] = V;
1584 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001585 } else {
1586 // Insert the new instruction into its new home.
1587 EdgeBB->getInstList().insert(InsertPt, N);
1588 if (!BBI->use_empty())
1589 TranslateMap[BBI] = N;
1590 }
1591 }
1592
1593 // Loop over all of the edges from PredBB to BB, changing them to branch
1594 // to EdgeBB instead.
1595 TerminatorInst *PredBBTI = PredBB->getTerminator();
1596 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1597 if (PredBBTI->getSuccessor(i) == BB) {
1598 BB->removePredecessor(PredBB);
1599 PredBBTI->setSuccessor(i, EdgeBB);
1600 }
Bill Wendling6a648b82011-06-04 09:42:04 +00001601
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001602 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001603 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001604 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001605
1606 return false;
1607}
1608
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001609/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1610/// PHI node, see if we can eliminate it.
Micah Villmow3574eca2012-10-08 16:38:25 +00001611static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001612 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1613 // statement", which has a very simple dominance structure. Basically, we
1614 // are trying to find the condition that is being branched on, which
1615 // subsequently causes this merge to happen. We really want control
1616 // dependence information for this check, but simplifycfg can't keep it up
1617 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001618 BasicBlock *BB = PN->getParent();
1619 BasicBlock *IfTrue, *IfFalse;
1620 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001621 if (!IfCond ||
1622 // Don't bother if the branch will be constant folded trivially.
1623 isa<ConstantInt>(IfCond))
1624 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001625
Chris Lattner822a8792006-11-18 19:19:36 +00001626 // Okay, we found that we can merge this two-entry phi node into a select.
1627 // Doing so would require us to fold *all* two entry phi nodes in this block.
1628 // At some point this becomes non-profitable (particularly if the target
1629 // doesn't support cmov's). Only do this transformation if there are two or
1630 // fewer PHI nodes in this block.
1631 unsigned NumPhis = 0;
1632 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1633 if (NumPhis > 2)
1634 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001635
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001636 // Loop over the PHI's seeing if we can promote them all to select
1637 // instructions. While we are at it, keep track of the instructions
1638 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001639 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne57808b32011-04-29 18:47:38 +00001640 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1641 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trick6b014382012-08-29 21:46:36 +00001642
Chris Lattner3aff13b2010-12-14 08:46:09 +00001643 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1644 PHINode *PN = cast<PHINode>(II++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001645 if (Value *V = SimplifyInstruction(PN, TD)) {
1646 PN->replaceAllUsesWith(V);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001647 PN->eraseFromParent();
Chris Lattner07ff3532010-12-14 07:20:29 +00001648 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001649 }
Andrew Trick6b014382012-08-29 21:46:36 +00001650
Peter Collingbournef15907f2011-04-29 18:47:31 +00001651 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1652 MaxCostVal0) ||
1653 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1654 MaxCostVal1))
Chris Lattner07ff3532010-12-14 07:20:29 +00001655 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001656 }
Andrew Trick6b014382012-08-29 21:46:36 +00001657
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001658 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner44da7ca2010-12-14 07:41:39 +00001659 // we ran out of PHIs then we simplified them all.
1660 PN = dyn_cast<PHINode>(BB->begin());
1661 if (PN == 0) return true;
Andrew Trick6b014382012-08-29 21:46:36 +00001662
Chris Lattner3aff13b2010-12-14 08:46:09 +00001663 // Don't fold i1 branches on PHIs which contain binary operators. These can
1664 // often be turned into switches and other things.
1665 if (PN->getType()->isIntegerTy(1) &&
1666 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1667 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1668 isa<BinaryOperator>(IfCond)))
1669 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001670
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001671 // If we all PHI nodes are promotable, check to make sure that all
1672 // instructions in the predecessor blocks can be promoted as well. If
1673 // not, we won't be able to get rid of the control flow, so it's not
1674 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001675 BasicBlock *DomBlock = 0;
1676 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1677 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1678 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1679 IfBlock1 = 0;
1680 } else {
1681 DomBlock = *pred_begin(IfBlock1);
1682 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001683 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001684 // This is not an aggressive instruction that we can promote.
1685 // Because of this, we won't be able to get rid of the control
1686 // flow, so the xform is not worth it.
1687 return false;
1688 }
1689 }
Andrew Trick6b014382012-08-29 21:46:36 +00001690
Chris Lattner44da7ca2010-12-14 07:41:39 +00001691 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1692 IfBlock2 = 0;
1693 } else {
1694 DomBlock = *pred_begin(IfBlock2);
1695 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001696 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001697 // This is not an aggressive instruction that we can promote.
1698 // Because of this, we won't be able to get rid of the control
1699 // flow, so the xform is not worth it.
1700 return false;
1701 }
1702 }
Andrew Trick6b014382012-08-29 21:46:36 +00001703
Chris Lattnere0b18e52010-12-14 07:23:10 +00001704 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001705 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trick6b014382012-08-29 21:46:36 +00001706
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001707 // If we can still promote the PHI nodes after this gauntlet of tests,
1708 // do all of the PHI's now.
Chris Lattner3aff13b2010-12-14 08:46:09 +00001709 Instruction *InsertPt = DomBlock->getTerminator();
Devang Pateld3a17882011-05-19 20:52:46 +00001710 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trick6b014382012-08-29 21:46:36 +00001711
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001712 // Move all 'aggressive' instructions, which are defined in the
1713 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001714 if (IfBlock1)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001715 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001716 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001717 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001718 if (IfBlock2)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001719 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001720 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001721 IfBlock2->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001722
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001723 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1724 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001725 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1726 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trick6b014382012-08-29 21:46:36 +00001727
1728 SelectInst *NV =
Devang Patelf60364d2011-05-18 18:16:44 +00001729 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner86cc4232007-02-11 01:37:51 +00001730 PN->replaceAllUsesWith(NV);
1731 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001732 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001733 }
Andrew Trick6b014382012-08-29 21:46:36 +00001734
Chris Lattner60d410d2010-12-14 08:01:53 +00001735 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1736 // has been flattened. Change DomBlock to jump directly to our new block to
1737 // avoid other simplifycfg's kicking in on the diamond.
1738 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patelf60364d2011-05-18 18:16:44 +00001739 Builder.SetInsertPoint(OldTI);
1740 Builder.CreateBr(BB);
Chris Lattner60d410d2010-12-14 08:01:53 +00001741 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001742 return true;
1743}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001744
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001745/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1746/// to two returning blocks, try to merge them together into one return,
1747/// introducing a select if the return values disagree.
Andrew Trick6b014382012-08-29 21:46:36 +00001748static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Patel176ec402011-05-18 21:33:11 +00001749 IRBuilder<> &Builder) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001750 assert(BI->isConditional() && "Must be a conditional branch");
1751 BasicBlock *TrueSucc = BI->getSuccessor(0);
1752 BasicBlock *FalseSucc = BI->getSuccessor(1);
1753 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1754 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001755
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001756 // Check to ensure both blocks are empty (just a return) or optionally empty
1757 // with PHI nodes. If there are other instructions, merging would cause extra
1758 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001759 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001760 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001761 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001762 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001763
Devang Patel176ec402011-05-18 21:33:11 +00001764 Builder.SetInsertPoint(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001765 // Okay, we found a branch that is going to two return nodes. If
1766 // there is no return value for this function, just change the
1767 // branch into a return.
1768 if (FalseRet->getNumOperands() == 0) {
1769 TrueSucc->removePredecessor(BI->getParent());
1770 FalseSucc->removePredecessor(BI->getParent());
Devang Patel176ec402011-05-18 21:33:11 +00001771 Builder.CreateRetVoid();
Eli Friedman080efb82008-12-16 20:54:32 +00001772 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001773 return true;
1774 }
Andrew Trick6b014382012-08-29 21:46:36 +00001775
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001776 // Otherwise, figure out what the true and false return values are
1777 // so we can insert a new select instruction.
1778 Value *TrueValue = TrueRet->getReturnValue();
1779 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trick6b014382012-08-29 21:46:36 +00001780
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001781 // Unwrap any PHI nodes in the return blocks.
1782 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1783 if (TVPN->getParent() == TrueSucc)
1784 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1785 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1786 if (FVPN->getParent() == FalseSucc)
1787 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001788
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001789 // In order for this transformation to be safe, we must be able to
1790 // unconditionally execute both operands to the return. This is
1791 // normally the case, but we could have a potentially-trapping
1792 // constant expression that prevents this transformation from being
1793 // safe.
1794 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1795 if (TCV->canTrap())
1796 return false;
1797 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1798 if (FCV->canTrap())
1799 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001800
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001801 // Okay, we collected all the mapped values and checked them for sanity, and
1802 // defined to really do this transformation. First, update the CFG.
1803 TrueSucc->removePredecessor(BI->getParent());
1804 FalseSucc->removePredecessor(BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00001805
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001806 // Insert select instructions where needed.
1807 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001808 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001809 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001810 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1811 } else if (isa<UndefValue>(TrueValue)) {
1812 TrueValue = FalseValue;
1813 } else {
Devang Patel176ec402011-05-18 21:33:11 +00001814 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1815 FalseValue, "retval");
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001816 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001817 }
1818
Andrew Trick6b014382012-08-29 21:46:36 +00001819 Value *RI = !TrueValue ?
Devang Patel176ec402011-05-18 21:33:11 +00001820 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1821
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001822 (void) RI;
Andrew Trick6b014382012-08-29 21:46:36 +00001823
David Greene89d6fd32010-01-05 01:26:52 +00001824 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001825 << "\n " << *BI << "NewRet = " << *RI
1826 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trick6b014382012-08-29 21:46:36 +00001827
Eli Friedman080efb82008-12-16 20:54:32 +00001828 EraseTerminatorInstAndDCECond(BI);
1829
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001830 return true;
1831}
1832
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001833/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1834/// probabilities of the branch taking each edge. Fills in the two APInt
1835/// parameters and return true, or returns false if no or invalid metadata was
1836/// found.
1837static bool ExtractBranchMetadata(BranchInst *BI,
Manman Ren062986c2012-09-15 00:39:57 +00001838 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001839 assert(BI->isConditional() &&
1840 "Looking for probabilities on unconditional branch?");
1841 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky91968482011-12-27 18:27:22 +00001842 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001843 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1844 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky91968482011-12-27 18:27:22 +00001845 if (!CITrue || !CIFalse) return false;
Manman Ren062986c2012-09-15 00:39:57 +00001846 ProbTrue = CITrue->getValue().getZExtValue();
1847 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewycky06cc66f2011-12-27 04:31:52 +00001848 return true;
1849}
1850
Manman Renee28e0f2012-06-13 05:43:29 +00001851/// checkCSEInPredecessor - Return true if the given instruction is available
1852/// in its predecessor block. If yes, the instruction will be removed.
1853///
Benjamin Kramer23d36222012-07-13 13:25:15 +00001854static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Renee28e0f2012-06-13 05:43:29 +00001855 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1856 return false;
1857 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1858 Instruction *PBI = &*I;
1859 // Check whether Inst and PBI generate the same value.
1860 if (Inst->isIdenticalTo(PBI)) {
1861 Inst->replaceAllUsesWith(PBI);
1862 Inst->eraseFromParent();
1863 return true;
1864 }
1865 }
1866 return false;
1867}
Nick Lewycky6c00c6a2012-01-25 09:43:14 +00001868
Chris Lattnerc8fbc342011-04-11 23:24:57 +00001869/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1870/// predecessor branches to us and one of our successors, fold the block into
1871/// the predecessor and use logical operations to pick the right destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001872bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001873 BasicBlock *BB = BI->getParent();
Devang Pateld3a17882011-05-19 20:52:46 +00001874
Manman Renee28e0f2012-06-13 05:43:29 +00001875 Instruction *Cond = 0;
1876 if (BI->isConditional())
1877 Cond = dyn_cast<Instruction>(BI->getCondition());
1878 else {
1879 // For unconditional branch, check for a simple CFG pattern, where
1880 // BB has a single predecessor and BB's successor is also its predecessor's
1881 // successor. If such pattern exisits, check for CSE between BB and its
1882 // predecessor.
1883 if (BasicBlock *PB = BB->getSinglePredecessor())
1884 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1885 if (PBI->isConditional() &&
1886 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1887 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1888 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1889 I != E; ) {
1890 Instruction *Curr = I++;
1891 if (isa<CmpInst>(Curr)) {
1892 Cond = Curr;
1893 break;
1894 }
1895 // Quit if we can't remove this instruction.
1896 if (!checkCSEInPredecessor(Curr, PB))
1897 return false;
1898 }
1899 }
1900
1901 if (Cond == 0)
1902 return false;
1903 }
Andrew Trick6b014382012-08-29 21:46:36 +00001904
Owen Andersone84178a2010-07-14 19:52:16 +00001905 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1906 Cond->getParent() != BB || !Cond->hasOneUse())
1907 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001908
Chris Lattner1347e872008-07-13 21:12:01 +00001909 // Only allow this if the condition is a simple instruction that can be
1910 // executed unconditionally. It must be in the same block as the branch, and
1911 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001912 BasicBlock::iterator FrontIt = BB->front();
Chris Lattner3c6e7462011-04-14 02:44:53 +00001913
Devang Pateld0a203d2009-02-04 21:39:48 +00001914 // Ignore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001915 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Nick Lewycky9d523102011-12-26 20:37:40 +00001916
Owen Andersone84178a2010-07-14 19:52:16 +00001917 // Allow a single instruction to be hoisted in addition to the compare
1918 // that feeds the branch. We later ensure that any values that _it_ uses
1919 // were also live in the predecessor, so that we don't unnecessarily create
1920 // register pressure or inhibit out-of-order execution.
1921 Instruction *BonusInst = 0;
1922 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001923 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
Dan Gohmanf0426602011-12-14 23:49:11 +00001924 isSafeToSpeculativelyExecute(FrontIt)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001925 BonusInst = &*FrontIt;
1926 ++FrontIt;
Andrew Trick6b014382012-08-29 21:46:36 +00001927
Chris Lattner3c6e7462011-04-14 02:44:53 +00001928 // Ignore dbg intrinsics.
1929 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Devang Patel60d490c2011-04-07 23:11:25 +00001930 }
1931
Owen Andersone84178a2010-07-14 19:52:16 +00001932 // Only a single bonus inst is allowed.
1933 if (&*FrontIt != Cond)
1934 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001935
Chris Lattner1347e872008-07-13 21:12:01 +00001936 // Make sure the instruction after the condition is the cond branch.
1937 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001938
Devang Pateld0a203d2009-02-04 21:39:48 +00001939 // Ingore dbg intrinsics.
Chris Lattner3c6e7462011-04-14 02:44:53 +00001940 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trick6b014382012-08-29 21:46:36 +00001941
Chris Lattner3c6e7462011-04-14 02:44:53 +00001942 if (&*CondIt != BI)
Chris Lattner1347e872008-07-13 21:12:01 +00001943 return false;
Chris Lattner6ff645b2009-01-19 23:03:13 +00001944
1945 // Cond is known to be a compare or binary operator. Check to make sure that
1946 // neither operand is a potentially-trapping constant expression.
1947 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1948 if (CE->canTrap())
1949 return false;
1950 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1951 if (CE->canTrap())
1952 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00001953
Chris Lattner1347e872008-07-13 21:12:01 +00001954 // Finally, don't infinitely unroll conditional loops.
1955 BasicBlock *TrueDest = BI->getSuccessor(0);
Manman Renee28e0f2012-06-13 05:43:29 +00001956 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0;
Chris Lattner1347e872008-07-13 21:12:01 +00001957 if (TrueDest == BB || FalseDest == BB)
1958 return false;
Devang Pateld4181942011-04-06 22:37:20 +00001959
Chris Lattner1347e872008-07-13 21:12:01 +00001960 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1961 BasicBlock *PredBlock = *PI;
1962 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trick6b014382012-08-29 21:46:36 +00001963
Chris Lattner093a4382008-07-13 22:23:11 +00001964 // Check that we have two conditional branches. If there is a PHI node in
1965 // the common successor, verify that the same value flows in from both
1966 // blocks.
Manman Renee28e0f2012-06-13 05:43:29 +00001967 SmallVector<PHINode*, 4> PHIs;
1968 if (PBI == 0 || PBI->isUnconditional() ||
Andrew Trick6b014382012-08-29 21:46:36 +00001969 (BI->isConditional() &&
Manman Renee28e0f2012-06-13 05:43:29 +00001970 !SafeToMergeTerminators(BI, PBI)) ||
1971 (!BI->isConditional() &&
1972 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner1347e872008-07-13 21:12:01 +00001973 continue;
Andrew Trick6b014382012-08-29 21:46:36 +00001974
Chris Lattner3c6e7462011-04-14 02:44:53 +00001975 // Determine if the two branches share a common destination.
Axel Naumann3780ad82012-09-17 14:20:57 +00001976 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattner3c6e7462011-04-14 02:44:53 +00001977 bool InvertPredCond = false;
Andrew Trick6b014382012-08-29 21:46:36 +00001978
Manman Renee28e0f2012-06-13 05:43:29 +00001979 if (BI->isConditional()) {
1980 if (PBI->getSuccessor(0) == TrueDest)
1981 Opc = Instruction::Or;
1982 else if (PBI->getSuccessor(1) == FalseDest)
1983 Opc = Instruction::And;
1984 else if (PBI->getSuccessor(0) == FalseDest)
1985 Opc = Instruction::And, InvertPredCond = true;
1986 else if (PBI->getSuccessor(1) == TrueDest)
1987 Opc = Instruction::Or, InvertPredCond = true;
1988 else
1989 continue;
1990 } else {
1991 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
1992 continue;
1993 }
Chris Lattner3c6e7462011-04-14 02:44:53 +00001994
Owen Andersone84178a2010-07-14 19:52:16 +00001995 // Ensure that any values used in the bonus instruction are also used
1996 // by the terminator of the predecessor. This means that those values
Andrew Trick6b014382012-08-29 21:46:36 +00001997 // must already have been resolved, so we won't be inhibiting the
Owen Andersone84178a2010-07-14 19:52:16 +00001998 // out-of-order core by speculating them earlier.
1999 if (BonusInst) {
2000 // Collect the values used by the bonus inst
2001 SmallPtrSet<Value*, 4> UsedValues;
2002 for (Instruction::op_iterator OI = BonusInst->op_begin(),
2003 OE = BonusInst->op_end(); OI != OE; ++OI) {
Nick Lewycky9d523102011-12-26 20:37:40 +00002004 Value *V = *OI;
Owen Andersone84178a2010-07-14 19:52:16 +00002005 if (!isa<Constant>(V))
2006 UsedValues.insert(V);
2007 }
2008
2009 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2010 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
Andrew Trick6b014382012-08-29 21:46:36 +00002011
Owen Andersone84178a2010-07-14 19:52:16 +00002012 // Walk up to four levels back up the use-def chain of the predecessor's
2013 // terminator to see if all those values were used. The choice of four
2014 // levels is arbitrary, to provide a compile-time-cost bound.
2015 while (!Worklist.empty()) {
2016 std::pair<Value*, unsigned> Pair = Worklist.back();
2017 Worklist.pop_back();
Andrew Trick6b014382012-08-29 21:46:36 +00002018
Owen Andersone84178a2010-07-14 19:52:16 +00002019 if (Pair.second >= 4) continue;
2020 UsedValues.erase(Pair.first);
2021 if (UsedValues.empty()) break;
Andrew Trick6b014382012-08-29 21:46:36 +00002022
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002023 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00002024 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2025 OI != OE; ++OI)
2026 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
Andrew Trick6b014382012-08-29 21:46:36 +00002027 }
Owen Andersone84178a2010-07-14 19:52:16 +00002028 }
Andrew Trick6b014382012-08-29 21:46:36 +00002029
Owen Andersone84178a2010-07-14 19:52:16 +00002030 if (!UsedValues.empty()) return false;
2031 }
Chris Lattner36989092008-07-13 21:20:19 +00002032
David Greene89d6fd32010-01-05 01:26:52 +00002033 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002034 IRBuilder<> Builder(PBI);
Devang Pateld3a17882011-05-19 20:52:46 +00002035
Chris Lattner36989092008-07-13 21:20:19 +00002036 // If we need to invert the condition in the pred block to match, do so now.
2037 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002038 Value *NewCond = PBI->getCondition();
Andrew Trick6b014382012-08-29 21:46:36 +00002039
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002040 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2041 CmpInst *CI = cast<CmpInst>(NewCond);
2042 CI->setPredicate(CI->getInversePredicate());
2043 } else {
Andrew Trick6b014382012-08-29 21:46:36 +00002044 NewCond = Builder.CreateNot(NewCond,
Devang Pateld3a17882011-05-19 20:52:46 +00002045 PBI->getCondition()->getName()+".not");
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00002046 }
Andrew Trick6b014382012-08-29 21:46:36 +00002047
Chris Lattner1347e872008-07-13 21:12:01 +00002048 PBI->setCondition(NewCond);
Nick Lewyckyc9a1aed2011-12-26 20:54:14 +00002049 PBI->swapSuccessors();
Chris Lattner1347e872008-07-13 21:12:01 +00002050 }
Andrew Trick6b014382012-08-29 21:46:36 +00002051
Owen Andersone84178a2010-07-14 19:52:16 +00002052 // If we have a bonus inst, clone it into the predecessor block.
2053 Instruction *NewBonus = 0;
2054 if (BonusInst) {
2055 NewBonus = BonusInst->clone();
2056 PredBlock->getInstList().insert(PBI, NewBonus);
2057 NewBonus->takeName(BonusInst);
2058 BonusInst->setName(BonusInst->getName()+".old");
2059 }
Andrew Trick6b014382012-08-29 21:46:36 +00002060
Chris Lattner36989092008-07-13 21:20:19 +00002061 // Clone Cond into the predecessor basic block, and or/and the
2062 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00002063 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00002064 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00002065 PredBlock->getInstList().insert(PBI, New);
2066 New->takeName(Cond);
2067 Cond->setName(New->getName()+".old");
Andrew Trick6b014382012-08-29 21:46:36 +00002068
Manman Renee28e0f2012-06-13 05:43:29 +00002069 if (BI->isConditional()) {
Andrew Trick6b014382012-08-29 21:46:36 +00002070 Instruction *NewCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002071 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Pateld3a17882011-05-19 20:52:46 +00002072 New, "or.cond"));
Manman Renee28e0f2012-06-13 05:43:29 +00002073 PBI->setCondition(NewCond);
2074
Manman Ren062986c2012-09-15 00:39:57 +00002075 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2076 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2077 PredFalseWeight);
2078 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2079 SuccFalseWeight);
2080 SmallVector<uint64_t, 8> NewWeights;
2081
Manman Renee28e0f2012-06-13 05:43:29 +00002082 if (PBI->getSuccessor(0) == BB) {
Manman Ren062986c2012-09-15 00:39:57 +00002083 if (PredHasWeights && SuccHasWeights) {
2084 // PBI: br i1 %x, BB, FalseDest
2085 // BI: br i1 %y, TrueDest, FalseDest
2086 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2087 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2088 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2089 // TrueWeight for PBI * FalseWeight for BI.
2090 // We assume that total weights of a BranchInst can fit into 32 bits.
2091 // Therefore, we will not have overflow using 64-bit arithmetic.
2092 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2093 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2094 }
Manman Renee28e0f2012-06-13 05:43:29 +00002095 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2096 PBI->setSuccessor(0, TrueDest);
2097 }
2098 if (PBI->getSuccessor(1) == BB) {
Manman Ren062986c2012-09-15 00:39:57 +00002099 if (PredHasWeights && SuccHasWeights) {
2100 // PBI: br i1 %x, TrueDest, BB
2101 // BI: br i1 %y, TrueDest, FalseDest
2102 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2103 // FalseWeight for PBI * TrueWeight for BI.
2104 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2105 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2106 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2107 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2108 }
Manman Renee28e0f2012-06-13 05:43:29 +00002109 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2110 PBI->setSuccessor(1, FalseDest);
2111 }
Manman Ren062986c2012-09-15 00:39:57 +00002112 if (NewWeights.size() == 2) {
2113 // Halve the weights if any of them cannot fit in an uint32_t
2114 FitWeights(NewWeights);
2115
2116 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2117 PBI->setMetadata(LLVMContext::MD_prof,
2118 MDBuilder(BI->getContext()).
2119 createBranchWeights(MDWeights));
2120 } else
2121 PBI->setMetadata(LLVMContext::MD_prof, NULL);
Manman Renee28e0f2012-06-13 05:43:29 +00002122 } else {
2123 // Update PHI nodes in the common successors.
2124 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewyckyedb58422012-06-24 10:15:42 +00002125 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Renee28e0f2012-06-13 05:43:29 +00002126 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2127 assert(PBI_C->getType()->isIntegerTy(1));
2128 Instruction *MergedCond = 0;
2129 if (PBI->getSuccessor(0) == TrueDest) {
2130 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2131 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2132 // is false: !PBI_Cond and BI_Value
2133 Instruction *NotCond =
2134 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2135 "not.cond"));
2136 MergedCond =
2137 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2138 NotCond, New,
2139 "and.cond"));
2140 if (PBI_C->isOne())
2141 MergedCond =
2142 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2143 PBI->getCondition(), MergedCond,
2144 "or.cond"));
2145 } else {
2146 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2147 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2148 // is false: PBI_Cond and BI_Value
Andrew Trick6b014382012-08-29 21:46:36 +00002149 MergedCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002150 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2151 PBI->getCondition(), New,
2152 "and.cond"));
2153 if (PBI_C->isOne()) {
2154 Instruction *NotCond =
2155 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2156 "not.cond"));
Andrew Trick6b014382012-08-29 21:46:36 +00002157 MergedCond =
Manman Renee28e0f2012-06-13 05:43:29 +00002158 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2159 NotCond, MergedCond,
2160 "or.cond"));
2161 }
2162 }
2163 // Update PHI Node.
2164 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2165 MergedCond);
2166 }
2167 // Change PBI from Conditional to Unconditional.
2168 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2169 EraseTerminatorInstAndDCECond(PBI);
2170 PBI = New_PBI;
Chris Lattner36989092008-07-13 21:20:19 +00002171 }
Devang Pateld4181942011-04-06 22:37:20 +00002172
Nick Lewycky06cc66f2011-12-27 04:31:52 +00002173 // TODO: If BB is reachable from all paths through PredBlock, then we
2174 // could replace PBI's branch probabilities with BI's.
2175
Chris Lattner3c6e7462011-04-14 02:44:53 +00002176 // Copy any debug value intrinsics into the end of PredBlock.
2177 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2178 if (isa<DbgInfoIntrinsic>(*I))
2179 I->clone()->insertBefore(PBI);
Andrew Trick6b014382012-08-29 21:46:36 +00002180
Chris Lattner117f8cf2010-12-14 05:57:30 +00002181 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00002182 }
2183 return false;
2184}
2185
Chris Lattner867661a2008-07-13 21:53:26 +00002186/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2187/// predecessor of another block, this function tries to simplify it. We know
2188/// that PBI and BI are both conditional branches, and BI is in one of the
2189/// successor blocks of PBI - PBI branches to BI.
2190static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2191 assert(PBI->isConditional() && BI->isConditional());
2192 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00002193
Chris Lattner867661a2008-07-13 21:53:26 +00002194 // If this block ends with a branch instruction, and if there is a
Andrew Trick6b014382012-08-29 21:46:36 +00002195 // predecessor that ends on a branch of the same condition, make
Chris Lattner867661a2008-07-13 21:53:26 +00002196 // this conditional branch redundant.
2197 if (PBI->getCondition() == BI->getCondition() &&
2198 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2199 // Okay, the outcome of this conditional branch is statically
2200 // knowable. If this block had a single pred, handle specially.
2201 if (BB->getSinglePredecessor()) {
2202 // Turn this into a branch on constant.
2203 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trick6b014382012-08-29 21:46:36 +00002204 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +00002205 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00002206 return true; // Nuke the branch on constant.
2207 }
Andrew Trick6b014382012-08-29 21:46:36 +00002208
Chris Lattner867661a2008-07-13 21:53:26 +00002209 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2210 // in the constant and simplify the block result. Subsequent passes of
2211 // simplifycfg will thread the block.
2212 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foadd8b4fb42011-03-30 11:19:20 +00002213 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson1d0be152009-08-13 21:58:54 +00002214 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad3ecfc862011-03-30 11:28:46 +00002215 std::distance(PB, PE),
Chris Lattner867661a2008-07-13 21:53:26 +00002216 BI->getCondition()->getName() + ".pr",
2217 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00002218 // Okay, we're going to insert the PHI node. Since PBI is not the only
2219 // predecessor, compute the PHI'd conditional value for all of the preds.
2220 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foadd8b4fb42011-03-30 11:19:20 +00002221 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif62539832010-07-12 10:59:23 +00002222 BasicBlock *P = *PI;
2223 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00002224 PBI != BI && PBI->isConditional() &&
2225 PBI->getCondition() == BI->getCondition() &&
2226 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2227 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trick6b014382012-08-29 21:46:36 +00002228 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00002229 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00002230 } else {
Gabor Greif62539832010-07-12 10:59:23 +00002231 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00002232 }
Gabor Greif62539832010-07-12 10:59:23 +00002233 }
Andrew Trick6b014382012-08-29 21:46:36 +00002234
Chris Lattner867661a2008-07-13 21:53:26 +00002235 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00002236 return true;
2237 }
2238 }
Andrew Trick6b014382012-08-29 21:46:36 +00002239
Chris Lattner867661a2008-07-13 21:53:26 +00002240 // If this is a conditional branch in an empty block, and if any
2241 // predecessors is a conditional branch to one of our destinations,
2242 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00002243 BasicBlock::iterator BBI = BB->begin();
2244 // Ignore dbg intrinsics.
2245 while (isa<DbgInfoIntrinsic>(BBI))
2246 ++BBI;
2247 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00002248 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00002249
Andrew Trick6b014382012-08-29 21:46:36 +00002250
Chris Lattner63bf29b2009-01-20 01:15:41 +00002251 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2252 if (CE->canTrap())
2253 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002254
Chris Lattnerb8245122008-07-13 22:04:41 +00002255 int PBIOp, BIOp;
2256 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2257 PBIOp = BIOp = 0;
2258 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2259 PBIOp = 0, BIOp = 1;
2260 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2261 PBIOp = 1, BIOp = 0;
2262 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2263 PBIOp = BIOp = 1;
2264 else
2265 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002266
Chris Lattnerb8245122008-07-13 22:04:41 +00002267 // Check to make sure that the other destination of this branch
2268 // isn't BB itself. If so, this is an infinite loop that will
2269 // keep getting unwound.
2270 if (PBI->getSuccessor(PBIOp) == BB)
2271 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002272
2273 // Do not perform this transformation if it would require
Chris Lattnerb8245122008-07-13 22:04:41 +00002274 // insertion of a large number of select instructions. For targets
2275 // without predication/cmovs, this is a big pessimization.
2276 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Andrew Trick6b014382012-08-29 21:46:36 +00002277
Chris Lattnerb8245122008-07-13 22:04:41 +00002278 unsigned NumPhis = 0;
2279 for (BasicBlock::iterator II = CommonDest->begin();
2280 isa<PHINode>(II); ++II, ++NumPhis)
2281 if (NumPhis > 2) // Disable this xform.
2282 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002283
Chris Lattnerb8245122008-07-13 22:04:41 +00002284 // Finally, if everything is ok, fold the branches to logical ops.
2285 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trick6b014382012-08-29 21:46:36 +00002286
David Greene89d6fd32010-01-05 01:26:52 +00002287 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00002288 << "AND: " << *BI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002289
2290
Chris Lattner093a4382008-07-13 22:23:11 +00002291 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2292 // branch in it, where one edge (OtherDest) goes back to itself but the other
2293 // exits. We don't *know* that the program avoids the infinite loop
2294 // (even though that seems likely). If we do this xform naively, we'll end up
2295 // recursively unpeeling the loop. Since we know that (after the xform is
2296 // done) that the block *is* infinite if reached, we just make it an obviously
2297 // infinite loop with no cond branch.
2298 if (OtherDest == BB) {
2299 // Insert it at the end of the function, because it's either code,
2300 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00002301 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2302 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00002303 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2304 OtherDest = InfLoopBlock;
Andrew Trick6b014382012-08-29 21:46:36 +00002305 }
2306
David Greene89d6fd32010-01-05 01:26:52 +00002307 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Pateld3a17882011-05-19 20:52:46 +00002308
Chris Lattnerb8245122008-07-13 22:04:41 +00002309 // BI may have other predecessors. Because of this, we leave
2310 // it alone, but modify PBI.
Andrew Trick6b014382012-08-29 21:46:36 +00002311
Chris Lattnerb8245122008-07-13 22:04:41 +00002312 // Make sure we get to CommonDest on True&True directions.
2313 Value *PBICond = PBI->getCondition();
Devang Pateld3a17882011-05-19 20:52:46 +00002314 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattnerb8245122008-07-13 22:04:41 +00002315 if (PBIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00002316 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2317
Chris Lattnerb8245122008-07-13 22:04:41 +00002318 Value *BICond = BI->getCondition();
2319 if (BIOp)
Devang Pateld3a17882011-05-19 20:52:46 +00002320 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2321
Chris Lattnerb8245122008-07-13 22:04:41 +00002322 // Merge the conditions.
Devang Pateld3a17882011-05-19 20:52:46 +00002323 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trick6b014382012-08-29 21:46:36 +00002324
Chris Lattnerb8245122008-07-13 22:04:41 +00002325 // Modify PBI to branch on the new condition to the new dests.
2326 PBI->setCondition(Cond);
2327 PBI->setSuccessor(0, CommonDest);
2328 PBI->setSuccessor(1, OtherDest);
Andrew Trick6b014382012-08-29 21:46:36 +00002329
Manman Ren56654032012-09-17 21:30:40 +00002330 // Update branch weight for PBI.
2331 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2332 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2333 PredFalseWeight);
2334 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2335 SuccFalseWeight);
2336 if (PredHasWeights && SuccHasWeights) {
2337 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2338 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2339 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2340 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2341 // The weight to CommonDest should be PredCommon * SuccTotal +
2342 // PredOther * SuccCommon.
2343 // The weight to OtherDest should be PredOther * SuccOther.
2344 SmallVector<uint64_t, 2> NewWeights;
2345 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2346 PredOther * SuccCommon);
2347 NewWeights.push_back(PredOther * SuccOther);
2348 // Halve the weights if any of them cannot fit in an uint32_t
2349 FitWeights(NewWeights);
2350
2351 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2352 PBI->setMetadata(LLVMContext::MD_prof,
2353 MDBuilder(BI->getContext()).
2354 createBranchWeights(MDWeights));
2355 }
2356
Chris Lattnerb8245122008-07-13 22:04:41 +00002357 // OtherDest may have phi nodes. If so, add an entry from PBI's
2358 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00002359 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002360
Chris Lattnerb8245122008-07-13 22:04:41 +00002361 // We know that the CommonDest already had an edge from PBI to
2362 // it. If it has PHIs though, the PHIs may have different
2363 // entries for BB and PBI's BB. If so, insert a select to make
2364 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00002365 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00002366 for (BasicBlock::iterator II = CommonDest->begin();
2367 (PN = dyn_cast<PHINode>(II)); ++II) {
2368 Value *BIV = PN->getIncomingValueForBlock(BB);
2369 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2370 Value *PBIV = PN->getIncomingValue(PBBIdx);
2371 if (BIV != PBIV) {
2372 // Insert a select in PBI to pick the right value.
Devang Pateld3a17882011-05-19 20:52:46 +00002373 Value *NV = cast<SelectInst>
2374 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattnerb8245122008-07-13 22:04:41 +00002375 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00002376 }
2377 }
Andrew Trick6b014382012-08-29 21:46:36 +00002378
David Greene89d6fd32010-01-05 01:26:52 +00002379 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2380 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002381
Chris Lattnerb8245122008-07-13 22:04:41 +00002382 // This basic block is probably dead. We know it has at least
2383 // one fewer predecessor.
2384 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00002385}
2386
Frits van Bommel65fdded2011-01-11 12:52:11 +00002387// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2388// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2389// Takes care of updating the successors and removing the old terminator.
2390// Also makes sure not to introduce new successors by assuming that edges to
2391// non-successor TrueBBs and FalseBBs aren't reachable.
2392static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Renb11cbe62012-09-17 22:28:55 +00002393 BasicBlock *TrueBB, BasicBlock *FalseBB,
2394 uint32_t TrueWeight,
2395 uint32_t FalseWeight){
Frits van Bommel65fdded2011-01-11 12:52:11 +00002396 // Remove any superfluous successor edges from the CFG.
2397 // First, figure out which successors to preserve.
2398 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2399 // successor.
2400 BasicBlock *KeepEdge1 = TrueBB;
2401 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
2402
2403 // Then remove the rest.
2404 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2405 BasicBlock *Succ = OldTerm->getSuccessor(I);
2406 // Make sure only to keep exactly one copy of each edge.
2407 if (Succ == KeepEdge1)
2408 KeepEdge1 = 0;
2409 else if (Succ == KeepEdge2)
2410 KeepEdge2 = 0;
2411 else
2412 Succ->removePredecessor(OldTerm->getParent());
2413 }
2414
Devang Pateld3372b82011-05-18 18:43:31 +00002415 IRBuilder<> Builder(OldTerm);
2416 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2417
Frits van Bommel65fdded2011-01-11 12:52:11 +00002418 // Insert an appropriate new terminator.
2419 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
2420 if (TrueBB == FalseBB)
2421 // We were only looking for one successor, and it was present.
2422 // Create an unconditional branch to it.
Devang Pateld3372b82011-05-18 18:43:31 +00002423 Builder.CreateBr(TrueBB);
Manman Renb11cbe62012-09-17 22:28:55 +00002424 else {
Frits van Bommel65fdded2011-01-11 12:52:11 +00002425 // We found both of the successors we were looking for.
2426 // Create a conditional branch sharing the condition of the select.
Manman Renb11cbe62012-09-17 22:28:55 +00002427 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2428 if (TrueWeight != FalseWeight)
2429 NewBI->setMetadata(LLVMContext::MD_prof,
2430 MDBuilder(OldTerm->getContext()).
2431 createBranchWeights(TrueWeight, FalseWeight));
2432 }
Frits van Bommel65fdded2011-01-11 12:52:11 +00002433 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2434 // Neither of the selected blocks were successors, so this
2435 // terminator must be unreachable.
2436 new UnreachableInst(OldTerm->getContext(), OldTerm);
2437 } else {
2438 // One of the selected values was a successor, but the other wasn't.
2439 // Insert an unconditional branch to the one that was found;
2440 // the edge to the one that wasn't must be unreachable.
2441 if (KeepEdge1 == 0)
2442 // Only TrueBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002443 Builder.CreateBr(TrueBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002444 else
2445 // Only FalseBB was found.
Devang Pateld3372b82011-05-18 18:43:31 +00002446 Builder.CreateBr(FalseBB);
Frits van Bommel65fdded2011-01-11 12:52:11 +00002447 }
2448
2449 EraseTerminatorInstAndDCECond(OldTerm);
2450 return true;
2451}
2452
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002453// SimplifySwitchOnSelect - Replaces
2454// (switch (select cond, X, Y)) on constant X, Y
2455// with a branch - conditional if X and Y lead to distinct BBs,
2456// unconditional otherwise.
2457static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2458 // Check for constant integer values in the select.
2459 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2460 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2461 if (!TrueVal || !FalseVal)
2462 return false;
2463
2464 // Find the relevant condition and destinations.
2465 Value *Condition = Select->getCondition();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002466 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2467 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002468
Manman Renb11cbe62012-09-17 22:28:55 +00002469 // Get weight for TrueBB and FalseBB.
2470 uint32_t TrueWeight = 0, FalseWeight = 0;
2471 SmallVector<uint64_t, 8> Weights;
2472 bool HasWeights = HasBranchWeights(SI);
2473 if (HasWeights) {
2474 GetBranchWeights(SI, Weights);
2475 if (Weights.size() == 1 + SI->getNumCases()) {
2476 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2477 getSuccessorIndex()];
2478 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2479 getSuccessorIndex()];
2480 }
2481 }
2482
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002483 // Perform the actual simplification.
Manman Renb11cbe62012-09-17 22:28:55 +00002484 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2485 TrueWeight, FalseWeight);
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00002486}
2487
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002488// SimplifyIndirectBrOnSelect - Replaces
2489// (indirectbr (select cond, blockaddress(@fn, BlockA),
2490// blockaddress(@fn, BlockB)))
2491// with
2492// (br cond, BlockA, BlockB).
2493static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2494 // Check that both operands of the select are block addresses.
2495 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2496 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2497 if (!TBA || !FBA)
2498 return false;
2499
2500 // Extract the actual blocks.
2501 BasicBlock *TrueBB = TBA->getBasicBlock();
2502 BasicBlock *FalseBB = FBA->getBasicBlock();
2503
Frits van Bommel65fdded2011-01-11 12:52:11 +00002504 // Perform the actual simplification.
Manman Renb11cbe62012-09-17 22:28:55 +00002505 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2506 0, 0);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002507}
2508
Chris Lattner61c77442010-12-13 03:18:54 +00002509/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2510/// instruction (a seteq/setne with a constant) as the only instruction in a
2511/// block that ends with an uncond branch. We are looking for a very specific
2512/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2513/// this case, we merge the first two "or's of icmp" into a switch, but then the
2514/// default value goes to an uncond block with a seteq in it, we get something
2515/// like:
2516///
2517/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2518/// DEFAULT:
2519/// %tmp = icmp eq i8 %A, 92
2520/// br label %end
2521/// end:
2522/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trick6b014382012-08-29 21:46:36 +00002523///
Chris Lattner61c77442010-12-13 03:18:54 +00002524/// We prefer to split the edge to 'end' so that there is a true/false entry to
2525/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002526static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
Micah Villmow3574eca2012-10-08 16:38:25 +00002527 const DataLayout *TD,
Devang Patela23812c2011-05-18 18:28:48 +00002528 IRBuilder<> &Builder) {
Chris Lattner61c77442010-12-13 03:18:54 +00002529 BasicBlock *BB = ICI->getParent();
Devang Patela23812c2011-05-18 18:28:48 +00002530
Chris Lattner61c77442010-12-13 03:18:54 +00002531 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2532 // complex.
2533 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2534
2535 Value *V = ICI->getOperand(0);
2536 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trick6b014382012-08-29 21:46:36 +00002537
Chris Lattner61c77442010-12-13 03:18:54 +00002538 // The pattern we're looking for is where our only predecessor is a switch on
2539 // 'V' and this block is the default case for the switch. In this case we can
2540 // fold the compared value into the switch to simplify things.
2541 BasicBlock *Pred = BB->getSinglePredecessor();
2542 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002543
Chris Lattner61c77442010-12-13 03:18:54 +00002544 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2545 if (SI->getCondition() != V)
2546 return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002547
Chris Lattner61c77442010-12-13 03:18:54 +00002548 // If BB is reachable on a non-default case, then we simply know the value of
2549 // V in this block. Substitute it and constant fold the icmp instruction
2550 // away.
2551 if (SI->getDefaultDest() != BB) {
2552 ConstantInt *VVal = SI->findCaseDest(BB);
2553 assert(VVal && "Should have a unique destination value");
2554 ICI->setOperand(0, VVal);
Andrew Trick6b014382012-08-29 21:46:36 +00002555
Chris Lattner302ba6f2010-12-14 06:17:25 +00002556 if (Value *V = SimplifyInstruction(ICI, TD)) {
2557 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00002558 ICI->eraseFromParent();
2559 }
2560 // BB is now empty, so it is likely to simplify away.
2561 return SimplifyCFG(BB) | true;
2562 }
Andrew Trick6b014382012-08-29 21:46:36 +00002563
Chris Lattnerabf70672010-12-13 03:43:57 +00002564 // Ok, the block is reachable from the default dest. If the constant we're
2565 // comparing exists in one of the other edges, then we can constant fold ICI
2566 // and zap it.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002567 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattnerabf70672010-12-13 03:43:57 +00002568 Value *V;
2569 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2570 V = ConstantInt::getFalse(BB->getContext());
2571 else
2572 V = ConstantInt::getTrue(BB->getContext());
Andrew Trick6b014382012-08-29 21:46:36 +00002573
Chris Lattnerabf70672010-12-13 03:43:57 +00002574 ICI->replaceAllUsesWith(V);
2575 ICI->eraseFromParent();
2576 // BB is now empty, so it is likely to simplify away.
2577 return SimplifyCFG(BB) | true;
2578 }
Andrew Trick6b014382012-08-29 21:46:36 +00002579
Chris Lattner61c77442010-12-13 03:18:54 +00002580 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2581 // the block.
2582 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2583 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
2584 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
2585 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2586 return false;
2587
2588 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2589 // true in the PHI.
2590 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2591 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2592
2593 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2594 std::swap(DefaultCst, NewCst);
2595
2596 // Replace ICI (which is used by the PHI for the default value) with true or
2597 // false depending on if it is EQ or NE.
2598 ICI->replaceAllUsesWith(DefaultCst);
2599 ICI->eraseFromParent();
2600
2601 // Okay, the switch goes to this block on a default value. Add an edge from
2602 // the switch to the merge point on the compared value.
2603 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2604 BB->getParent(), BB);
Manman Renb0102772012-09-17 23:07:43 +00002605 SmallVector<uint64_t, 8> Weights;
2606 bool HasWeights = HasBranchWeights(SI);
2607 if (HasWeights) {
2608 GetBranchWeights(SI, Weights);
2609 if (Weights.size() == 1 + SI->getNumCases()) {
2610 // Split weight for default case to case for "Cst".
2611 Weights[0] = (Weights[0]+1) >> 1;
2612 Weights.push_back(Weights[0]);
2613
2614 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2615 SI->setMetadata(LLVMContext::MD_prof,
2616 MDBuilder(SI->getContext()).
2617 createBranchWeights(MDWeights));
2618 }
2619 }
Chris Lattner61c77442010-12-13 03:18:54 +00002620 SI->addCase(Cst, NewBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002621
Chris Lattner61c77442010-12-13 03:18:54 +00002622 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patela23812c2011-05-18 18:28:48 +00002623 Builder.SetInsertPoint(NewBB);
2624 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2625 Builder.CreateBr(SuccBlock);
Chris Lattner61c77442010-12-13 03:18:54 +00002626 PHIUse->addIncoming(NewCst, NewBB);
2627 return true;
2628}
2629
Chris Lattner97fdb892010-12-13 05:03:41 +00002630/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2631/// Check to see if it is branching on an or/and chain of icmp instructions, and
2632/// fold it into a switch instruction if so.
Micah Villmow3574eca2012-10-08 16:38:25 +00002633static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *TD,
Devang Patel02dd5412011-05-18 23:18:47 +00002634 IRBuilder<> &Builder) {
Chris Lattner97fdb892010-12-13 05:03:41 +00002635 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2636 if (Cond == 0) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002637
2638
Chris Lattner97fdb892010-12-13 05:03:41 +00002639 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2640 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2641 // 'setne's and'ed together, collect them.
2642 Value *CompVal = 0;
2643 std::vector<ConstantInt*> Values;
2644 bool TrueWhenEqual = true;
2645 Value *ExtraCase = 0;
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002646 unsigned UsedICmps = 0;
Andrew Trick6b014382012-08-29 21:46:36 +00002647
Chris Lattner97fdb892010-12-13 05:03:41 +00002648 if (Cond->getOpcode() == Instruction::Or) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002649 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
2650 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002651 } else if (Cond->getOpcode() == Instruction::And) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002652 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
2653 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00002654 TrueWhenEqual = false;
2655 }
Andrew Trick6b014382012-08-29 21:46:36 +00002656
Chris Lattner97fdb892010-12-13 05:03:41 +00002657 // If we didn't have a multiply compared value, fail.
2658 if (CompVal == 0) return false;
2659
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002660 // Avoid turning single icmps into a switch.
2661 if (UsedICmps <= 1)
2662 return false;
2663
Chris Lattner97fdb892010-12-13 05:03:41 +00002664 // There might be duplicate constants in the list, which the switch
2665 // instruction can't handle, remove them now.
2666 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2667 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trick6b014382012-08-29 21:46:36 +00002668
Chris Lattner97fdb892010-12-13 05:03:41 +00002669 // If Extra was used, we require at least two switch values to do the
2670 // transformation. A switch with one value is just an cond branch.
2671 if (ExtraCase && Values.size() < 2) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002672
Andrew Trickb1b97832012-08-29 21:46:38 +00002673 // TODO: Preserve branch weight metadata, similarly to how
2674 // FoldValueComparisonIntoPredecessors preserves it.
2675
Chris Lattner97fdb892010-12-13 05:03:41 +00002676 // Figure out which block is which destination.
2677 BasicBlock *DefaultBB = BI->getSuccessor(1);
2678 BasicBlock *EdgeBB = BI->getSuccessor(0);
2679 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002680
Chris Lattner97fdb892010-12-13 05:03:41 +00002681 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002682
Chris Lattner302ba6f2010-12-14 06:17:25 +00002683 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00002684 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trick6b014382012-08-29 21:46:36 +00002685
Chris Lattner97fdb892010-12-13 05:03:41 +00002686 // If there are any extra values that couldn't be folded into the switch
2687 // then we evaluate them with an explicit branch first. Split the block
2688 // right before the condbr to handle it.
2689 if (ExtraCase) {
2690 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2691 // Remove the uncond branch added to the old block.
2692 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel02dd5412011-05-18 23:18:47 +00002693 Builder.SetInsertPoint(OldTI);
2694
Chris Lattner117f8cf2010-12-14 05:57:30 +00002695 if (TrueWhenEqual)
Devang Patel02dd5412011-05-18 23:18:47 +00002696 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002697 else
Devang Patel02dd5412011-05-18 23:18:47 +00002698 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002699
Chris Lattner97fdb892010-12-13 05:03:41 +00002700 OldTI->eraseFromParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002701
Chris Lattner97bd89e2010-12-13 05:34:18 +00002702 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2703 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00002704 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002705
Chris Lattner302ba6f2010-12-14 06:17:25 +00002706 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2707 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00002708 BB = NewBB;
2709 }
Devang Patel02dd5412011-05-18 23:18:47 +00002710
2711 Builder.SetInsertPoint(BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00002712 // Convert pointer to int before we switch.
2713 if (CompVal->getType()->isPointerTy()) {
Micah Villmow3574eca2012-10-08 16:38:25 +00002714 assert(TD && "Cannot switch on pointer without DataLayout");
Devang Patel02dd5412011-05-18 23:18:47 +00002715 CompVal = Builder.CreatePtrToInt(CompVal,
Micah Villmowaa76e9e2012-10-24 15:52:52 +00002716 TD->getIntPtrType(CompVal->getType()),
Devang Patel02dd5412011-05-18 23:18:47 +00002717 "magicptr");
Chris Lattner97fdb892010-12-13 05:03:41 +00002718 }
Andrew Trick6b014382012-08-29 21:46:36 +00002719
Chris Lattner97fdb892010-12-13 05:03:41 +00002720 // Create the new switch instruction now.
Devang Patel02dd5412011-05-18 23:18:47 +00002721 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Pateld80e8ed2011-05-17 23:29:05 +00002722
Chris Lattner97fdb892010-12-13 05:03:41 +00002723 // Add all of the 'cases' to the switch instruction.
2724 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2725 New->addCase(Values[i], EdgeBB);
Andrew Trick6b014382012-08-29 21:46:36 +00002726
Chris Lattner97fdb892010-12-13 05:03:41 +00002727 // We added edges from PI to the EdgeBB. As such, if there were any
2728 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2729 // the number of edges added.
2730 for (BasicBlock::iterator BBI = EdgeBB->begin();
2731 isa<PHINode>(BBI); ++BBI) {
2732 PHINode *PN = cast<PHINode>(BBI);
2733 Value *InVal = PN->getIncomingValueForBlock(BB);
2734 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2735 PN->addIncoming(InVal, BB);
2736 }
Andrew Trick6b014382012-08-29 21:46:36 +00002737
Chris Lattner97fdb892010-12-13 05:03:41 +00002738 // Erase the old branch instruction.
2739 EraseTerminatorInstAndDCECond(BI);
Andrew Trick6b014382012-08-29 21:46:36 +00002740
Chris Lattner302ba6f2010-12-14 06:17:25 +00002741 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00002742 return true;
2743}
2744
Duncan Sandsad99ef82011-09-05 12:57:57 +00002745bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2746 // If this is a trivial landing pad that just continues unwinding the caught
2747 // exception then zap the landing pad, turning its invokes into calls.
2748 BasicBlock *BB = RI->getParent();
2749 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2750 if (RI->getValue() != LPInst)
2751 // Not a landing pad, or the resume is not unwinding the exception that
2752 // caused control to branch here.
2753 return false;
2754
2755 // Check that there are no other instructions except for debug intrinsics.
2756 BasicBlock::iterator I = LPInst, E = RI;
2757 while (++I != E)
2758 if (!isa<DbgInfoIntrinsic>(I))
2759 return false;
2760
2761 // Turn all invokes that unwind here into calls and delete the basic block.
2762 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2763 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2764 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2765 // Insert a call instruction before the invoke.
2766 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2767 Call->takeName(II);
2768 Call->setCallingConv(II->getCallingConv());
2769 Call->setAttributes(II->getAttributes());
2770 Call->setDebugLoc(II->getDebugLoc());
2771
2772 // Anything that used the value produced by the invoke instruction now uses
2773 // the value produced by the call instruction. Note that we do this even
2774 // for void functions and calls with no uses so that the callgraph edge is
2775 // updated.
2776 II->replaceAllUsesWith(Call);
2777 BB->removePredecessor(II->getParent());
2778
2779 // Insert a branch to the normal destination right before the invoke.
2780 BranchInst::Create(II->getNormalDest(), II);
2781
2782 // Finally, delete the invoke instruction!
2783 II->eraseFromParent();
2784 }
2785
2786 // The landingpad is now unreachable. Zap it.
2787 BB->eraseFromParent();
2788 return true;
2789}
2790
Devang Patel176ec402011-05-18 21:33:11 +00002791bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00002792 BasicBlock *BB = RI->getParent();
2793 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trick6b014382012-08-29 21:46:36 +00002794
Chris Lattner3d512132010-12-13 06:25:44 +00002795 // Find predecessors that end with branches.
2796 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2797 SmallVector<BranchInst*, 8> CondBranchPreds;
2798 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2799 BasicBlock *P = *PI;
2800 TerminatorInst *PTI = P->getTerminator();
2801 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2802 if (BI->isUnconditional())
2803 UncondBranchPreds.push_back(P);
2804 else
2805 CondBranchPreds.push_back(BI);
2806 }
2807 }
Andrew Trick6b014382012-08-29 21:46:36 +00002808
Chris Lattner3d512132010-12-13 06:25:44 +00002809 // If we found some, do the transformation!
Evan Chengc3f507f2011-01-29 04:46:23 +00002810 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner3d512132010-12-13 06:25:44 +00002811 while (!UncondBranchPreds.empty()) {
2812 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2813 DEBUG(dbgs() << "FOLDING: " << *BB
2814 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengc3f507f2011-01-29 04:46:23 +00002815 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner3d512132010-12-13 06:25:44 +00002816 }
Andrew Trick6b014382012-08-29 21:46:36 +00002817
Chris Lattner3d512132010-12-13 06:25:44 +00002818 // If we eliminated all predecessors of the block, delete the block now.
2819 if (pred_begin(BB) == pred_end(BB))
2820 // We know there are no successors, so just nuke the block.
2821 BB->eraseFromParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002822
Chris Lattner3d512132010-12-13 06:25:44 +00002823 return true;
2824 }
Andrew Trick6b014382012-08-29 21:46:36 +00002825
Chris Lattner3d512132010-12-13 06:25:44 +00002826 // Check out all of the conditional branches going to this return
2827 // instruction. If any of them just select between returns, change the
2828 // branch itself into a select/return pair.
2829 while (!CondBranchPreds.empty()) {
2830 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trick6b014382012-08-29 21:46:36 +00002831
Chris Lattner3d512132010-12-13 06:25:44 +00002832 // Check to see if the non-BB successor is also a return block.
2833 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2834 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Patel176ec402011-05-18 21:33:11 +00002835 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00002836 return true;
2837 }
2838 return false;
2839}
2840
Chris Lattner3d512132010-12-13 06:25:44 +00002841bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2842 BasicBlock *BB = UI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00002843
Chris Lattner3d512132010-12-13 06:25:44 +00002844 bool Changed = false;
Andrew Trick6b014382012-08-29 21:46:36 +00002845
Chris Lattner3d512132010-12-13 06:25:44 +00002846 // If there are any instructions immediately before the unreachable that can
2847 // be removed, do so.
2848 while (UI != BB->begin()) {
2849 BasicBlock::iterator BBI = UI;
2850 --BBI;
Eli Friedman81763882011-08-15 23:59:28 +00002851 // Do not delete instructions that can have side effects which might cause
2852 // the unreachable to not be reachable; specifically, calls and volatile
2853 // operations may have this effect.
Chris Lattner3d512132010-12-13 06:25:44 +00002854 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman81763882011-08-15 23:59:28 +00002855
2856 if (BBI->mayHaveSideEffects()) {
2857 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2858 if (SI->isVolatile())
2859 break;
2860 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2861 if (LI->isVolatile())
2862 break;
2863 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2864 if (RMWI->isVolatile())
2865 break;
2866 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2867 if (CXI->isVolatile())
2868 break;
2869 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2870 !isa<LandingPadInst>(BBI)) {
Chris Lattner3d512132010-12-13 06:25:44 +00002871 break;
Eli Friedman81763882011-08-15 23:59:28 +00002872 }
Bill Wendling23b49ba2011-08-16 20:41:17 +00002873 // Note that deleting LandingPad's here is in fact okay, although it
2874 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2875 // all the predecessors of this block will be the unwind edges of Invokes,
2876 // and we can therefore guarantee this block will be erased.
Eli Friedman81763882011-08-15 23:59:28 +00002877 }
2878
Eli Friedman2adc5b62011-03-09 00:48:33 +00002879 // Delete this instruction (any uses are guaranteed to be dead)
2880 if (!BBI->use_empty())
2881 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattner302ba6f2010-12-14 06:17:25 +00002882 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002883 Changed = true;
2884 }
Andrew Trick6b014382012-08-29 21:46:36 +00002885
Chris Lattner3d512132010-12-13 06:25:44 +00002886 // If the unreachable instruction is the first in the block, take a gander
2887 // at all of the predecessors of this instruction, and simplify them.
2888 if (&BB->front() != UI) return Changed;
Andrew Trick6b014382012-08-29 21:46:36 +00002889
Chris Lattner3d512132010-12-13 06:25:44 +00002890 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2891 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2892 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel1aa89a22011-05-19 00:09:21 +00002893 IRBuilder<> Builder(TI);
Chris Lattner3d512132010-12-13 06:25:44 +00002894 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2895 if (BI->isUnconditional()) {
2896 if (BI->getSuccessor(0) == BB) {
2897 new UnreachableInst(TI->getContext(), TI);
2898 TI->eraseFromParent();
2899 Changed = true;
2900 }
2901 } else {
2902 if (BI->getSuccessor(0) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002903 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner3d512132010-12-13 06:25:44 +00002904 EraseTerminatorInstAndDCECond(BI);
2905 } else if (BI->getSuccessor(1) == BB) {
Devang Patel1aa89a22011-05-19 00:09:21 +00002906 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner3d512132010-12-13 06:25:44 +00002907 EraseTerminatorInstAndDCECond(BI);
2908 Changed = true;
2909 }
2910 }
2911 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002912 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002913 i != e; ++i)
2914 if (i.getCaseSuccessor() == BB) {
Chris Lattner3d512132010-12-13 06:25:44 +00002915 BB->removePredecessor(SI->getParent());
2916 SI->removeCase(i);
2917 --i; --e;
2918 Changed = true;
2919 }
2920 // If the default value is unreachable, figure out the most popular
2921 // destination and make it the default.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002922 if (SI->getDefaultDest() == BB) {
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002923 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002924 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002925 i != e; ++i) {
Nick Lewycky9d523102011-12-26 20:37:40 +00002926 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002927 Popularity[i.getCaseSuccessor()];
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002928 if (entry.first == 0) {
2929 entry.first = 1;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002930 entry.second = i.getCaseIndex();
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002931 } else {
2932 entry.first++;
2933 }
2934 }
2935
Chris Lattner3d512132010-12-13 06:25:44 +00002936 // Find the most popular block.
2937 unsigned MaxPop = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002938 unsigned MaxIndex = 0;
Chris Lattner3d512132010-12-13 06:25:44 +00002939 BasicBlock *MaxBlock = 0;
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002940 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner3d512132010-12-13 06:25:44 +00002941 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trick6b014382012-08-29 21:46:36 +00002942 if (I->second.first > MaxPop ||
Eli Friedmanb1a6eab2011-03-15 02:23:35 +00002943 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
2944 MaxPop = I->second.first;
2945 MaxIndex = I->second.second;
Chris Lattner3d512132010-12-13 06:25:44 +00002946 MaxBlock = I->first;
2947 }
2948 }
2949 if (MaxBlock) {
2950 // Make this the new default, allowing us to delete any explicit
2951 // edges to it.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002952 SI->setDefaultDest(MaxBlock);
Chris Lattner3d512132010-12-13 06:25:44 +00002953 Changed = true;
Andrew Trick6b014382012-08-29 21:46:36 +00002954
Chris Lattner3d512132010-12-13 06:25:44 +00002955 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2956 // it.
2957 if (isa<PHINode>(MaxBlock->begin()))
2958 for (unsigned i = 0; i != MaxPop-1; ++i)
2959 MaxBlock->removePredecessor(SI->getParent());
Andrew Trick6b014382012-08-29 21:46:36 +00002960
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002961 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002962 i != e; ++i)
2963 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner3d512132010-12-13 06:25:44 +00002964 SI->removeCase(i);
2965 --i; --e;
2966 }
2967 }
2968 }
2969 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2970 if (II->getUnwindDest() == BB) {
2971 // Convert the invoke to a call instruction. This would be a good
2972 // place to note that the call does not throw though.
Devang Patel1aa89a22011-05-19 00:09:21 +00002973 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner3d512132010-12-13 06:25:44 +00002974 II->removeFromParent(); // Take out of symbol table
Andrew Trick6b014382012-08-29 21:46:36 +00002975
Chris Lattner3d512132010-12-13 06:25:44 +00002976 // Insert the call now...
2977 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel1aa89a22011-05-19 00:09:21 +00002978 Builder.SetInsertPoint(BI);
2979 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foada3efbb12011-07-15 08:37:34 +00002980 Args, II->getName());
Chris Lattner3d512132010-12-13 06:25:44 +00002981 CI->setCallingConv(II->getCallingConv());
2982 CI->setAttributes(II->getAttributes());
2983 // If the invoke produced a value, the call does now instead.
2984 II->replaceAllUsesWith(CI);
2985 delete II;
2986 Changed = true;
2987 }
2988 }
2989 }
Andrew Trick6b014382012-08-29 21:46:36 +00002990
Chris Lattner3d512132010-12-13 06:25:44 +00002991 // If this block is now dead, remove it.
2992 if (pred_begin(BB) == pred_end(BB) &&
2993 BB != &BB->getParent()->getEntryBlock()) {
2994 // We know there are no successors, so just nuke the block.
2995 BB->eraseFromParent();
2996 return true;
2997 }
2998
2999 return Changed;
3000}
3001
Benjamin Kramer56442df2011-02-02 15:56:22 +00003002/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3003/// integer range comparison into a sub, an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00003004static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003005 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramer56442df2011-02-02 15:56:22 +00003006
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003007 // Make sure all cases point to the same destination and gather the values.
3008 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003009 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003010 Cases.push_back(I.getCaseValue());
3011 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003012 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003013 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003014 return false;
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003015 Cases.push_back(I.getCaseValue());
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003016 }
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003017 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer042b27f2011-02-03 22:51:41 +00003018
3019 // Sort the case values, then check if they form a range we can transform.
3020 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3021 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3022 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3023 return false;
3024 }
3025
3026 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003027 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramer56442df2011-02-02 15:56:22 +00003028
Benjamin Kramer33828bc2011-02-07 22:37:28 +00003029 Value *Sub = SI->getCondition();
3030 if (!Offset->isNullValue())
Devang Patel1f5812b2011-05-19 00:13:33 +00003031 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3032 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren222d6192012-09-18 00:47:33 +00003033 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003034 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramer56442df2011-02-02 15:56:22 +00003035
Manman Ren222d6192012-09-18 00:47:33 +00003036 // Update weight for the newly-created conditional branch.
3037 SmallVector<uint64_t, 8> Weights;
3038 bool HasWeights = HasBranchWeights(SI);
3039 if (HasWeights) {
3040 GetBranchWeights(SI, Weights);
3041 if (Weights.size() == 1 + SI->getNumCases()) {
3042 // Combine all weights for the cases to be the true weight of NewBI.
3043 // We assume that the sum of all weights for a Terminator can fit into 32
3044 // bits.
3045 uint32_t NewTrueWeight = 0;
3046 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3047 NewTrueWeight += (uint32_t)Weights[I];
3048 NewBI->setMetadata(LLVMContext::MD_prof,
3049 MDBuilder(SI->getContext()).
3050 createBranchWeights(NewTrueWeight,
3051 (uint32_t)Weights[0]));
3052 }
3053 }
3054
Benjamin Kramer56442df2011-02-02 15:56:22 +00003055 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003056 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramer56442df2011-02-02 15:56:22 +00003057 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003058 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramer56442df2011-02-02 15:56:22 +00003059 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3060 }
3061 SI->eraseFromParent();
3062
3063 return true;
3064}
Chris Lattner3d512132010-12-13 06:25:44 +00003065
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003066/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3067/// and use it to remove dead cases.
3068static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3069 Value *Cond = SI->getCondition();
3070 unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
3071 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00003072 ComputeMaskedBits(Cond, KnownZero, KnownOne);
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003073
3074 // Gather dead cases.
3075 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003076 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003077 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3078 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3079 DeadCases.push_back(I.getCaseValue());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003080 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003081 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003082 }
3083 }
3084
Manman Ren222d6192012-09-18 00:47:33 +00003085 SmallVector<uint64_t, 8> Weights;
3086 bool HasWeight = HasBranchWeights(SI);
3087 if (HasWeight) {
3088 GetBranchWeights(SI, Weights);
3089 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3090 }
3091
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003092 // Remove dead cases from the switch.
3093 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003094 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003095 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00003096 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren222d6192012-09-18 00:47:33 +00003097 if (HasWeight) {
3098 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3099 Weights.pop_back();
3100 }
3101
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003102 // Prune unused values from PHI nodes.
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003103 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003104 SI->removeCase(Case);
3105 }
Manman Ren222d6192012-09-18 00:47:33 +00003106 if (HasWeight) {
3107 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3108 SI->setMetadata(LLVMContext::MD_prof,
3109 MDBuilder(SI->getParent()->getContext()).
3110 createBranchWeights(MDWeights));
3111 }
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003112
3113 return !DeadCases.empty();
3114}
3115
Hans Wennborg448da512011-06-18 10:28:47 +00003116/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3117/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3118/// by an unconditional branch), look at the phi node for BB in the successor
3119/// block and see if the incoming value is equal to CaseValue. If so, return
3120/// the phi node, and set PhiIndex to BB's index in the phi node.
3121static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3122 BasicBlock *BB,
3123 int *PhiIndex) {
3124 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3125 return NULL; // BB must be empty to be a candidate for simplification.
3126 if (!BB->getSinglePredecessor())
3127 return NULL; // BB must be dominated by the switch.
3128
3129 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3130 if (!Branch || !Branch->isUnconditional())
3131 return NULL; // Terminator must be unconditional branch.
3132
3133 BasicBlock *Succ = Branch->getSuccessor(0);
3134
3135 BasicBlock::iterator I = Succ->begin();
3136 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3137 int Idx = PHI->getBasicBlockIndex(BB);
3138 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3139
3140 Value *InValue = PHI->getIncomingValue(Idx);
3141 if (InValue != CaseValue) continue;
3142
3143 *PhiIndex = Idx;
3144 return PHI;
3145 }
3146
3147 return NULL;
3148}
3149
3150/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3151/// instruction to a phi node dominated by the switch, if that would mean that
3152/// some of the destination blocks of the switch can be folded away.
3153/// Returns true if a change is made.
3154static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3155 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3156 ForwardingNodesMap ForwardingNodes;
3157
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00003158 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00003159 ConstantInt *CaseValue = I.getCaseValue();
3160 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg448da512011-06-18 10:28:47 +00003161
3162 int PhiIndex;
3163 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3164 &PhiIndex);
3165 if (!PHI) continue;
3166
3167 ForwardingNodes[PHI].push_back(PhiIndex);
3168 }
3169
3170 bool Changed = false;
3171
3172 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3173 E = ForwardingNodes.end(); I != E; ++I) {
3174 PHINode *Phi = I->first;
3175 SmallVector<int,4> &Indexes = I->second;
3176
3177 if (Indexes.size() < 2) continue;
3178
3179 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3180 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3181 Changed = true;
3182 }
3183
3184 return Changed;
3185}
3186
Hans Wennborg486270a2012-09-06 09:43:28 +00003187/// ValidLookupTableConstant - Return true if the backend will be able to handle
3188/// initializing an array of constants like C.
Hans Wennborgbf015822012-09-07 08:22:57 +00003189static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg486270a2012-09-06 09:43:28 +00003190 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3191 return CE->isGEPWithNoNotionalOverIndexing();
3192
3193 return isa<ConstantFP>(C) ||
3194 isa<ConstantInt>(C) ||
3195 isa<ConstantPointerNull>(C) ||
3196 isa<GlobalValue>(C) ||
3197 isa<UndefValue>(C);
3198}
3199
3200/// GetCaseResulsts - Try to determine the resulting constant values in phi
3201/// nodes at the common destination basic block for one of the case
3202/// destinations of a switch instruction.
3203static bool GetCaseResults(SwitchInst *SI,
3204 BasicBlock *CaseDest,
3205 BasicBlock **CommonDest,
3206 SmallVector<std::pair<PHINode*,Constant*>, 4> &Res) {
3207 // The block from which we enter the common destination.
3208 BasicBlock *Pred = SI->getParent();
3209
3210 // If CaseDest is empty, continue to its successor.
3211 if (CaseDest->getFirstNonPHIOrDbg() == CaseDest->getTerminator() &&
3212 !isa<PHINode>(CaseDest->begin())) {
3213
3214 TerminatorInst *Terminator = CaseDest->getTerminator();
3215 if (Terminator->getNumSuccessors() != 1)
3216 return false;
3217
3218 Pred = CaseDest;
3219 CaseDest = Terminator->getSuccessor(0);
3220 }
3221
3222 // If we did not have a CommonDest before, use the current one.
3223 if (!*CommonDest)
3224 *CommonDest = CaseDest;
3225 // If the destination isn't the common one, abort.
3226 if (CaseDest != *CommonDest)
3227 return false;
3228
3229 // Get the values for this case from phi nodes in the destination block.
3230 BasicBlock::iterator I = (*CommonDest)->begin();
3231 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3232 int Idx = PHI->getBasicBlockIndex(Pred);
3233 if (Idx == -1)
3234 continue;
3235
3236 Constant *ConstVal = dyn_cast<Constant>(PHI->getIncomingValue(Idx));
3237 if (!ConstVal)
3238 return false;
3239
3240 // Be conservative about which kinds of constants we support.
3241 if (!ValidLookupTableConstant(ConstVal))
3242 return false;
3243
3244 Res.push_back(std::make_pair(PHI, ConstVal));
3245 }
3246
3247 return true;
3248}
3249
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003250namespace {
3251 /// SwitchLookupTable - This class represents a lookup table that can be used
3252 /// to replace a switch.
3253 class SwitchLookupTable {
3254 public:
3255 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3256 /// with the contents of Values, using DefaultValue to fill any holes in the
3257 /// table.
3258 SwitchLookupTable(Module &M,
3259 uint64_t TableSize,
3260 ConstantInt *Offset,
3261 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003262 Constant *DefaultValue,
Micah Villmow3574eca2012-10-08 16:38:25 +00003263 const DataLayout *TD);
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003264
3265 /// BuildLookup - Build instructions with Builder to retrieve the value at
3266 /// the position given by Index in the lookup table.
3267 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3268
Hans Wennborgd72271c2012-09-26 09:44:49 +00003269 /// WouldFitInRegister - Return true if a table with TableSize elements of
3270 /// type ElementType would fit in a target-legal register.
Micah Villmow3574eca2012-10-08 16:38:25 +00003271 static bool WouldFitInRegister(const DataLayout *TD,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003272 uint64_t TableSize,
3273 const Type *ElementType);
3274
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003275 private:
3276 // Depending on the contents of the table, it can be represented in
3277 // different ways.
3278 enum {
3279 // For tables where each element contains the same value, we just have to
3280 // store that single value and return it for each lookup.
3281 SingleValueKind,
3282
Hans Wennborgd72271c2012-09-26 09:44:49 +00003283 // For small tables with integer elements, we can pack them into a bitmap
3284 // that fits into a target-legal register. Values are retrieved by
3285 // shift and mask operations.
3286 BitMapKind,
3287
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003288 // The table is stored as an array of values. Values are retrieved by load
3289 // instructions from the table.
3290 ArrayKind
3291 } Kind;
3292
3293 // For SingleValueKind, this is the single value.
3294 Constant *SingleValue;
3295
Hans Wennborgd72271c2012-09-26 09:44:49 +00003296 // For BitMapKind, this is the bitmap.
3297 ConstantInt *BitMap;
3298 IntegerType *BitMapElementTy;
3299
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003300 // For ArrayKind, this is the array.
3301 GlobalVariable *Array;
3302 };
3303}
3304
3305SwitchLookupTable::SwitchLookupTable(Module &M,
3306 uint64_t TableSize,
3307 ConstantInt *Offset,
3308 const SmallVector<std::pair<ConstantInt*, Constant*>, 4>& Values,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003309 Constant *DefaultValue,
Micah Villmow3574eca2012-10-08 16:38:25 +00003310 const DataLayout *TD) {
Hans Wennborg565df792012-09-26 11:07:37 +00003311 assert(Values.size() && "Can't build lookup table without values!");
3312 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg486270a2012-09-06 09:43:28 +00003313
3314 // If all values in the table are equal, this is that value.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003315 SingleValue = Values.begin()->second;
Hans Wennborg486270a2012-09-06 09:43:28 +00003316
3317 // Build up the table contents.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003318 SmallVector<Constant*, 64> TableContents(TableSize);
3319 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3320 ConstantInt *CaseVal = Values[I].first;
3321 Constant *CaseRes = Values[I].second;
3322 assert(CaseRes->getType() == DefaultValue->getType());
Hans Wennborg486270a2012-09-06 09:43:28 +00003323
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003324 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3325 .getLimitedValue();
Hans Wennborg486270a2012-09-06 09:43:28 +00003326 TableContents[Idx] = CaseRes;
3327
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003328 if (CaseRes != SingleValue)
3329 SingleValue = NULL;
Hans Wennborg486270a2012-09-06 09:43:28 +00003330 }
3331
3332 // Fill in any holes in the table with the default result.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003333 if (Values.size() < TableSize) {
3334 for (uint64_t I = 0; I < TableSize; ++I) {
3335 if (!TableContents[I])
3336 TableContents[I] = DefaultValue;
Hans Wennborg486270a2012-09-06 09:43:28 +00003337 }
3338
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003339 if (DefaultValue != SingleValue)
3340 SingleValue = NULL;
Hans Wennborg486270a2012-09-06 09:43:28 +00003341 }
3342
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003343 // If each element in the table contains the same value, we only need to store
3344 // that single value.
3345 if (SingleValue) {
3346 Kind = SingleValueKind;
3347 return;
Hans Wennborg486270a2012-09-06 09:43:28 +00003348 }
3349
Hans Wennborgd72271c2012-09-26 09:44:49 +00003350 // If the type is integer and the table fits in a register, build a bitmap.
3351 if (WouldFitInRegister(TD, TableSize, DefaultValue->getType())) {
3352 IntegerType *IT = cast<IntegerType>(DefaultValue->getType());
3353 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3354 for (uint64_t I = TableSize; I > 0; --I) {
3355 TableInt <<= IT->getBitWidth();
Benjamin Kramer64f27e72012-10-01 11:31:48 +00003356 // Insert values into the bitmap. Undef values are set to zero.
3357 if (!isa<UndefValue>(TableContents[I - 1])) {
3358 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3359 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3360 }
Hans Wennborgd72271c2012-09-26 09:44:49 +00003361 }
3362 BitMap = ConstantInt::get(M.getContext(), TableInt);
3363 BitMapElementTy = IT;
3364 Kind = BitMapKind;
3365 ++NumBitMaps;
3366 return;
3367 }
3368
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003369 // Store the table in an array.
3370 ArrayType *ArrayTy = ArrayType::get(DefaultValue->getType(), TableSize);
Hans Wennborg486270a2012-09-06 09:43:28 +00003371 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3372
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003373 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3374 GlobalVariable::PrivateLinkage,
3375 Initializer,
3376 "switch.table");
3377 Array->setUnnamedAddr(true);
3378 Kind = ArrayKind;
3379}
3380
3381Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3382 switch (Kind) {
3383 case SingleValueKind:
3384 return SingleValue;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003385 case BitMapKind: {
3386 // Type of the bitmap (e.g. i59).
3387 IntegerType *MapTy = BitMap->getType();
3388
3389 // Cast Index to the same type as the bitmap.
3390 // Note: The Index is <= the number of elements in the table, so
3391 // truncating it to the width of the bitmask is safe.
Hans Wennborg50b7d702012-09-26 14:01:53 +00003392 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborgd72271c2012-09-26 09:44:49 +00003393
3394 // Multiply the shift amount by the element width.
3395 ShiftAmt = Builder.CreateMul(ShiftAmt,
3396 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3397 "switch.shiftamt");
3398
3399 // Shift down.
3400 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3401 "switch.downshift");
3402 // Mask off.
3403 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3404 "switch.masked");
3405 }
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003406 case ArrayKind: {
3407 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3408 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3409 "switch.gep");
3410 return Builder.CreateLoad(GEP, "switch.load");
3411 }
3412 }
3413 llvm_unreachable("Unknown lookup table kind!");
3414}
3415
Micah Villmow3574eca2012-10-08 16:38:25 +00003416bool SwitchLookupTable::WouldFitInRegister(const DataLayout *TD,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003417 uint64_t TableSize,
3418 const Type *ElementType) {
3419 if (!TD)
3420 return false;
3421 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3422 if (!IT)
3423 return false;
3424 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3425 // are <= 15, we could try to narrow the type.
Benjamin Kramer465251a2012-09-27 18:29:58 +00003426
3427 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3428 if (TableSize >= UINT_MAX/IT->getBitWidth())
3429 return false;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003430 return TD->fitsInLegalInteger(TableSize * IT->getBitWidth());
3431}
3432
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003433/// ShouldBuildLookupTable - Determine whether a lookup table should be built
3434/// for this switch, based on the number of caes, size of the table and the
3435/// types of the results.
3436static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003437 uint64_t TableSize,
Micah Villmow3574eca2012-10-08 16:38:25 +00003438 const DataLayout *TD,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003439 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003440 // The table density should be at least 40%. This is the same criterion as for
3441 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3442 // FIXME: Find the best cut-off.
Hans Wennborg565df792012-09-26 11:07:37 +00003443 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3444 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003445 if (SI->getNumCases() * 10 >= TableSize * 4)
3446 return true;
3447
Hans Wennborgd72271c2012-09-26 09:44:49 +00003448 // If each table would fit in a register, we should build it anyway.
3449 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3450 E = ResultTypes.end(); I != E; ++I) {
3451 if (!SwitchLookupTable::WouldFitInRegister(TD, TableSize, I->second))
3452 return false;
3453 }
3454 return true;
Hans Wennborg486270a2012-09-06 09:43:28 +00003455}
3456
3457/// SwitchToLookupTable - If the switch is only used to initialize one or more
3458/// phi nodes in a common successor block with different constant values,
3459/// replace the switch with lookup tables.
3460static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborgd72271c2012-09-26 09:44:49 +00003461 IRBuilder<> &Builder,
Micah Villmow3574eca2012-10-08 16:38:25 +00003462 const DataLayout* TD) {
Hans Wennborg486270a2012-09-06 09:43:28 +00003463 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3464 // FIXME: Handle unreachable cases.
3465
3466 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3467 // split off a dense part and build a lookup table for that.
3468
Hans Wennborg486270a2012-09-06 09:43:28 +00003469 // FIXME: This creates arrays of GEPs to constant strings, which means each
3470 // GEP needs a runtime relocation in PIC code. We should just build one big
3471 // string and lookup indices into that.
3472
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003473 // Ignore the switch if the number of cases is too small.
Hans Wennborg486270a2012-09-06 09:43:28 +00003474 // This is similar to the check when building jump tables in
3475 // SelectionDAGBuilder::handleJTSwitchCase.
3476 // FIXME: Determine the best cut-off.
3477 if (SI->getNumCases() < 4)
3478 return false;
3479
3480 // Figure out the corresponding result for each case value and phi node in the
3481 // common destination, as well as the the min and max case values.
3482 assert(SI->case_begin() != SI->case_end());
3483 SwitchInst::CaseIt CI = SI->case_begin();
3484 ConstantInt *MinCaseVal = CI.getCaseValue();
3485 ConstantInt *MaxCaseVal = CI.getCaseValue();
3486
3487 BasicBlock *CommonDest = NULL;
Hans Wennborg2f9fc762012-09-10 07:44:22 +00003488 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg486270a2012-09-06 09:43:28 +00003489 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3490 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3491 SmallDenseMap<PHINode*, Type*> ResultTypes;
3492 SmallVector<PHINode*, 4> PHIs;
3493
3494 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3495 ConstantInt *CaseVal = CI.getCaseValue();
3496 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3497 MinCaseVal = CaseVal;
3498 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3499 MaxCaseVal = CaseVal;
3500
3501 // Resulting value at phi nodes for this case value.
3502 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3503 ResultsTy Results;
3504 if (!GetCaseResults(SI, CI.getCaseSuccessor(), &CommonDest, Results))
3505 return false;
3506
3507 // Append the result from this case to the list for each phi.
3508 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3509 if (!ResultLists.count(I->first))
3510 PHIs.push_back(I->first);
3511 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3512 }
3513 }
3514
3515 // Get the resulting values for the default case.
Hans Wennborg2f9fc762012-09-10 07:44:22 +00003516 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3517 if (!GetCaseResults(SI, SI->getDefaultDest(), &CommonDest, DefaultResultsList))
3518 return false;
3519 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3520 PHINode *PHI = DefaultResultsList[I].first;
3521 Constant *Result = DefaultResultsList[I].second;
3522 DefaultResults[PHI] = Result;
3523 ResultTypes[PHI] = Result->getType();
Hans Wennborg486270a2012-09-06 09:43:28 +00003524 }
3525
3526 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
Hans Wennborg486270a2012-09-06 09:43:28 +00003527 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
Hans Wennborgd72271c2012-09-26 09:44:49 +00003528 if (!ShouldBuildLookupTable(SI, TableSize, TD, ResultTypes))
Hans Wennborg486270a2012-09-06 09:43:28 +00003529 return false;
3530
Hans Wennborg486270a2012-09-06 09:43:28 +00003531 // Create the BB that does the lookups.
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003532 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg486270a2012-09-06 09:43:28 +00003533 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3534 "switch.lookup",
3535 CommonDest->getParent(),
3536 CommonDest);
3537
3538 // Check whether the condition value is within the case range, and branch to
3539 // the new BB.
3540 Builder.SetInsertPoint(SI);
3541 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3542 "switch.tableidx");
3543 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3544 MinCaseVal->getType(), TableSize));
3545 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3546
3547 // Populate the BB that does the lookups.
3548 Builder.SetInsertPoint(LookupBB);
3549 bool ReturnedEarly = false;
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003550 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3551 PHINode *PHI = PHIs[I];
Hans Wennborg486270a2012-09-06 09:43:28 +00003552
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003553 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgd72271c2012-09-26 09:44:49 +00003554 DefaultResults[PHI], TD);
Hans Wennborgdb5dbf02012-09-26 09:34:53 +00003555
3556 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg486270a2012-09-06 09:43:28 +00003557
Hans Wennborg57933e32012-09-19 14:24:21 +00003558 // If the result is used to return immediately from the function, we want to
3559 // do that right here.
3560 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->use_begin()) &&
3561 *PHI->use_begin() == CommonDest->getFirstNonPHIOrDbg()) {
3562 Builder.CreateRet(Result);
3563 ReturnedEarly = true;
3564 break;
Hans Wennborg486270a2012-09-06 09:43:28 +00003565 }
3566
Hans Wennborg57933e32012-09-19 14:24:21 +00003567 PHI->addIncoming(Result, LookupBB);
Hans Wennborg486270a2012-09-06 09:43:28 +00003568 }
3569
3570 if (!ReturnedEarly)
3571 Builder.CreateBr(CommonDest);
3572
3573 // Remove the switch.
3574 for (unsigned i = 0; i < SI->getNumSuccessors(); ++i) {
3575 BasicBlock *Succ = SI->getSuccessor(i);
3576 if (Succ == SI->getDefaultDest()) continue;
3577 Succ->removePredecessor(SI->getParent());
3578 }
3579 SI->eraseFromParent();
3580
3581 ++NumLookupTables;
3582 return true;
3583}
3584
Devang Patel007349d2011-05-18 20:35:38 +00003585bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00003586 BasicBlock *BB = SI->getParent();
3587
Jakob Stoklund Olesene5a7a682012-10-25 18:51:15 +00003588 if (isValueEqualityComparison(SI)) {
3589 // If we only have one predecessor, and if it is a branch on this value,
3590 // see if that predecessor totally determines the outcome of this switch.
3591 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3592 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3593 return SimplifyCFG(BB) | true;
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00003594
Jakob Stoklund Olesene5a7a682012-10-25 18:51:15 +00003595 Value *Cond = SI->getCondition();
3596 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3597 if (SimplifySwitchOnSelect(SI, Select))
3598 return SimplifyCFG(BB) | true;
Frits van Bommelf7b2a9d2011-02-28 09:44:07 +00003599
Jakob Stoklund Olesene5a7a682012-10-25 18:51:15 +00003600 // If the block only contains the switch, see if we can fold the block
3601 // away into any preds.
3602 BasicBlock::iterator BBI = BB->begin();
3603 // Ignore dbg intrinsics.
3604 while (isa<DbgInfoIntrinsic>(BBI))
3605 ++BBI;
3606 if (SI == &*BBI)
3607 if (FoldValueComparisonIntoPredecessors(SI, Builder))
3608 return SimplifyCFG(BB) | true;
3609 }
Benjamin Kramer56442df2011-02-02 15:56:22 +00003610
3611 // Try to transform the switch into an icmp and a branch.
Devang Patel007349d2011-05-18 20:35:38 +00003612 if (TurnSwitchRangeIntoICmp(SI, Builder))
Benjamin Kramer56442df2011-02-02 15:56:22 +00003613 return SimplifyCFG(BB) | true;
Benjamin Kramer10fcfb52011-05-14 15:57:25 +00003614
3615 // Remove unreachable cases.
3616 if (EliminateDeadSwitchCases(SI))
3617 return SimplifyCFG(BB) | true;
3618
Hans Wennborg448da512011-06-18 10:28:47 +00003619 if (ForwardSwitchConditionToPHI(SI))
3620 return SimplifyCFG(BB) | true;
3621
Hans Wennborgd72271c2012-09-26 09:44:49 +00003622 if (SwitchToLookupTable(SI, Builder, TD))
Hans Wennborg486270a2012-09-06 09:43:28 +00003623 return SimplifyCFG(BB) | true;
3624
Chris Lattner3d512132010-12-13 06:25:44 +00003625 return false;
3626}
3627
3628bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3629 BasicBlock *BB = IBI->getParent();
3630 bool Changed = false;
Andrew Trick6b014382012-08-29 21:46:36 +00003631
Chris Lattner3d512132010-12-13 06:25:44 +00003632 // Eliminate redundant destinations.
3633 SmallPtrSet<Value *, 8> Succs;
3634 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3635 BasicBlock *Dest = IBI->getDestination(i);
3636 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3637 Dest->removePredecessor(BB);
3638 IBI->removeDestination(i);
3639 --i; --e;
3640 Changed = true;
3641 }
Andrew Trick6b014382012-08-29 21:46:36 +00003642 }
Chris Lattner3d512132010-12-13 06:25:44 +00003643
3644 if (IBI->getNumDestinations() == 0) {
3645 // If the indirectbr has no successors, change it to unreachable.
3646 new UnreachableInst(IBI->getContext(), IBI);
3647 EraseTerminatorInstAndDCECond(IBI);
3648 return true;
3649 }
Andrew Trick6b014382012-08-29 21:46:36 +00003650
Chris Lattner3d512132010-12-13 06:25:44 +00003651 if (IBI->getNumDestinations() == 1) {
3652 // If the indirectbr has one successor, change it to a direct branch.
3653 BranchInst::Create(IBI->getDestination(0), IBI);
3654 EraseTerminatorInstAndDCECond(IBI);
3655 return true;
3656 }
Andrew Trick6b014382012-08-29 21:46:36 +00003657
Chris Lattner3d512132010-12-13 06:25:44 +00003658 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3659 if (SimplifyIndirectBrOnSelect(IBI, SI))
3660 return SimplifyCFG(BB) | true;
3661 }
3662 return Changed;
3663}
3664
Devang Patela23812c2011-05-18 18:28:48 +00003665bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner3d512132010-12-13 06:25:44 +00003666 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00003667
Manman Ren554da1a2012-09-20 22:37:36 +00003668 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3669 return true;
3670
Chris Lattner3d512132010-12-13 06:25:44 +00003671 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindola77a2c372011-06-30 20:14:24 +00003672 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
Chris Lattner3d512132010-12-13 06:25:44 +00003673 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3674 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3675 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003676
Chris Lattner3d512132010-12-13 06:25:44 +00003677 // If the only instruction in the block is a seteq/setne comparison
3678 // against a constant, try to simplify the block.
3679 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3680 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3681 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3682 ;
Nick Lewycky9d523102011-12-26 20:37:40 +00003683 if (I->isTerminator() &&
3684 TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003685 return true;
3686 }
Andrew Trick6b014382012-08-29 21:46:36 +00003687
Manman Renee28e0f2012-06-13 05:43:29 +00003688 // If this basic block is ONLY a compare and a branch, and if a predecessor
3689 // branches to us and our successor, fold the comparison into the
3690 // predecessor and use logical operations to update the incoming value
3691 // for PHI nodes in common successor.
3692 if (FoldBranchToCommonDest(BI))
3693 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00003694 return false;
3695}
3696
3697
Devang Patel007349d2011-05-18 20:35:38 +00003698bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner3d512132010-12-13 06:25:44 +00003699 BasicBlock *BB = BI->getParent();
Andrew Trick6b014382012-08-29 21:46:36 +00003700
Chris Lattner3d512132010-12-13 06:25:44 +00003701 // Conditional branch
3702 if (isValueEqualityComparison(BI)) {
3703 // If we only have one predecessor, and if it is a branch on this value,
3704 // see if that predecessor totally determines the outcome of this
3705 // switch.
3706 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patel007349d2011-05-18 20:35:38 +00003707 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003708 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003709
Chris Lattner3d512132010-12-13 06:25:44 +00003710 // This block must be empty, except for the setcond inst, if it exists.
3711 // Ignore dbg intrinsics.
3712 BasicBlock::iterator I = BB->begin();
3713 // Ignore dbg intrinsics.
3714 while (isa<DbgInfoIntrinsic>(I))
3715 ++I;
3716 if (&*I == BI) {
Devang Patelb55d9242011-05-18 20:53:17 +00003717 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003718 return SimplifyCFG(BB) | true;
3719 } else if (&*I == cast<Instruction>(BI->getCondition())){
3720 ++I;
3721 // Ignore dbg intrinsics.
3722 while (isa<DbgInfoIntrinsic>(I))
3723 ++I;
Devang Patelb55d9242011-05-18 20:53:17 +00003724 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003725 return SimplifyCFG(BB) | true;
3726 }
3727 }
Andrew Trick6b014382012-08-29 21:46:36 +00003728
Chris Lattner3d512132010-12-13 06:25:44 +00003729 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Devang Patel02dd5412011-05-18 23:18:47 +00003730 if (SimplifyBranchOnICmpChain(BI, TD, Builder))
Chris Lattner3d512132010-12-13 06:25:44 +00003731 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003732
Dan Gohman3b205172012-01-05 23:58:56 +00003733 // If this basic block is ONLY a compare and a branch, and if a predecessor
3734 // branches to us and one of our successors, fold the comparison into the
3735 // predecessor and use logical operations to pick the right destination.
3736 if (FoldBranchToCommonDest(BI))
3737 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003738
Chris Lattner3d512132010-12-13 06:25:44 +00003739 // We have a conditional branch to two blocks that are only reachable
3740 // from BI. We know that the condbr dominates the two blocks, so see if
3741 // there is any identical code in the "then" and "else" blocks. If so, we
3742 // can hoist it up to the branching block.
3743 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
3744 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
Rafael Espindola216dde92011-05-19 02:26:30 +00003745 if (HoistThenElseCodeToIf(BI))
Chris Lattner3d512132010-12-13 06:25:44 +00003746 return SimplifyCFG(BB) | true;
3747 } else {
3748 // If Successor #1 has multiple preds, we may be able to conditionally
3749 // execute Successor #0 if it branches to successor #1.
3750 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
3751 if (Succ0TI->getNumSuccessors() == 1 &&
3752 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Rafael Espindola216dde92011-05-19 02:26:30 +00003753 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
Chris Lattner3d512132010-12-13 06:25:44 +00003754 return SimplifyCFG(BB) | true;
3755 }
3756 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
3757 // If Successor #0 has multiple preds, we may be able to conditionally
3758 // execute Successor #1 if it branches to successor #0.
3759 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
3760 if (Succ1TI->getNumSuccessors() == 1 &&
3761 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Rafael Espindola216dde92011-05-19 02:26:30 +00003762 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
Chris Lattner3d512132010-12-13 06:25:44 +00003763 return SimplifyCFG(BB) | true;
3764 }
Andrew Trick6b014382012-08-29 21:46:36 +00003765
Chris Lattner3d512132010-12-13 06:25:44 +00003766 // If this is a branch on a phi node in the current block, thread control
3767 // through this block if any PHI node entries are constants.
3768 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
3769 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00003770 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00003771 return SimplifyCFG(BB) | true;
Andrew Trick6b014382012-08-29 21:46:36 +00003772
Chris Lattner3d512132010-12-13 06:25:44 +00003773 // Scan predecessor blocks for conditional branches.
3774 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
3775 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
3776 if (PBI != BI && PBI->isConditional())
3777 if (SimplifyCondBranchToCondBranch(PBI, BI))
3778 return SimplifyCFG(BB) | true;
3779
3780 return false;
3781}
3782
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003783/// Check if passing a value to an instruction will cause undefined behavior.
3784static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
3785 Constant *C = dyn_cast<Constant>(V);
3786 if (!C)
3787 return false;
3788
Benjamin Kramer1e21db62012-10-04 16:11:49 +00003789 if (I->use_empty())
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003790 return false;
3791
3792 if (C->isNullValue()) {
Benjamin Kramer1e21db62012-10-04 16:11:49 +00003793 // Only look at the first use, avoid hurting compile time with long uselists
3794 User *Use = *I->use_begin();
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003795
3796 // Now make sure that there are no instructions in between that can alter
3797 // control flow (eg. calls)
3798 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003799 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003800 return false;
3801
3802 // Look through GEPs. A load from a GEP derived from NULL is still undefined
3803 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
3804 if (GEP->getPointerOperand() == I)
3805 return passingValueIsAlwaysUndefined(V, GEP);
3806
3807 // Look through bitcasts.
3808 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
3809 return passingValueIsAlwaysUndefined(V, BC);
3810
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003811 // Load from null is undefined.
3812 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
3813 return LI->getPointerAddressSpace() == 0;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003814
Benjamin Kramer9bb54882011-08-26 02:25:55 +00003815 // Store to null is undefined.
3816 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
3817 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003818 }
3819 return false;
3820}
3821
3822/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewycky9d523102011-12-26 20:37:40 +00003823/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003824static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
3825 for (BasicBlock::iterator i = BB->begin();
3826 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
3827 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
3828 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
3829 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
3830 IRBuilder<> Builder(T);
3831 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
3832 BB->removePredecessor(PHI->getIncomingBlock(i));
3833 // Turn uncoditional branches into unreachables and remove the dead
3834 // destination from conditional branches.
3835 if (BI->isUnconditional())
3836 Builder.CreateUnreachable();
3837 else
3838 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
3839 BI->getSuccessor(0));
3840 BI->eraseFromParent();
3841 return true;
3842 }
3843 // TODO: SwitchInst.
3844 }
3845
3846 return false;
3847}
3848
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003849bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00003850 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003851
Chris Lattner302ba6f2010-12-14 06:17:25 +00003852 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003853 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00003854
Dan Gohmane2c6d132010-08-14 00:29:42 +00003855 // Remove basic blocks that have no predecessors (except the entry block)...
3856 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00003857 if ((pred_begin(BB) == pred_end(BB) &&
3858 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00003859 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00003860 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00003861 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00003862 return true;
3863 }
3864
Chris Lattner694e37f2003-08-17 19:41:53 +00003865 // Check to see if we can constant propagate this terminator instruction
3866 // away...
Frits van Bommel5649ba72011-05-22 16:24:18 +00003867 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner694e37f2003-08-17 19:41:53 +00003868
Dan Gohman2c635662009-10-30 22:39:04 +00003869 // Check for and eliminate duplicate PHI nodes in this block.
3870 Changed |= EliminateDuplicatePHINodes(BB);
3871
Benjamin Kramer98d6d232011-08-26 01:22:29 +00003872 // Check for and remove branches that will always cause undefined behavior.
3873 Changed |= removeUndefIntroducingPredecessor(BB);
3874
Chris Lattnerddb97a22010-12-13 05:10:48 +00003875 // Merge basic blocks into their predecessor if there is only one distinct
3876 // pred, and if there is only one distinct successor of the predecessor, and
3877 // if there are no PHI nodes.
3878 //
3879 if (MergeBlockIntoPredecessor(BB))
3880 return true;
Andrew Trick6b014382012-08-29 21:46:36 +00003881
Devang Patel3e410c62011-05-18 18:01:27 +00003882 IRBuilder<> Builder(BB);
3883
Dan Gohman882d87d2008-03-11 21:53:06 +00003884 // If there is a trivial two-entry PHI node in this basic block, and we can
3885 // eliminate it, do so now.
3886 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
3887 if (PN->getNumIncomingValues() == 2)
Devang Pateld3a17882011-05-19 20:52:46 +00003888 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00003889
Devang Patel007349d2011-05-18 20:35:38 +00003890 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner3d512132010-12-13 06:25:44 +00003891 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00003892 if (BI->isUnconditional()) {
Devang Patela23812c2011-05-18 18:28:48 +00003893 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003894 } else {
Devang Patel007349d2011-05-18 20:35:38 +00003895 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003896 }
3897 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel176ec402011-05-18 21:33:11 +00003898 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingaa5abe82012-02-06 21:16:41 +00003899 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
3900 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003901 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patel007349d2011-05-18 20:35:38 +00003902 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003903 } else if (UnreachableInst *UI =
3904 dyn_cast<UnreachableInst>(BB->getTerminator())) {
3905 if (SimplifyUnreachable(UI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00003906 } else if (IndirectBrInst *IBI =
3907 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
3908 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00003909 }
3910
Chris Lattner694e37f2003-08-17 19:41:53 +00003911 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00003912}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003913
3914/// SimplifyCFG - This function is used to do simplification of a CFG. For
3915/// example, it adjusts branches to branches to eliminate the extra hop, it
3916/// eliminates unreachable basic blocks, and does other "peephole" optimization
3917/// of the CFG. It returns true if a modification was made.
3918///
Micah Villmow3574eca2012-10-08 16:38:25 +00003919bool llvm::SimplifyCFG(BasicBlock *BB, const DataLayout *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00003920 return SimplifyCFGOpt(TD).run(BB);
3921}